Pandas Cumsum function and dealing with Nan's

So I did a cumulative sum of a dataframe which looks like

 owner_username  ACHUTAN   AKKI  DHRUV  DISHA  INDER  KUNAL   MANU
game_id                                                          
1144483.0         316.0  296.0    NaN  309.0  119.0   79.0  142.0
1144484.0         136.0  143.0   19.0  116.0   90.0   93.0   11.0
1144485.0           NaN   49.0    2.0   53.0  145.0    NaN  190.0
1144486.0         359.0    NaN  308.0  106.0   65.0   71.0   65.0
1144487.0         112.0  161.0  356.0  150.0   76.0  119.0  160.0

So I don’t the value to be NaN instead it should take the last value for example in the columns “ACHUTAN” the first Nan should be 136.

Any help would be greatly appreciated.

You may use the following:

df["ACHUTAN"].fillna(df["ACHUTAN"].iloc[-1])

where

# Returns the last row's value for column "ACHUTAN" 
df["ACHUTAN"].iloc[-1]
1 Like

You need to use DataFrame.ffill() or fillna with method = ‘ffill’

df["ACHUTAN"].ffill()

So it will fill NaN using the last value.

More details can be found in the documentation
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html#pandas.DataFrame.fillna

1 Like