Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : How can I check if the content of one entire column of a Dataframe is empty?

I want to check if one entire column of a dataframe is empty ! So let's say that I have

data1 = [12,34,'',678,896]
data2 = ['','','','','']

df = pd.DataFrame(list(zip(data1,data2)),columns = ['Data1','Data2'])
print(df)

   Data1 Data2
0     12
1     34
2    
3    678
4    896

The column "Data1" has data and the column "Data2" is empty. I tried the function print(df['Data2'].empty), but it returns me false and I don't get why. So how can I verify that ?

Thank you

like image 923
Maikiii Avatar asked Sep 03 '25 06:09

Maikiii


2 Answers

If there are blank spaces, it might not be all '' so it is better to use regex here, then we can use Series.isna() and Series.all()

df['Data2'].replace(r'^\s*$', np.nan, regex=True).isna().all()
like image 195
ansev Avatar answered Sep 04 '25 20:09

ansev


You can check if the Series is empty by first converting ''(Blank) to np.nan and then dropna():

In [2530]: import numpy as np
In [2531]: df.Data2 = df.Data2.replace('', np.nan)

In [2533]: df.Data2.dropna().empty
Out[2533]: True
like image 40
Mayank Porwal Avatar answered Sep 04 '25 21:09

Mayank Porwal