Skip to content Skip to sidebar Skip to footer

Writing Numpy Array With Nans Into Csv In Python

I am trying to write 2D numpy array into csv file using np.savetxt. import numpy as np data = np.array([[0,np.nan,2,3],[4,5,np.nan,7],[8,9,10,np.nan]]) np.savetxt('file.csv', dat

Solution 1:

The most straightforward solution:

data1 = data.astype(str)
data1[data1=='nan'] = ''
np.savetxt("file.csv", data1, delimiter=",", fmt="%s")

Solution 2:

You can solve this using pandas with na_rep parameter. For example:

df.to_csv(r'path\df.csv', sep=',', na_rep=np.NaN)

Post a Comment for "Writing Numpy Array With Nans Into Csv In Python"