Reputation: 123
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
Upvotes: 0
Views: 861
Reputation: 30920
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()
Upvotes: 1
Reputation: 57
You should remove inplace=True
df['Fruits','Veg','Non_veg'] = df['Fruits','Veg','Non_veg'].fillna(method= 'ffill')
Upvotes: 1
Reputation: 25239
Don't use inplace
on slicing object. Do assigment
df.loc[:, ['Fruits','Veg','Non_veg']] = df.loc[:, ['Fruits','Veg','Non_veg']].ffill()
Upvotes: 1