【问题标题】:How to add data to CSV columns, one by one using pandas如何使用 pandas 将数据一一添加到 CSV 列
【发布时间】:2021-07-19 22:37:02
【问题描述】:

我有一个熊猫脚本如下。我正在读取给定文件夹中的多个 csv 文件。所有 csv 文件都具有相似的格式和列。 对于给定的列(区域),我想添加所有行。然后我想将这些数据保存到一个新的 CSV 文件中。

这是目前为止的代码。

import pandas as pd
import glob

path = r'C:\Users\kundemj\Desktop\Post_Processing\HEA517_2000' # path
all_files = glob.glob(path + "/*.csv")

for filename in all_files:
    df = pd.read_csv(filename)
    area_sum = df['Area'].sum()
    print(area_sum)

我可以通过使用 excel_write 函数弄清楚,但我想使用 'to_csv' 以及 mode = 'append',因为我有一堆具有相同文件名的文件夹。

我要找的CSV文件格式如下:

filename1, filename2, filename3,.....
area_sum1, area_sum2, area_sum3,.....

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以试试这个:

    import pandas as pd
    import glob
    
    path = r'C:\Users\kundemj\Desktop\Post_Processing\HEA517_2000' # path
    all_files = glob.glob(path + "/*.csv")
    
    # Create an empty dict
    results = {"filename": [], "sum": []}
    
    # Iterate on files and populate the newly created dict
    for filename in all_files:
        results["filename"].append(filename)
        df = pd.read_csv(filename)
        results["sum"].append(df['Area'].sum())
    
    # Save to csv file
    results = pd.DataFrame(results)
    results.to_csv(path="path_to_file.csv", index=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 2012-03-02
      • 1970-01-01
      相关资源
      最近更新 更多