I have a large pandas dataframe and am struggling to set NaN values of specific columns to 1. The column types for the columns I want to work on are below:
guests = object, beds = float64, bathrooms = float64, bedrooms = object.
I have tried these methods but none have worked:
df['guests', 'bedrooms', 'beds', 'bathrooms'] = df['guests', 'bedrooms', 'beds', 'bathrooms'].replace(np.nan, 1)
df['guests', 'bedrooms', 'beds', 'bathrooms'].fillna(1, inplace=True)
Any help appreciated.
CodePudding user response:
Don't use inplace
as you are modifying a copy of the DataFrame, but assign
back or update
:
df.update(df[['guests', 'bedrooms', 'beds', 'bathrooms']].fillna(1))
Or:
cols = ['guests', 'bedrooms', 'beds', 'bathrooms']
df[cols] = df[cols].fillna(1)
Or limit the values in fillna
using a dictionary:
cols = ['guests', 'bedrooms', 'beds', 'bathrooms']
df.fillna({k: 1 for k in cols}, inplace=True)
CodePudding user response:
Use DataFrame.fillna
with convert columns names by dictionary to 1
:
df = df.fillna(dict.fromkeys(['guests', 'bedrooms', 'beds', 'bathrooms'], 1))