Python Pandas add Filename Column CSV

前端 未结 2 413
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 09:42

My python code works correctly in the below example. My code combines a directory of CSV files and matches the headers. However, I want to take it a step further - how do I

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 10:42

    This should work:

    import os
    
    for csv in globbed_files:
        frame = pd.read_csv(csv)
        frame['filename'] = os.path.basename(csv)
        data.append(frame)
    

    frame['filename'] creates a new column named filename and os.path.basename() turns a path like /a/d/c.txt into the filename c.txt.

提交回复
热议问题