且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

读取多个csv文件并将文件名添加为pandas中的新列

更新时间:2022-05-23 08:53:45

我认为您需要 concat 用于删除index中的重复项:

I think you need assign for add new column in loop, also parameter ignore_index=True was added to concat for remove duplicates in index:

要测试的文件为 a.csv b.csv


files = glob.glob('files/*.csv')
df = pd.concat([pd.read_csv(fp).assign(New=os.path.basename(fp).split('.')[0]) for fp in files])
print (df)
   a  b  c  d New
0  0  1  2  5   a
1  1  5  8  3   a
2  0  9  6  5   b
3  1  6  4  2   b
4  0  7  1  7   c
5  1  3  2  6   c