我们有三个子表,每个表都有表头但是没有每行的索引,每一个表在csv文件中结构如下:
name,age
x,65
y,77
z,10
通过Pandas打开 data = pd.read_csv(r'test.csv'),默认会加上行索引,并且第一行为列索引
name age
0 x 65
1 y 77
2 z 10
data = pd.read_csv(r'test.csv',header=None),将列索引置为空则会再次补充表头
0 1
0 name age
1 x 65
2 y 77
3 z 10
正常的合并会导致以下情况:
name,age
x,65
y,77
z,10
name,age
x,65
y,77
z,10
name,age
x,65
y,77
z,10
因此在我们合并时,希望做到的是只保存一个表头,不添加行索引。但是通过df.drop_duplicates()去重对读入的表头只能去掉一个,因为作为表头的那一行不会进行匹配。
代码整理如下
import pandas as pd
import glob
def hebing(csv_list, outputfile):
for inputfile in csv_list:
f = open(inputfile)
data = pd.read_csv(f)
data.to_csv(outputfile, mo