Selecting with complex criteria from pandas.DataFrame

后端 未结 4 986
孤街浪徒
孤街浪徒 2020-11-22 11:12

For example I have simple DF:

import pandas as pd
from random import randint

df = pd.DataFrame({\'A\': [randint(1, 9) for x in xrange(10)],
                         


        
4条回答
  •  遥遥无期
    2020-11-22 11:26

    And remember to use parenthesis!

    Keep in mind that & operator takes a precedence over operators such as > or < etc. That is why

    4 < 5 & 6 > 4
    

    evaluates to False. Therefore if you're using pd.loc, you need to put brackets around your logical statements, otherwise you get an error. That's why do:

    df.loc[(df['A'] > 10) & (df['B'] < 15)]
    

    instead of

    df.loc[df['A'] > 10 & df['B'] < 15]
    

    which would result in

    TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

提交回复
热议问题