簡體   English   中英

Pandas - 用條件連接兩個數據幀

[英]Pandas - Joining two Dataframes with Condition

我是數據分析的初學者,我正在使用 python pandas lib 將兩個數據幀連接在一起。

目標是使用第二個表中的所有數據創建一個新的數據框,並在“類型”上加入第二個表上的第一個表,以用第一個表中的字母替換數字。 我已經嘗試了一些合並和連接,但找不到解決方案。 幫助將不勝感激。

#Tables were created with pd.read_csv(path, sep = '\t', encoding = 'ISO-8859-1')
#First Table

ID  type
1   A
2   B
3   C
4   D
5   E
...

#Second Table

ID  type  column2  column3 ... 
1   2     x
2   2     y
3   3     x
4   1     y
5   4     z
...

如果我理解正確

df2.type.map(df1.set_index('ID').type)
Out[152]: 
0    B
1    B
2    C
3    A
4    D
Name: type, dtype: object

嘗試這個,

print pd.merge(df1,df2,on=['ID']).drop('type_y',axis=1).rename(columns={'type_x':'type'})

輸出:

   ID type column2
0   1    A       x
1   2    B       y
2   3    C       x
3   4    D       y
4   5    E       z

當 df1 中有很多列並希望將其添加到結果中時,請使用pd.merge ,否則使用 WB 的解決方案。

暫無
暫無

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

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