合并两个CSV并将其名称附加在第一栏中

时间:2019-12-03 11:59:43

标签: python python-3.x pandas

我有两个CSV文件,我希望无条件附加它们。

即:

CSV1
TS,AA,BB,CC,DD,EE,FF,GG,HH,II
12:13:06.366,1.72,1,1,1.66,1.76,41913977,C,13,45
13:13:06.366,1.55,2,3,1.55,1.59,62384783,C,156,1
14:13:06.366,1.55,2,5,1.5,1.55,63161255,C,17,20

CSV2
TS,AA,BB,CC,DD,EE,FF,GG,HH,II
13:37:27.483,0.54,1,1,0.1,1,3058525,C,13,45
14:37:27.483,0.54,1,2,0.1,1,3058525,O,13,45
15:37:27.483,0.8,29,31,0.4,0.85,77148452,C,17,27


Output I need is:
FileName,TS,AA,BB,CC,DD,EE,FF,GG,HH,II
CSV1,12:13:06.366,1.72,1,1,1.66,1.76,41913977,C,13,45
CSV1,13:13:06.366,1.55,2,3,1.55,1.59,62384783,C,156,1
CSV1,14:13:06.366,1.55,2,5,1.5,1.55,63161255,C,17,20
CSV2,13:37:27.483,0.54,1,1,0.1,1,3058525,C,13,45
CSV2,14:37:27.483,0.54,1,2,0.1,1,3058525,O,13,45
CSV2,15:37:27.483,0.8,29,31,0.4,0.85,77148452,C,17,27

我得到的输出如下所示。第一列正在转换为索引。

             TS,AA,BB,CC,DD,EE,FF,GG,HH,II,UNKNOWN,Name
12:13:06.366,1.72,1,1,1.66,1.76,41913977,C,13,45,NULL,CSV1
13:13:06.366,1.55,2,3,1.55,1.59,62384783,C,156,1,NULL,CSV1
14:13:06.366,1.55,2,5,1.5,1.55,63161255,C,17,20,NULL,CSV1
13:37:27.483,0.54,1,1,0.1,1,3058525,C,13,45,NULL,CSV2
14:37:27.483,0.54,1,2,0.1,1,3058525,O,13,45,NULL,CSV2
15:37:27.483,0.8,29,31,0.4,0.85,77148452,C,17,27,NULL,CSV2

下面是我用来添加所有CSV的代码

combined_csv = pd.concat([pd.read_csv(f).assign(New=os.path.basename(f)) for f in all_filenames ], sort=False,ignore_index=False)

0 个答案:

没有答案