第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將熊貓數(shù)據(jù)框每列的總數(shù)(總和,計數(shù))添加到 csv 文件中

將熊貓數(shù)據(jù)框每列的總數(shù)(總和,計數(shù))添加到 csv 文件中

溫溫醬 2022-06-14 10:08:24
我正在嘗試將特定列的 Sum/Count 添加到 pandas 數(shù)據(jù)幀,然后再將其寫入 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)`任何幫助,將不勝感激。注意:總計必須在文件頂部的標(biāo)題之前。我期待以下輸出:
查看完整描述

2 回答

?
飲歌長嘯

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個贊

提示:如果您不提供 的路徑to_csv,該函數(shù)將返回一個字符串。您可以使用此字符串手動構(gòu)建您的 CSV 內(nèi)容。


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)

現(xiàn)在您不必計算逗號的數(shù)量!


查看完整回答
反對 回復(fù) 2022-06-14
?
拉風(fēng)的咖菲貓

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個贊

您可以先創(chuàng)建一個帶有標(biāo)頭信息的數(shù)據(jù)框,然后以附加模式將其與數(shù)據(jù)框一起寫入 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)


查看完整回答
反對 回復(fù) 2022-06-14
  • 2 回答
  • 0 關(guān)注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號