我想知道为什么下面的条件选择不起作用。我希望选择索引 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
这是由于 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
因此原始行不返回任何行,而不是所需的索引。
关于python - 关于使用column.isnull()&column.str.len() > n进行df条件选择的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55565396/