Selecting rows from a Dataframe based on values in multiple columns in pandas

前端 未结 2 1607
星月不相逢
星月不相逢 2020-12-14 11:48

This question is very related to another, and I\'ll even use the example from the very helpful accepted solution on that question. Here\'s the example from the acce

2条回答
  •  鱼传尺愫
    2020-12-14 12:19

    There is only a very small change needed in your code: change the and with & (and add parentheses for correct ordering of comparisons):

    In [104]: df.loc[(df['A'] == 'foo') & (df['B'] == 'one')]
    Out[104]:
         A    B  C   D
    0  foo  one  0   0
    6  foo  one  6  12
    

    The reason you have to use & is that this will do the comparison element-wise on arrays, while and expect to compare two expressions that evaluate to True or False.
    Similarly, when you want the or comparison, you can use | in this case.

提交回复
热议问题