Pandas slicing/selecting with multiple conditions with or statement

前端 未结 1 559
难免孤独
难免孤独 2021-02-13 15:48

When I select by chaining different conditions with \"AND\" the selection works fine. When I select by chaining conditions with \"OR\" the selection throws an error.

<         


        
1条回答
  •  一个人的身影
    2021-02-13 16:21

    The important thing to note is that & is not identical to and they are different things so the "or" equivalent to to & is |

    Normally both & and | are bitwise logical operators rather than the python "logical" operators.

    In pandas these operators are overloaded for Series operation.

    In [1]: import pandas as pd
    
    In [2]: import numpy as np
    
    In [3]: df = pd.DataFrame([[1,4,3],[2,3,5],[4,5,6],[3,2,5]], columns=['a', 'b',
       ...:  'c'])
    
    In [4]: df
    Out[4]:
       a  b  c
    0  1  4  3
    1  2  3  5
    2  4  5  6
    3  3  2  5
    
    In [5]: df.loc[(df.a != 1) & (df.b < 5)]
    Out[5]:
       a  b  c
    1  2  3  5
    3  3  2  5
    
    In [6]: df.loc[(df.a != 1) | (df.b < 5)]
    Out[6]:
       a  b  c
    0  1  4  3
    1  2  3  5
    2  4  5  6
    3  3  2  5
    

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