Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - pandas export to csv or dat file removing None or numpy.nan

When exporting a dataframe df to a dat file, how to remove the None or numpy.nan in the file? I just need an empty value.

df.to_csv('test.dat')

I have tried:

df = df.fillna('')

or

df = df.replace(numpy.nan, '') and df = df.replace(None, '')

But I still see 'None' or 'nan' in the csv or dat file.

like image 869
thatMeow Avatar asked Mar 23 '26 07:03

thatMeow


2 Answers

Use the parameter

na_rep : string, default ” Missing data representation"

and set this to ""

which you can read here:

pandas.DataFrame.to_csv

This is the code:

file=pd.DataFrame({"one":[1,2,None,3,4],"two":[5,6,7,np.nan,8]})

file.to_csv("xxxxxxx",na_rep="")

Will lead to: Result

like image 121
2Obe Avatar answered Mar 24 '26 21:03

2Obe


I found a solution to my own question:

df = df.replace('None','')
df = df.replace('nan','')

It is clear that somehow pandas treat None and numpy.nan as string value here. Not sure why but this solution works.

like image 32
thatMeow Avatar answered Mar 24 '26 22:03

thatMeow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!