【问题标题】:How can I filter a pandas dataset based on multiple columns?如何根据多列过滤熊猫数据集?
【发布时间】:2017-07-27 22:13:13
【问题描述】:

我正在尝试一些 ifthen 逻辑,但我在数据框中工作并且找不到任何示例。

我要做的是过滤此数据集以仅包含以下值 col1=col3 和 col2=col4

col1       col2     col3       col4
Wagner     John     Wagner     John
Jane       Mary     Klein      Peter 
Schneider  Megan    Wicker     Sam
Schneider  Megan    Schneider  Megan

结果

col1       col2     col3        col4
Wagner     John     Wagner      John
Schneider  Megan    Schneider   Megan

我的代码在这里不起作用

 df1.apply(lambda x : x['col1'] if x['col1'] == x['col1'] and x['col2'] == x['col2'] else "", axis=1

【问题讨论】:

    标签: python pandas lambda


    【解决方案1】:

    我会使用DataFrame.query() 方法:

    In [205]: df.query("col1==col3 and col2==col4")
    Out[205]:
            col1   col2       col3   col4
    0     Wagner   John     Wagner   John
    3  Schneider  Megan  Schneider  Megan
    

    或“经典”方法:

    In [206]: df.loc[(df.col1==df.col3) & (df.col2==df.col4)]
    Out[206]:
            col1   col2       col3   col4
    0     Wagner   John     Wagner   John
    3  Schneider  Megan  Schneider  Megan
    

    【讨论】:

    • 我累了,报错 ValueError: cannot assign without a target object
    • @OptimusPrime,你说的是第一种还是第二种方法?
    • @OptimusPrime,确保你使用==而不是=
    • 当我做 df.loc[(df.col1==df.col3) & (df.col2==df.col4)] vs df.loc[(df .col1==df.col3) df.loc[(df.col2==df.col4)]
    • @OptimusPrime,我没有得到你的第二行代码:df.loc[(df.col1==df.col3) df.loc[(df.col2==df.col4)]
    【解决方案2】:

    摆弄numpy 并假设列是它们的特定顺序

    df[np.equal(*df.values.T.reshape(2, 2, -1)).all(0)]
    
            col1   col2       col3   col4
    0     Wagner   John     Wagner   John
    3  Schneider  Megan  Schneider  Megan
    

    如果列的顺序不同

    cols = ['col1', 'col2', 'col3', 'col4']
    v = np.column_stack([df[c].values for c in cols])
    df[np.equal(*v.T.reshape(2, 2, -1)).all(0)]
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2016-08-31
      • 1970-01-01
      • 2020-05-05
      • 2014-12-27
      • 2020-11-28
      • 2020-08-08
      • 2019-05-21
      • 2018-07-13
      相关资源
      最近更新 更多