在多个字段上过滤时包围

Bracketing when filtering on mutiple fields

筛选时关于括号的问题:

df.info()

RangeIndex: 4005 entries, 0 to 4004
Data columns (total 41 columns):
currency_str                   4005 non-null object
state                          4005 non-null object

display(
        df[
            df['currency_str'] == 'INR'  
        ])

正确显示我的 INR 行。

当我添加第二个过滤器时,我需要用双括号括起来,否则我会出错。

display(

        df[
            (df['currency_str'] == 'INR')    &  
            (df['state'].str.contains('Done'))
        ])

Pandas 背后发生了什么? & 还不够吗?这是否与标准包含在“”中的字符串字段特别相关?

没有括号

display(
        df[
            df['currency_str'] == 'INR'    &  
            df['state'].str.contains('Done')
        ])
TypeError: cannot compare a dtyped [bool] array with a scalar of type [bool]

一组括号

display(
        df[
            (df['currency_str'] == 'INR'    &  
            df['state'].str.contains('Done'))
        ])
TypeError: cannot compare a dtyped [bool] array with a scalar of type [bool]

您应该为每个条件添加 ()

df=pd.DataFrame({'currency_str':['INR','INR','None'],'state':['LOLDone','l','Done']})

df[(df['currency_str'] == 'INR') &(df['state'].str.contains('Done'))]
Out[789]: 
  currency_str    state
0          INR  LOLDone