如何合并几个csv文件平均字段?

时间:2019-07-24 22:58:56

标签: python python-3.x pandas csv

我有几个csv文件,分别是file1,file2,file3等。它们看起来都像这样(完全相同,只有float有所变化):

filename,    column1,  column2, ... columnN
asdfasd.jpg   23.23,    21.24,        1e-06
ersdadfsd.jpg 223.23,   1.23,         1
assd.jpg      23.23,    1e-08,       232.1
...

我想得到一个相同的表,其中所有字段均包含均值。如何有效地做到这一点?

1 个答案:

答案 0 :(得分:1)

all_csv = []
for one_file in list_of_file:
    all_csv.append(pd.read_csv(one_file))
df = pd.concat(all_csv).groupby('filename').mean()

应该想要你想要的。

例如,有两个csv:

>>> df1 = pd.DataFrame({'name': ['a', 'b'], 'v1': [1, 2,], 'v2': [3, 4]}) # your first csv
>>> df2 = pd.DataFrame({'name': ['a', 'b'], 'v1': [5, 6,], 'v2': [7, 8]}) # your second csv
>>> df3 = pd.concat([df1, df2])
>>> df3
  name  v1  v2
0    a   1   3
1    b   2   4
0    a   5   7
1    b   6   8
>>> df3.groupby('name').mean() 
# create sub dataframe with only the same name values (a and b) and 
# the mean compute the mean on this sub dataframe column by column.