Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - find first non-null value in column

Tags:

python

pandas

If I have a series that has either NULL or some non-null value. How can I find the 1st row where the value is not NULL so I can report back the datatype to the user. If the value is non-null all values are the same datatype in that series.

Thanks

like image 717
code base 5000 Avatar asked Feb 09 '17 13:02

code base 5000


People also ask

How can I get non null value in pandas?

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

What is first () in pandas?

Pandas DataFrame first() Method The first() method returns the first n rows, based on the specified value. The index have to be dates for this method to work as expected.


1 Answers

You can use first_valid_index with select by loc:

s = pd.Series([np.nan,2,np.nan]) print (s) 0    NaN 1    2.0 2    NaN dtype: float64  print (s.first_valid_index()) 1  print (s.loc[s.first_valid_index()]) 2.0  # If your Series contains ALL NaNs, you'll need to check as follows:  s = pd.Series([np.nan, np.nan, np.nan]) idx = s.first_valid_index()  # Will return None first_valid_value = s.loc[idx] if idx is not None else None print(first_valid_value) None 
like image 65
jezrael Avatar answered Sep 19 '22 04:09

jezrael