python - 在 python 中使用动态列名将不同的数组保存在单个 csv 文件中
问题描述
我的数据表有 250 列,列名为“1”...“250”。在对每一列进行随机抽样后,我想将所有抽样列保存在一个 csv 文件中,其列名与数据表中的列名相同。
for i in range(1,250):
z=np.random.choice(df[i], len(df), replace=False)
如何进行?
解决方案
我相信需要分配回每一列,然后写入csv
:to_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
推荐阅读
- html - 如何填充边距的整个背景颜色?
- https - 服务器和客户端在客户机器上运行,我应该使用 HTTPS,如何使用?
- amazon-web-services - 忽略自动生成的 AWS Amplify 文件
- swift - 为 ARKit(不是 QLPreview)材质属性加载 USDZ
- c# - 根据数组成员的其他属性,在 Unity 编辑器中显示数组成员的某些属性
- html - 假设边框和背景是可见的,那么元素可见部分的高度是多少?
- javascript - onClick 中带有正斜杠的 HTML 提交按钮
- sql - oracle中的外部应用转换
- java - 我想使用java作为Web服务器在android中制作登录应用程序,并在没有查询字符串的情况下在java中传递控件值
- math - 组合分析