Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First non-null value per row from a list of Pandas columns

Tags:

python

pandas

If I've got a DataFrame in pandas which looks something like:

    A   B   C 0   1 NaN   2 1 NaN   3 NaN 2 NaN   4   5 3 NaN NaN NaN 

How can I get the first non-null value from each row? E.g. for the above, I'd like to get: [1, 3, 4, None] (or equivalent Series).

like image 241
Dave Challis Avatar asked Aug 05 '15 09:08

Dave Challis


People also ask

How do I check if multiple columns are null in pandas?

By using isnull(). values. any() method you can check if a pandas DataFrame contains NaN / None values in any cell (all rows & columns ). This method returns True if it finds NaN/None on any cell of a DataFrame, returns False when not found.


1 Answers

Fill the nans from the left with fillna, then get the leftmost column:

df.fillna(method='bfill', axis=1).iloc[:, 0] 
like image 77
Andy Jones Avatar answered Sep 29 '22 19:09

Andy Jones