python - 将熊猫数据框每列的总数(总和,计数)添加到 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)`
任何帮助,将不胜感激。
注意:总计必须在文件顶部的标题之前。
我期待以下输出:
解决方案
提示:如果您不提供 的路径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)
现在您不必计算逗号的数量!
推荐阅读
- python - 在 vscode 中使用 python anaconda 作为我的解释器时无法安装格式化程序
- c# - IFormFile 在 ASP.NET Core 3.0 MVC 中始终为 NULL
- python - 如何在没有滑雪套件学习的情况下为 K 折交叉验证创建训练集?
- python - tkinter 滚动区域不更新
- reactjs - 自定义 Lottie 动画在 React Native 中不起作用
- javascript - 试图从 mongoose 的请求中获取一个空对象以正确处理错误
- windows - net use 在没有用户名和密码的情况下工作,但是当我定义它们时,它给出了系统错误 87 已发生
- html - 如何将内容放在固定标题下方
- swift - 是否可以将 Combine 与 NSManagedObject 的单个字段一起使用?
- ios - 试图理解苹果的状态码定义