Julian Julian - 2 years ago 173
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


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

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

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')

Answer Source

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=',')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download