Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas check if column is null with query function

Tags:

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

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.

like image 837
user2671057 Avatar asked Sep 03 '17 07:09

user2671057


People also ask

How do you check if a column is null or not in pandas?

Python Pandas – Check for Null values using notnull() Now, on displaying the DataFrame, the CSV data will be displayed in the form of True and False i.e. boolean values because notnull() returns boolean. For Null values, False will get displayed. For Not-Null values, True will get displayed.

What is Isnull () in pandas?

Pandas DataFrame isnull() Method The isnull() method returns a DataFrame object where all the values are replaced with a Boolean value True for NULL values, and otherwise False.


1 Answers

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:

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 
like image 182
jezrael Avatar answered Nov 20 '22 04:11

jezrael