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?

>Solution :

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']]

Leave a Reply