Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 关于使用column.isnull()进行df条件选择的问题(&;column.str.len()>;N_Python_Pandas - Fatal编程技术网

Python 关于使用column.isnull()进行df条件选择的问题(&;column.str.len()>;N

Python 关于使用column.isnull()进行df条件选择的问题(&;column.str.len()>;N,python,pandas,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

我想知道为什么下面的条件选择不起作用。我希望选择索引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: []
任何帮助都将不胜感激


谢谢

您需要使用单独的括号:

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

         A     B     C
0     this  None  some
3  example  None  data
这是由于。在您的代码中,
df['B'].isnull()&df['A'].str.len()
首先得到求值,得到:

0    False
1    False
2    False
3     True
dtype: bool
0    False
1    False
2    False
3    False
dtype: bool
然后应用剩余的比较
>3
,得出:

0    False
1    False
2    False
3     True
dtype: bool
0    False
1    False
2    False
3    False
dtype: bool

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

这是一个打字错误,括号必须围绕条件,因此使用:

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

         A     B     C
0     this  None  some
3  example  None  data

使用
Series/DataFrame
逻辑比较运算符有助于减少所有括号:
df.loc[df['B'].isnull()&df['A'].str.len().gt(3)]
是的,在每种情况下都要谨慎。(第1条)及(第2条)。