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

前端 未结 2 1600
星月不相逢
星月不相逢 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:09

    You can do this with tiny altering in your code:

    print(df[df['A'] == 'foo'][df['B'] == 'one'])
    

    Output:

         A    B  C   D
    0  foo  one  0   0
    6  foo  one  6  12
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题