Skip to content
Advertisement

How to replace all the non-first values of columns with NaN based on date?

I have this dataframe:

df

I want to replace the non-First values of the columns with NaN, for each day.

This is how should the dataframe look like:

df desidered

This is what i tried:

JavaScript

#i’m trying to use replace, but this does not consider the date

JavaScript

Advertisement

Answer

groupby + rank

First create boolean mask with isna, then use groupby + rank with method='first' to assign numerical ranks, finally mask the values in the original dataframe where rank is 1

JavaScript

Result

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement