我的数据表有 250 列,列名称为“1”...“250”。对每列进行随机采样后,我想将所有采样的列保存在一个 csv 文件中,其列名称与数据表中的列名称相同。
for i in range(1,250):
z=np.random.choice(df[i], len(df), replace=False)
如何进行?
最佳答案
我认为需要分配回每一列,然后通过to_csv
写入csv
:
for i in range(1,250):
df[i]=np.random.choice(df[i], len(df), replace=False)
df.to_csv(file, index=False)
另一个解决方案 sample
:
df1 = df.sample(len(df.columns), replace=False)
df.to_csv(file, index=False)
示例:
df = pd.DataFrame(np.random.randint(30, size=(5,4))).rename(columns=lambda x: x+1)
print (df)
1 2 3 4
0 12 10 2 14
1 9 14 28 4
2 9 11 14 8
3 22 8 2 9
4 28 3 23 6
df1 = df.sample(len(df.columns), axis=0, replace=False)
print (df1)
1 2 3 4
3 22 8 2 9
0 12 10 2 14
2 9 11 14 8
4 28 3 23 6
for i in range(1,5):
df[i]=np.random.choice(df[i], len(df), replace=False)
print (df)
1 2 3 4
0 28 11 23 8
1 22 3 2 14
2 9 10 28 4
3 9 8 14 9
4 12 14 2 6
关于python - 在Python中使用动态列名将不同的数组保存在单个csv文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239099/