【问题标题】:How to find values from one dataframe in another using pandas?如何使用熊猫从另一个数据框中的一个数据框中查找值?
【发布时间】:2017-01-20 17:40:51
【问题描述】:
I have two dataframes:

    df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],'B': ['B7', 'B4', 'B0', 'B3'] })
    df2 = pd.DataFrame({'A': ['A4', 'A3', 'A7', 'A8'],'B': ['B0', 'B1', 'B2', 'B3']})

我需要从B 列中获取所有公共值,所以这里将是B0B3

使用df1.B.isin(df2.B) 给我False False True True,但不是值列表。

【问题讨论】:

    标签: python pandas indexing merge conditional-statements


    【解决方案1】:

    你需要boolean indexing:

    print (df1[df1.B.isin(df2.B)])
    
        A   B
    2  A2  B0
    3  A3  B3
    
    print (df1.ix[df1.B.isin(df2.B), 'B'])
    2    B0
    3    B3
    Name: B, dtype: object
    
    print (df1.ix[df1.B.isin(df2.B), 'B'].tolist())
    ['B0', 'B3']
    

    merge 的另一个解决方案:

    print (pd.merge(df1,df2, on='B'))
      A_x   B A_y
    0  A2  B0  A4
    1  A3  B3  A8
    
    print (pd.merge(df1,df2, on='B')['B'])
    0    B0
    1    B3
    Name: B, dtype: object
    

    【讨论】:

      猜你喜欢
      • 2022-11-27
      • 2021-08-31
      • 2016-09-15
      • 2019-06-30
      • 1970-01-01
      • 2020-07-31
      • 2021-12-10
      • 2017-07-14
      相关资源
      最近更新 更多