简体   繁体   中英

How to fill Nan values for multiple columns at once?

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

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()

Don't use inplace on slicing object. Do assigment

df.loc[:, ['Fruits','Veg','Non_veg']] = df.loc[:, ['Fruits','Veg','Non_veg']].ffill()

你应该删除inplace=True
df['Fruits','Veg','Non_veg'] = df['Fruits','Veg','Non_veg'].fillna(method= 'ffill')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM