簡體   English   中英

使用Pandas的左聯接表(1:n),行數與左表相同

[英]Left join tables (1:n) using Pandas, keeping number of rows the same as left table

如何保留具有1:n關系的聯接表,同時使行數與左表相同,並使用';'等字符/字符串連接所有重復數據。

例:
國家表

CountryID      Country      Area
1              UK           1029
2              Russia       8374

城市表

CountryID      City     
1              London           
1              Manchester       
2              Moscow          
2              Ufa   

我想要:

CountryID      Country      Area      Cities
1              UK           1029      London;Manchester
2              Russia       8374      Moscow;Ufa

我知道如何執行正常的左聯接

country.merge(city, how='left', on='CountryID')

這給了我四行而不是兩行:

Area      Country      CountryID      City
1029      UK           1              London
1029      UK           1              Manchester
8374      Russia       2              Moscow
8374      Russia       2              Ufa

如果性能很重要,請使用由groupby + join創建的Series by map作為df1新列:

df1['Cities'] = df1['CountryID'].map(df2.groupby('CountryID')['City'].apply(';'.join))
print (df1)
   CountryID Country  Area             Cities
0          1      UK  1029  London;Manchester
1          2  Russia  8374         Moscow;Ufa

詳細說明

print (df2.groupby('CountryID')['City'].apply(';'.join))
CountryID
1    London;Manchester
2           Moscow;Ufa
Name: City, dtype: object

join另一種解決方案:

df = df1.join(df2.groupby('CountryID')['City'].apply(';'.join), on='CountryID')
print (df)
   CountryID Country  Area               City
0          1      UK  1029  London;Manchester
1          2  Russia  8374         Moscow;Ufa

這將為您提供所需的結果:

df1.merge(df2, on='CountryID').groupby(['CountryID', 'Country', 'Area']).agg({'City': lambda x: ';'.join(x)}).reset_index()

#   CountryID Country  Area               City
#0          1      UK  1029  London;Manchester
#1          2  Russia  8374         Moscow;Ufa

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM