Home > Mobile >  fill NaN values by previous value
fill NaN values by previous value

Time:07-23

I have a DataFrame with some NaNs:

>>> import pandas as pd
>>> df = pd.DataFrame([[111, 222, 'apple'], [888, 444, 'pear'], [666, 777, 'pineapple'] [None, 444, None]])
>>> df
    0     1     2
0   111   222   apple
1   888   444   pear
2   666   777   pineapple
3   NaN   444   NaN

And I want to get such a df

    0     1     2
0   111   222   apple
1   888   444   pear
2   666   777   pineapple
3   888   444   pear

CodePudding user response:

Simply use ffill() with a groupby

>>> df.assign(**df.groupby(1, as_index=False).ffill())

       0    1          2
0  111.0  222      apple
1  888.0  444       pear
2  666.0  777  pineapple
3  888.0  444       pear

CodePudding user response:

Another way of using groupby and ffill will be to assign it back to the dataframe.

df[[0,2]] = df.groupby(1).ffill()
  • Related