![](/img/trans.png)
[英]Pandas error in merging two files based on different number of columns (2 and 1) in 2 dataframes
[英]Pandas/Python - Merging files on different columns based on incoming files
我有一個接收傳入文件的 python 程序。 傳入文件是基於不同國家的文件。 示例文件如下 - 文件 1(美國) -
country state city population
USA IL Chicago 2000000
USA TX Dallas 1000000
USA CO Denver 5000000
文件 2(非美國) -
country state city population
UK London 2000000
UK Bristol 1000000
UK Glasgow 5000000
然后我有一個需要與傳入文件合並的映射文件。 映射文件看起來像這樣
Country state Continent
UK Europe
Egypt Africa
USA TX North America
USA IL North America
USA CO North America
現在的要求是,如果它是美國文件,我需要將傳入文件與基於 state 列的映射文件加入,如果它是非美國文件,則基於國家列加入。 例如 - 如果它是美國文件 -
result_file = pd.merge(input_file, mapping_file, on="state", how="left")
如果它是非美國文件 -
result_file = pd.merge(input_file, mapping_file, on="country", how="left")
如何放置一個可以識別傳入文件並相應地合並文件的條件? 提前致謝
為了得到這兩種情況的統一代碼,讀取文件后,為fileX的DataFrame(df)和映射文件(dfmap)的DataFrame添加另一列,名稱為(country_state),其中國家和Z9ED369E2EA9342586合並,則使該列成為鏈接關系。
例如:
import pandas as pd
df = pd.read_csv('fileX.txt') # assumed for fileX
dfmap = pd.read_csv('mapping_file.txt') # assumed for mapping file
df.fillna('') # to replace Nan values with ''
if 'state' in df.columns:
df['country_state'] = df['country'] + df['state']
else:
df['country_state'] = df['country']
dfmap['country_state'] = dfmap['country'] + dfmap['state']
result_file = pd.merge(df, dfmap, on="country_state", how="left")
然后你可以刪除你不需要的列
添加修改,如果不存在則添加state
,並根據country
和state
設置關系,而不添加前面代碼中顯示的列“country_sate”:
import pandas as pd
df = pd.read_csv('file1.txt')
dfmap = pd.read_csv('file_map.txt')
df.fillna('')
if 'state' not in df.columns:
df['state']=''
result_file = pd.merge(df, dfmap, on=["country", "state"], how="left")
如果它們在同一個文件夾中,您可以使用
import os
list_of_files=os.listdir('my_directory/')
或者您可以在 Country 列中進行簡單搜索以查找 USA,然后根據情況應用合並
首先,清空非美國文件的 state 列。
input_file.loc[input_file.country!='US', 'state'] = ''
然后,合並兩列:
result_file = pd.merge(input_file, mapping_file, on=["country", "state"], how="left")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.