Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading