【问题标题】:Adding a Grand Total Line to a dataframe to CSV output将总计行添加到数据帧以 CSV 输出
【发布时间】:2021-05-16 08:13:47
【问题描述】:

我有一个包含以下数据的 CSV 文件:

Product Date Company Revenue
A 2/1/2021 1230 24314
A 2/1/2021 1224 14222
B 2/1/2021 1442 24141
B 2/1/2021 1424 54352
B 2/1/2021 4919 12213
C 2/1/2021 2312 43536
C 2/1/2021 2322 24241
D 2/1/2021 1131 34532
E 2/1/2021 1414 45645
E 2/1/2021 7674 21321

我有一个脚本可以过滤每个产品,然后为该产品创建一个 CSV:

report_import = (r’path\product_report.csv")

report_df = pd.read_csv(report_import, sep='\t',encoding="utf16")

# Get all available products
products = set(report_df[‘Product’])

for product in products:
    #Perform a filter for each product
    temp_df = report_df[report_df[‘Product’] == product]
    temp_df.to_csv(r"path\" + product + ".csv", index=False) 

如何添加显示收入列总和的总计行?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    只需添加一行

    temp_df['grand total'] = temp_df.Revenue.sum() 
    

    【讨论】:

    • 这将添加一列总计。问题是将总数作为一行。
    【解决方案2】:

    我建议这个答案。您需要将数据框末尾的收入列的总和作为新的原始数据。

    def test_new():
     df = pd.read_csv(r'D:\myfolder\prodc.csv')     
     df.loc['Total','Revenue']= df['Revenue'].sum()
     print(df)
    

    test_new()

    【讨论】:

    • 总行是否可以不包含在索引中?
    • @MaxLee 你的意思是单独一行?
    猜你喜欢
    • 2023-03-23
    • 2018-08-03
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多