set NaN values in pandas dataframe to 1

Question:

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)
Asked By: Lewis-010

||

Answers:

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)
Answered By: mozway

Use DataFrame.fillna with convert columns names by dictionary to 1:

print (dict.fromkeys(['guests', 'bedrooms', 'beds', 'bathrooms'], 1))
{'guests': 1, 'bedrooms': 1, 'beds': 1, 'bathrooms': 1}

df = df.fillna(dict.fromkeys(['guests', 'bedrooms', 'beds', 'bathrooms'], 1))
Answered By: jezrael
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.