猿问

将熊猫数据框每列的总数(总和,计数)添加到 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)`

任何帮助,将不胜感激。


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


我期待以下输出:

温温酱
浏览 107回答 2
2回答

饮歌长啸

提示:如果您不提供 的路径to_csv,该函数将返回一个字符串。您可以使用此字符串手动构建您的 CSV 内容。summary = df.agg({    'E': 'count',    'F': 'sum',    'T': 'sum'})summary = summary.reindex(df.columns).to_frame().Theader = 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)现在您不必计算逗号的数量!

拉风的咖菲猫

您可以先创建一个带有标头信息的数据框,然后以附加模式将其与数据框一起写入 csv:import pandas as pddf = 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().Twith open(out_path, 'a') as f:    header.to_csv(f, header=False, index=False)    df.to_csv(f, index=False)
随时随地看视频慕课网APP

相关分类

Python
我要回答