我需要將位於一個文件夾中的多個CSV文件合併爲一個文件。將csv文件(從一個文件夾)合併爲一個,使用Python添加具有不同名稱的列
我原來的數據是這樣的
y_1980.csv:
country y_1980
0 afg 196
1 ago 125
2 alb 23
3 . .
. . .
y_1981.csv:
country y_1981
0 afg 192
1 ago 120
2 alb 0
3 . .
. . .
y_20xx.csv:
country y_20xx
0 afg 176
1 ago 170
2 alb 76
3 . .
. . .
我所期望得到的是類似這樣的:
country y_1980 y_1981 ... y_20xx
0 afg 196 192 ... 176
1 ago 125 120 ... 170
2 alb 23 0 ... 76
3 . . . ... .
. . . . ... .
到目前爲止,我當前的代碼如下,但結果我得到的是數據幀的一前一後的合併:
interesting_files = glob.glob("/Users/Desktop/Data/*.csv")
header_saved = True
with open('/Users/Desktop/Data/table.csv','wb') as fout:
for filename in interesting_files:
with open(filename) as fin:
header = next(fin)
if not header_saved:
fout.write(header)
header_saved = True
for line in fin:
fout.write(line)
它,如果你使用容易得多'pandas'。因爲它擺脫了「for-loop」並且保持內存足跡低。而且,它更全面。讓我知道你是否想要熊貓解決方案。 – everestial007
是的,我想熊貓解決方案請 – PAstudilloE
檢查答案。它會工作優雅,更全面。讓我知道它是否有效。 – everestial007