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

Pandas filling NaN values with a string value and keeping None values as the same

I have a dataframe with mixed datatypes. I would like to fill NaN values but keep None values as the same.

I tried to use fillna() method from pandas but the function is filling both NaN and None values.
I want to fill NaN with a specific string value like ‘x’, instead of numbers. And keep None values as the same.

For example:
   A     B     C
0  12    0    None
1  None  NaN  None
2  NaN   9.8  1
3  0     NaN  1

Expected:
   A     B     C
0  12    0    None
1  None  x    None
2  x     9.8  1
3  0     x    1

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

>Solution :

df = pd.DataFrame([[None, 3], ["", np.nan]]) #created a dummy dataframe with these values

and then use this below code segment to change None to ‘None’ (a string) and then replace NA with which ever values you want to replace it with.

the finally converting it back to None (not a string)

df.replace({None:'None'}).fillna("x").replace({'None':None})

result looks like this

0 None  3.0 
1       x
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