[英]Merge multiple CSV files that share 2 columns into one unique data frame
我在一個文件夾中有多個 CSV 文件(如 200),我想將它們合並到一個唯一的數據幀中。 例如,每個文件有 3 列,其中 2 列在所有文件( Country
和Year
)中是通用的,每個文件中的第三列是不同的。
例如,一個文件具有以下列:
Country Year X
----------------------
Mexico 2015 10
Spain 2014 6
其他文件可以是這樣的:
Country Year A
--------------------
Mexico 2015 90
Spain 2014 67
USA 2020 8
我可以讀取這些文件並將它們與以下代碼合並:
x = pd.read_csv("x.csv")
a = pd.read_csv("a.csv")
df = pd.merge(a, x, how="left", left_on=["country", "year"],
right_on=["country", "year"], indicator=False)
這導致了我想要的輸出,如下所示:
Country Year A X
-------------------------
Mexico 2015 90 10
Spain 2014 67 6
USA 2020 8
但是,我的問題是對每個文件進行先前的處理,有 200 多個,我想知道是否可以使用循環(或其他方法)來讀取文件並將它們合並到一個唯一的數據幀中。
非常感謝,希望我說的夠清楚了。
像這樣使用 glob:
import glob
print(glob.glob("/home/folder/*.csv"))
這將列出列表中的所有文件: ['/home/folder/file1.csv', '/home/folder/file2.csv', .... ]
現在,你可以遍歷這個列表: from 1->end, keeping 0 as your base
,然后做pd.read_csv()
和pd.merge()
- 它應該被排序!
嘗試這個:
import os
import pandas as pd
# update this to path that contains your .csv's
path = '.'
# get files that end with csv in path
dir_list = [file for file in os.listdir(path) if file.endswith('.csv')]
# initiate empty list
df_list = []
# simple for loop with Try, Except that passes on iterations that throw errors when trying to 'read_csv' your files
for file in dir_list:
try:
# append to df_list and set your indices to match across your df's for later pd.concat to work
df_list.append(pd.read_csv(file).set_index(['Country', 'Year']))
except: # change this depending on whatever Errors pd.read_csv() throws
pass
concatted = pd.concat(df_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.