如何有条件地合并数据框列

时间:2020-03-14 13:51:21

标签: python pandas join merge

我有两个puanlar = browser.find_elements_by_css_selector("meta[itemprop='ratingValue']") for puan in puanlar: Ratings.append(puan.get_attribute('content'))

dfs

df1

Person Dept Date Company ID Value 0 Faye Sales 12/31/16 FB Co Inc 123 27 1 Faye Sales 3/31/17 Unknown 123 34 2 Ray Eng 3/31/18 xyz co 345 59 3 Ray HR 6/30/18 XyZ 345 54 4 Jay HR 9/30/18 A 678 53 5 Jim Ops 9/30/16 New 999 8

df2

我要:

  1. 合并到 Company Symbol ID 0 FB Inc FB 123 1 XYZ Corp No Symbol 345 2 A LLC AA 678 3 EFG Corp EFG 555
  2. ID中的Company替换为df1中格式整齐的{{1},如果{{ 1}})
  3. df2中的Company添加到df1

使输出看起来像:

df2

Symbol中找不到匹配项(df2与{ {1}}):

df1

我该如何解决?

2 个答案:

答案 0 :(得分:1)

只需使用fillna更改代码即可

df3 = pd.merge(df1, df2, on='ID', how='left')
df3.Company_y.fillna(df3.Company_x, inplace=True) # here is fillna with two value 
df3=df3.drop('Company_x', 1)

答案 1 :(得分:0)

使用np.where.notnull()逻辑也可以做到这一点吗?您输入的内容复制/粘贴得不好。

df3 = pd.merge(df1, df2, on='ID', how='left')
df3['Company_x'] = np.where(df3['Company_y'].notnull(),
                            df3['Company_y'], df3['Company_x'])
df3 = df3.drop('Company_x', axis=1)
相关问题