首页 > 解决方案 > 将熊猫数据框每列的总数(总和,计数)添加到 csv 文件中

问题描述

我正在尝试将特定列的 Sum/Count 添加到 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)`

任何帮助,将不胜感激。

注意:总计必须在文件顶部的标题之前。

我期待以下输出:

示例数据框

标签: pythonpython-3.xpandas

解决方案


提示:如果您不提供 的路径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)

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


推荐阅读