Carmen Mitru
Carmen Mitru

Reputation: 153

How can I select the rows that have only one element non nan value and all the the rest are NaN?

I am trying to extract from a dataframe the rows that have only element no-Nan and the rest are None. For example :

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

For this example of dataframe it should return the first row. I tried this code but it doesn't work:

df_table.isnull(df_table[cols]).all(axis=1)

Thanks!

Upvotes: 1

Views: 283

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150745

Use sum instead of all:

df.loc[df.notnull().sum(1)==1]

To get the non-nan elements, you can use, for example, max:

df.loc[df.notnull().sum(1)==1].max(1)

or

df.loc[df.notnull().sum(1)==1].ffill(1).iloc[:,-1]

which gives:

0    2.0
1    3.0
dtype: float64

Upvotes: 2

Related Questions