Merge CSVs in Python with different columns

后端 未结 4 941
栀梦
栀梦 2021-02-05 18:47

I have hundreds of large CSV files that I would like to merge into one. However, not all CSV files contain all columns. Therefore, I need to merge files based on column name, no

4条回答
  •  半阙折子戏
    2021-02-05 19:46

    You can use the pandas module to do this pretty easily. This snippet assumes all your csv files are in the current folder.

    import pandas as pd
    import os
    
    all_csv = [file_name for file_name in os.listdir(os.getcwd()) if '.csv' in file_name]
    
    li = []
    
    for filename in all_csv:
        df = pd.read_csv(filename, index_col=None, header=0, parse_dates=True, infer_datetime_format=True)
        li.append(df)
    
    frame = pd.concat(li, axis=0, ignore_index=True)
    frame.to_csv('melted_csv.csv', index=False)
    

提交回复
热议问题