![](/img/trans.png)
[英]Adding a column to multiple .csv files with the file name as you combine those .csv files into a single dataframe
[英]Combine multiple csv files column wise with the header as file name
我在平台上找不到确切的代码,这就是为什么发布它以征求建议。
我有多个 CSV 文件(大约 100 个)具有相同的数据格式和 header 名称。
,Mean,SD
1,96.432,13.899
2,96.432,13.899
3,96.432,13.899
4,96.432,13.899
5,96.432,13.899
我想按列对所有文件进行 append ,以便将它们放在一个文件中。 另外,每个数据的 header 应该是文件名,以便我可以跟踪哪些数据属于哪个文件。 比如上面的意思,sd-->文件名的另一行。
请指导我,因为我是 Python 的新手。
谢谢你和问候,汗。
问题是关于格式的模糊,所以这可能与所需的 output 不同。
filenames = [...]
dfs = []
for f in filenames:
newdf = pd.read_csv(f)
newdf.rename(columns={'Mean': 'Mean ' + f, 'SD': 'SD ' + f})
dfs.append(newdf)
df = pd.concat(dfs)
您可以使用pandas
以及glob
和字典理解来读取和连接文件:
from glob import glob
import pandas as pd
files = glob('/tmp/*.csv') # change the location/pattern accordingly
# if you have a list of files, use: files=['file1.csv', 'file2.csv'...]
df = pd.concat({fname.rsplit('/')[-1]: pd.read_csv(fname, index_col=0)
for fname in files}, axis=1)
output:
>>> print(df)
file1.csv file2.csv
Mean SD Mean SD
1 96.432 13.899 96.432 13.899
2 96.432 13.899 96.432 13.899
3 96.432 13.899 96.432 13.899
4 96.432 13.899 96.432 13.899
5 96.432 13.899 96.432 13.899
保存到新文件:
df.to_csv('concatenated_file.csv')
output:
,file1.csv,file1.csv,file2.csv,file2.csv
,Mean,SD,Mean,SD
,,,,
1,96.432,13.899,96.432,13.899
2,96.432,13.899,96.432,13.899
3,96.432,13.899,96.432,13.899
4,96.432,13.899,96.432,13.899
5,96.432,13.899,96.432,13.899
您可以使用 pandas 与
In [3]: import pandas
In [4]: import pandas as pd
In [13]: ls
abc1.csv abc.csv
In [14]: df = pd.read_csv('abc.csv')
In [15]: df1 = pd.read_csv('abc1.csv')
In [16]: df
Out[16]:
Mean SD
0 1 96.432 13.899
1 2 96.432 13.899
In [16]: df
Out[16]:
Mean SD
0 1 96.432 13.899
1 2 96.432 13.899
In [17]: df1
Out[17]:
Mean SD
0 3 96.432 13.899
1 4 96.432 13.899
2 5 96.432 13.899
In [18]: df.append(df1)
Out[18]:
Mean SD
0 1 96.432 13.899
1 2 96.432 13.899
0 3 96.432 13.899
1 4 96.432 13.899
2 5 96.432 13.899
In [19]: ds = df.append(df1)
In [20]: ds
Out[20]:
Mean SD
0 1 96.432 13.899
1 2 96.432 13.899
0 3 96.432 13.899
1 4 96.432 13.899
2 5 96.432 13.899
In [21]: ds.to_csv('file1.csv')
In [23]: ls
abc1.csv abc.csv file1.csv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.