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

标签 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: []

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

您需要使用单独的括号:

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/

相关文章:

javascript - 如何在 Django 模型表单中包含日期选择器?

python - CSV 到文本文件布局

python - 根据向量绘制数组中的对象

python - 如何在 Python 中打开 .ndjson 文件?

Python/Statsmodels - 向量自回归 endog

python - Scikit-learn(SVC 估计器)总是给出相同的预测值

python - 使用类继承时出现类型错误

python - 如何根据另一列滚动函数的结果计算 pandas DataFrame 列的值

python - 如何在pandas数据帧上使用haversine库使用haversine距离

python - 在 x 轴上绘制列名称