Skip to content Skip to sidebar Skip to footer

Pandas Cumcount() When Np.nan Exists

I have a dataframe like this: df = pd.DataFrame([[1, 2, np.nan], [1, np.nan, 3], [2, 2, 3], [3, 4, np.nan]]) when I groupb

Solution 1:

groupby omit NaNs rows so possible solution should be replace them to value which not exist in data, e.g. -1.

Btw, cumcount seems create with omited rows separated group.

for i, dfin df.groupby([0, 1, 2]):
    print (df)
   0    1    2
2  2  2.0  3.0

print (df.fillna(-1).groupby([0, 1, 2]).cumcount())
00102030
dtype: int64

Post a Comment for "Pandas Cumcount() When Np.nan Exists"