![](/img/trans.png)
[英]Split huge file into n files keeping first 7 columns + next 3 columns until column n
[英]Python or Unix/Bash. Split big dataframe into individual columns keeping first n columns
我有一个很大的 dataframe (df) X,有 n 列(~30000),~2000 行和列名,如下所示:
A,B,C,D,F,G,H,v1,453,73v,4-5,ss,9-dd,...,n
X 的元素是整数、浮点数和字符串的混合。
使用 python 或 unix/bash,我想将 X 拆分为 n-7 dfs。 每个生成的 df 将保留 X 的前 7 列 + X 的下一个单列。因此,前 3 个 df 将具有以下列:
A,B,C,D,F,G,H,v1
A,B,C,D,F,G,H,453
A,B,C,D,F,G,H,73v
等等...
我希望每个生成的 dfs 保留其最后一列的名称 +“.txt”。 因此,前三个 df 将被称为“v1.txt”、“453.txt”和“73v.txt”。
这篇文章有点类似于:将大文件拆分为 n 个文件,保留前 7 列 + 后 3 列,直到第 n 列
但我无法适应它。
您可以进行如下操作:
import pandas as pd
import numpy as np
np.random.seed(42)
df = pd.DataFrame({'A': np.random.randint(0, 100, 10),
'B': np.random.randint(0, 100, 10),
'C': np.random.randint(0, 100, 10),
'D': np.random.randint(0, 100, 10),
'F': np.random.randint(0, 100, 10),
'G': np.random.randint(0, 100, 10),
'H': np.random.randint(0, 100, 10),
'v1': np.random.randint(0, 100, 10),
'453': np.random.randint(0, 100, 10),
'73v': np.random.randint(0, 100, 10)})
for i in range(7, df.shape[1]):
sub_df = df.iloc[:, np.r_[0:7, i]]
sub_df.to_csv(f'{df.columns[i]}.txt', sep='\t')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.