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", data, delimiter=",", fmt='%.2f')
Which creates a file file.csv with the following content.
0.00,nan,2.00,3.00
4.00,5.00,nan,7.00
8.00,9.00,10.00,nan
As you can see the file contains nan instead of blanks. I know nan is not a string.
Expected Output:
0.00,,2.00,3.00
4.00,5.00,,7.00
8.00,9.00,10.00,
Using pandas I can achieve this like below.
import pandas as pd
df = pd.DataFrame(data)
df.to_csv("file1.csv", index=False)
But I'm refraining from using pandas for now. So is it possible to achieve this using numpy?
savetxtis doing is a formatted write of each row of your array.'%.2f,%.2f,...'%tuple(row). Just basic python % formatting.