0
df
   Fruits  Veg       Non_veg
 1 Apple   Broccoli  Chicken
 2 Banana   Nan       Nan
 3  Nan    Tomato     Nan

In the above sample data frame, I have Nan values and I need to fill it with forward filling all at once and the code I used is :

df[['Fruits','Veg','Non_veg']].fillna(method='ffill',inplace=True)

Is this way of coding is correct ? also if the forward filling cell has another Nan value like in the above data frame how to overcome?

The Expected output for ffill is:

df
       Fruits  Veg       Non_veg
     1 Apple   Broccoli  Chicken
     2 Banana  Broccoli  Chicken
     3 Banana  Tomato    Chicken
emremrah
  • 1,543
  • 10
  • 17
jain
  • 95
  • 1
  • 11

3 Answers3

1

Use: DataFrame.ffill.Here you can se how use inplace : How to use inplace=True

#df.replace('Nan',np.nan) #if NaN is string
cols=['Fruits','Veg','Non_veg']
df[cols]=df[cols].ffill()
ansev
  • 28,746
  • 5
  • 11
  • 29
0

Don't use inplace on slicing object. Do assigment

df.loc[:, ['Fruits','Veg','Non_veg']] = df.loc[:, ['Fruits','Veg','Non_veg']].ffill()
Andy L.
  • 24,086
  • 3
  • 14
  • 26
0

You should remove inplace=True
df['Fruits','Veg','Non_veg'] = df['Fruits','Veg','Non_veg'].fillna(method= 'ffill')