Mykola Zotko
Mykola Zotko

Reputation: 17824

Identify consecutive not nan values at the end

How to get the last part of consecutive not NaN values in a table? For example:

   col
0  1.0
1  2.0
2  NaN
3  NaN
4  3.0
5  NaN
6  4.0
7  5.0
8  6.0

Desired result:

   col
6  4.0
7  5.0
8  6.0

My solution:

df[df.col[::-1].isna().cumsum()[::-1].eq(0)]

Upvotes: 0

Views: 79

Answers (3)

Akshay Sehgal
Akshay Sehgal

Reputation: 19322

Here is another way you can do this -

df[df.loc[::-1, 'col'].isna().cumsum()[::-1]==0]
    col
6   4.0
7   5.0
8   6.0

Upvotes: 1

ESDAIRIM
ESDAIRIM

Reputation: 651

This worked for me:

last_index = np.where(df.col.isna())[0][-1]
df.iloc[last_index+1:]

Upvotes: 0

ashkangh
ashkangh

Reputation: 1624

Try this:

last_index = df[df.col.isna()].index[-1]
df.iloc[last_index + 1:]

output:

    col
6   4.0
7   5.0
8   6.0

Upvotes: 2

Related Questions