pandas 使用查询函数检查列是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46021195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:23:11  来源:igfitidea点击:

pandas check if column is null with query function

pythonpandasdataframenull

提问by user2671057

I have pandas dataframe that I want to execute on it query function with isnull() or not isnull() condition like that:

我有 Pandas 数据框,我想用 isnull() 或 not isnull() 条件在它上面执行查询函数,如下所示:

In [67]: df_data = pd.DataFrame({'a':[1,20,None,40,50]})
In [68]: df_data
Out[68]:       a
         0   1.0
         1  20.0
         2   NaN
         3  40.0
         4  50.0

if I use this command:

如果我使用这个命令:

df_data.query('a isnull', engine='python')

or this command:

或此命令:

df_data.query('a isnull()', engine='python')

I get an error:

我收到一个错误:

In [75]: df_data.query('a isnull', engine='python')  
File "<unknown>", line 1    a isnull           
SyntaxError: invalid syntax

In [76]: df_data.query('a isnull()', engine='python')  
File "<unknown>", line 1    a isnull ()           
SyntaxError: invalid syntax

What is the right way to do that?

这样做的正确方法是什么?

Thank you.

谢谢你。

回答by jezrael

Use .:

使用.

a = df_data.query('a.isnull()', engine='python')
print (a)
    a
2 NaN

b = df_data.query('a.notnull()', engine='python')
print (b)
      a
0   1.0
1  20.0
3  40.0
4  50.0


You can use also logic NaN != NaN:

您还可以使用逻辑NaN != NaN

a = df_data.query('a != a')
print (a)
    a
 2 NaN

b = df_data.query('a == a')
print (b)
      a
0   1.0
1  20.0
3  40.0
4  50.0