python pandas select rows where two columns are (not) equal

后端 未结 2 539
一生所求
一生所求 2021-01-04 10:01
hsp.loc[hsp[\'Len_old\'] == hsp[\'Len_new\']]

I try this code, it\'s working.

But I tried these three

hsp.loc[hsp[\'Type_o         


        
相关标签:
2条回答
  • 2021-01-04 10:27

    Ways to be confused by == versus != when comparing pd.Series

    As expected

    df[['Len_old', 'Len_new']].assign(NE=df.Len_old != df.Len_new)
    
       Len_old  Len_new     NE
    0       15       15  False
    1       12       12  False
    2       10        8   True
    3        4        5   True
    4        9       10   True
    

    But if one of the column's values were strings!

    df[['Len_old', 'Len_new']].assign(NE=df.Len_old.astype(str) != df.Len_new)
    
       Len_old  Len_new    NE
    0       15       15  True
    1       12       12  True
    2       10        8  True
    3        4        5  True
    4        9       10  True
    

    Make sure both are the same types.

    0 讨论(0)
  • 2021-01-04 10:30

    Use the complement operator ~

    hsp.loc[~(hsp['Type_old'] == hsp['Type_new'])]
    

    which gives:

       id Type_old Type_new  Len_old  Len_new
    1   2      Num     Char       12       12
    2   3     Char      Num       10        8
    

    When dealing with Boolean operations, the complement operator is a handy way to invert True with False

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