Zmann3000
Zmann3000

Reputation: 816

Find first N non null values in each row

If I have a pandas dataframe like this:

 NaN NaN NaN  0  5  7  2  2  3  7  8
 NaN NaN  0   1  2  3  5  8  8 NaN 4
 NaN  0   3   6  9 NaN 4  6  1  5  1
 NaN NaN  0   1  2  3  5  8  8 NaN 2
 NaN NaN NaN  0  5  7  2  2  3  7  8
 NaN NaN  0   1  2  3  5  8  8 NaN 4

How do I only keep the first five non null values in each row and set the rest to nan such that I get a dataframe that looks like this:

 NaN NaN NaN  0  5  7  2   2  NaN NaN NaN
 NaN NaN  0   1  2  3  5  NaN NaN NaN NaN
 NaN  0   3   6  9 NaN 4  NaN NaN NaN NaN
 NaN NaN  0   1  2  3  5 NaN NaN NaN NaN
 NaN NaN NaN  0  5  7  2   2  NaN NaN Nan
 NaN NaN  0   1  2  3  5  NaN NaN NaN NaN

Upvotes: 2

Views: 82

Answers (1)

Mykola Zotko
Mykola Zotko

Reputation: 17864

You can use:

df.mask(df.notna().cumsum(axis=1).gt(5))

Upvotes: 2

Related Questions