【问题标题】:How to match multiple columns from two dataframes that have different sizes?如何匹配来自具有不同大小的两个数据框的多个列?
【发布时间】:2021-05-28 09:50:27
【问题描述】:

here 中找到了一个类似的解决方案,其中询问者只有一个数据帧,并且他们的要求是匹配一个固定的字符串值:

result = df.loc[(df['Col1'] =='Team2') & (df['Col2']=='Medium'), 'Col3'].values[0]

但是,我在使用 .loc 方法时遇到的问题是它要求 2 个数据帧具有相同的大小,因为它只会匹配每个数据帧相同行位置上的值。因此,如果行的顺序混合在任一数据框中,它将无法按预期工作。

这种情况的示例如下所示:

df1 - df1 = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})

df2 - df2 = pd.DataFrame({'a': [1, 3, 2], 'b': [4, 6, 5]})

使用 df1.loc[(df1['a'] == df2['a']) & (df1['b'] == df2['b']), 'Status'] = 'Included' 将产生:

但我正在寻找这样的东西:

我研究了诸如 .lookup 之类的方法,但在 2020 年 12 月已弃用(这也需要类似大小的数据框)。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    如果需要更改值例如使用numpy.where:

    df = df1.merge(df2, indicator='status', how='left')
    df['status'] = np.where(df['status'].eq('both'), 'included', 'not included')
    print (df)
       a  b    status
    0  1  4  included
    1  2  5  included
    2  3  6  included
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2015-11-10
      • 1970-01-01
      • 2013-03-15
      相关资源
      最近更新 更多