将熊猫数据帧每一列的总计(总和,计数)添加到csv文件

时间:2019-10-03 16:19:14

标签: python python-3.x pandas

我正在尝试将特定列的总和/计数添加到pandas数据框,然后再将其写入csv文件。我想出了一个非常精致的解决方案,想知道是否有人可以提出更好的方法。

`df.to_csv(out_path, index=False)
 #reading content of csv file
 with open(out_path,'r') as my_file:
     content = my_file.read()
 #adding comma in the line below adjust cell in csv file and appending content of pandas dataframe after writing aggregate total/sum. 
 with open(out_path,'w') as my_file:
     my_file.write(',,,,'+str(df['E'].count()))
     my_file.write(','+ str(df['F'].astype(float).sum()))
     my_file.write(',,,,,,,,,,,,,,'+ str(df['T'].astype(float).sum()))
     my_file.write('\n')
     my_file.write(content)`

任何帮助将不胜感激。

注意:Total必须在文件头之前的文件顶部。

我期望以下输出:

Sample Dataframe

2 个答案:

答案 0 :(得分:1)

提示::如果不提供指向to_csv的路径,则该函数将返回一个字符串。您可以使用此字符串来手动构建CSV内容。

summary = df.agg({
    'E': 'count',
    'F': 'sum',
    'T': 'sum'
})
summary = summary.reindex(df.columns).to_frame().T

header = summary.to_csv(index=False, header=False)
body = df.to_csv(index=False)

with open(out_path, 'w') as f:
    f.write(header)
    f.write(body)

现在您不必计算逗号的数量!

答案 1 :(得分:0)

您可以首先使用标头信息创建一个数据框,然后将其与该数据框一起以追加模式写入csv:

import pandas as pd
df = pd.DataFrame([[2,4,6,2,3,9],[3,5,2,1,5,7],[4,6,8,9,0,4]], columns=list('ABCEFT'))

header = pd.Series(df.agg({'E': len, 'F': sum, 'T': sum}), index=df.columns).to_frame().T

with open(out_path, 'a') as f:
    header.to_csv(f, header=False, index=False)
    df.to_csv(f, index=False)