为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

温温酱 2022-06-14 10:08:24
我正在尝试将特定列的 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)`任何帮助,将不胜感激。注意:总计必须在文件顶部的标题之前。我期待以下输出:
查看完整描述

2 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

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

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


查看完整回答
反对 回复 2022-06-14
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

您可以先创建一个带有标头信息的数据框,然后以附加模式将其与数据框一起写入 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)


查看完整回答
反对 回复 2022-06-14
  • 2 回答
  • 0 关注
  • 106 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号