datashout
datashout

Reputation: 147

How to replace nan by dictionary in pandas dataframe column

I want to replace a NaN in a dataframe column by a dictionary like this: {"value":["100"]}

df[column].apply(type).value_counts()

output:

<class 'dict'>     11565
<class 'float'>       43


df[column].isna().sum()

output => 43

How can I do this?

Upvotes: 1

Views: 76

Answers (1)

jezrael
jezrael

Reputation: 863226

Use lambda function for replace by dictionary:

df = pd.DataFrame({'column':[np.nan, {'a':[4,5]}]})

d = {"value":["100"]}
df['column'] = df['column'].apply(lambda x: d if pd.isna(x) else x)
print (df)
               column
0  {'value': ['100']}
1       {'a': [4, 5]}

Or list comprehension:

df['column'] = [d if pd.isna(x) else x for x in df['column']]

Upvotes: 1

Related Questions