替换熊猫中的列



我有一个数据帧,它有80列。我想用不同的值替换一些随机列。我找到了一些解决方案,我们使用df["c"]=mylist。但是,如果我想随机选择一列,但我不知道列名,该怎么办。比如colNum = 12,然后我做df[colNum] = mylist。这是我尝试过但没有成功的代码:

def poisonData(data):
newValues = []
for i in range(6):
colNum = np.random.randint(0,81)
temp=data.iloc[:,colNum]
for x in temp:
newValues.append(float(x*colNum))
se = pd.Series(newValues)
data.columns[colNum] = se.values
return data

我也试过CCD_ 3。我找不出我做错了什么:(

您可以使用random.sample,然后使用.iloc来选择任何不重复的列:

>>> index_of_random_cols = random.sample(range(len(df.columns)), 6)
>>> df.iloc[:, index_of_random_cols]

然后,您可以使用随机值的numpy数组来填充这些列:

... = np.random.rand(len(df.index), 6)

结果代码:

>>> N_cols = 6
>>> index_of_random_cols = random.sample(range(len(df.columns)), 6)
>>> df.iloc[:, index_of_random_cols] = index_of_random_cols * np.random.rand(len(df.index), N_cols)

使用numpy.random.choice随机选择N列:

N = 3
cols = np.random.choice(df.columns, size=N, replace=False)

然后,循环:

for col in columns: 
df[col] # do something

或具有矢量函数:

df[cols] = df[cols].apply(something)
# OR
df[cols] = func(df[cols])

最新更新