关于使用column.isnull()和column.str.len()> n进行df条件选择的问题

时间:2019-04-08 02:09:47

标签: python pandas

我想知道为什么以下条件选择不起作用。我希望选择索引0和3,但这什么也不返回。想知道我是否缺少明显的东西。

In [5]: a = {'A':['this', 'is', 'an', 'example'], 'B':[None, None, None, None], 
   ...: 'C':['some', 'more', 'example', 'data']}

In [6]: df = pd.DataFrame(a)

In [7]: df
Out[7]: 
         A     B        C
0     this  None     some
1       is  None     more
2       an  None  example
3  example  None     data

这将返回2行:

In [8]: df.loc[(df['A'].str.len() > 3)]
Out[8]: 
         A     B     C
0     this  None  some
3  example  None  data

这将返回所有行:

In [9]: df.loc[(df['B'].isnull())]
Out[9]: 
         A     B        C
0     this  None     some
1       is  None     more
2       an  None  example
3  example  None     data

所以我希望它返回索引0和3,但不返回任何行

In [10]: df.loc[(df['B'].isnull() & df['A'].str.len() > 3)]
Out[10]: 
Empty DataFrame
Columns: [A, B, C]
Index: []

任何帮助将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:1)

您需要使用单独的括号:

df.loc[(df['B'].isnull()) & (df['A'].str.len() > 3)]

         A     B     C
0     this  None  some
3  example  None  data

这是由于Operator precedence引起的。在您的代码中,df['B'].isnull() & df['A'].str.len()首先得到评估,得出:

0    False
1    False
2    False
3     True
dtype: bool

然后应用剩余的比较>3,得出:

0    False
1    False
2    False
3    False
dtype: bool

因此,原始行不返回任何行,而不是所需的索引。

答案 1 :(得分:0)

这是一个错字,必须在条件周围加上括号,因此请使用:

df.loc[(df['B'].isnull()) & (df['A'].str.len() > 3)]

输出:

         A     B     C
0     this  None  some
3  example  None  data
相关问题