Changing NaN cells in pandas dataframe with different type of columns

How can I fill all the NaN values in pandas dataframe with the empty value of column type. For example, I have 2 columns – "Name" – str, "Age" – int. I want to fill all the NaN cells in "Name" with "" and all the NaN in "Age" with 0. Do pandas has a method to implement it. I can do that separately for "Name" and "Age" but I want to let pandas determine the type of column by himself and in dependence of this type change NaN to either "" either 0. Thank you in advance.

>Solution :

The parameter value of pandas.DataFrame.fillna accept dictionnaries. So, assuming your dataframe is df, you can fill NaN values with multiple values in multiple columns by using :

df.fillna({"Name": "", "Age": 0}, inplace=True)

Furthermore, if you need to fill NaN values based on the type of the columns, use this :

df= pd.concat([df.select_dtypes(include=np.number).fillna(0),
               df.select_dtypes(include='object').fillna("")], axis=1)

NB: The code above will work properly only if your dataframe holds string and/or numeric columns.

Leave a Reply