首页 > 解决方案 > 在 python 中使用动态列名将不同的数组保存在单个 csv 文件中

问题描述

我的数据表有 250 列,列名为“1”...“250”。在对每一列进行随机抽样后,我想将所有抽样列保存在一个 csv 文件中,其列名与数据表中的列名相同。

for i in range(1,250):
   z=np.random.choice(df[i], len(df), replace=False)

如何进行?

标签: pythonpandasnumpy

解决方案


我相信需要分配回每一列,然后写入csvto_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

推荐阅读