Julian Julian - 6 months ago 47
Python Question

Limit decimals numbers when writing to csv in python

I loop over files and for each of these files, I compute a list of 4000+ (fixed number) features on it. These features are computed by a function and returned as

numpy.array


I want to write a CSV file with one line per file (each line is one
numpy.array
with 4000+ elements).

I'm currently using the
csv
library of Python and even if my array is rounded (thanks to
np.around
), the CSV file contains numbers with a lot of digits, e.g.
0,302499999999999
instead of
0,3025


I know this may come from floating points limitations in Python, but i wanted to know if there is any way to avoid this (by writing it as a string?) in the output file.

Sample of code below to reproduce the issue :

import numpy as np
import csv

for i in range(10) :
row = np.around(np.random.random(4000), decimals=5)

with open('output.csv', "ab") as fp:
wr = csv.writer(fp, dialect='excel')
wr.writerow(row)

Answer

You can use numpy.savetxt() like this:

import numpy as np

with open('output.csv', 'w') as fh:
    for i in range(10):  # loop over features
        row = np.random.random(4000)
        np.savetxt(fh, row.reshape(1, -1), fmt='%.5e', delimiter=',')