How to convert NaN to 'N/A' in pandas?

Question:

How should I convert NaN to N/A in Pandas?

Any thoughts and suggestions are appreciated!

Asked By: Boomshakalaka

||

Answers:

You should clarify why you want to convert NaN to ‘N/A’. NaN is a special internal representation of missing data. Sure ‘N/A’ represents missing data, but to python, this will just be another string, and will be decidedly different from a None/null/missing value.

Without clarification, I am assuming that you want to export NaN values as ‘N/A’ when you are writing a CSV, XL, etc…; in order to do that, you can use the na_rep argument

df.to_csv('path/to/my.csv', na_rep='N/A')

This will make NaN values in your exported file write out as ‘N/A’.


pandas also has a fillna function, but be aware, this will convert missing data into a string, e.g.,

df.fillna('N/A')

will now not have any missing data, and pd.isna() will not work, since a String ‘N/A’ is not a null entry

Answered By: Ravi Patel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.