Monica
Monica

Reputation: 1070

saving numpy array to file with a certain precision

I have a following numpy array:

geom= [[ 6.          0.2        -1.6        -1.3915    ]
         [ 6.          1.40507435 -1.6        -0.69575   ]
         [ 6.          1.40507435 -1.6         0.69575   ]
         [ 6.          0.2        -1.6         1.3915    ]
         [ 6.         -1.00507435 -1.6         0.69575   ]
         [ 6.         -1.00507435 -1.6        -0.69575   ]]

When I save it to the file :

np.savetxt(g, geom, fmt ='%f6', delimiter=' ', newline='\n', header='', footer='', comments='# ')

My first column gets a format '6.0000008'. Subsequently I want to modify that file to obtain 6.0 or 6. Is there any easy solution to do it? I have tried to convert string to int, but I am getting the error message in return:

ValueError: invalid literal for int() with base 10: '6.0000008'

Upvotes: 1

Views: 1779

Answers (1)

Grr
Grr

Reputation: 16079

Assuming you would like to keep the other floats as is you aren't going to find a simple solution to this in NumPy. Granted you could probably use structured arrays to achieve what you want but it will be significantly more work than just using Pandas (as mentioned by @jakevdp).

You could just import your NumPy array into a Pandas DataFrame, make the changes you want and then output the data into any Pandas acceptable format.

For example, to write a csv:

df = pd.DataFrame(geom)
df[0] = df[0].astype(int)
df.to_csv(g, index=False)

Upvotes: 1

Related Questions