Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save numpy array to CSV without scientific notation

Tags:

python

csv

numpy

I was able to calculate the mean, min and max of A:

 import numpy as np

 A = ['33.33', '33.33', '33.33', '33.37']

 NA = np.asarray(A)
 NA = NA.astype(float)
 AVG = np.mean(NA, axis=0)
 MN = np.min(NA, axis=0)
 MX = np.max(NA, axis=0)

 print AVG, MN, MX

What is the easiest way to save those results to a csv documento using python? I dont have one so it needs to be created.

If I use this:

 np.savetxt('datasave.csv', (AVG,MN,MX), delimiter=',')

It will show as scientific notation in csv. How do I not get that but float?

like image 798
Cristian J Estrada Avatar asked Mar 09 '17 07:03

Cristian J Estrada


People also ask

How do I make NumPy not use scientific notation?

Approach: Import numpy library and create numpy array. Pass the formatter to the set_printoptions() method. Print the Array, The entire array will be displayed without scientific notation.

How do I convert a NumPy array to a csv file?

Use the numpy. savetxt() Function to Save a NumPy Array in a CSV File. The savetxt() function from the numpy module can save an array to a text file. We can specify the file format, delimiter character, and many other arguments to get the final result in our desired format.

How do I get rid of scientific notation in Python?

Summary: Use the string literal syntax f"{number:. nf}" to suppress the scientific notation of a number to its floating-point representation.

How do you pretty print a NumPy array by suppressing the scientific notation like 1e10?

And suppress suppresses the use of scientific notation for small numbers: y = np. array([1.5e-10, 1.5, 1500]) print(y) # [ 1.500e-10 1.500e+00 1.500e+03] np. set_printoptions(suppress=True) print(y) # [ 0.


2 Answers

In [153]: print(AVG, MN, MX)
33.34 33.33 33.37

The default write:

In [154]: np.savetxt('test.txt',(AVG, MN, MX), delimiter=',')
In [155]: cat test.txt
3.333999999999999631e+01
3.332999999999999829e+01
3.336999999999999744e+01

write with a custom fmt:

In [156]: np.savetxt('test.txt',(AVG, MN, MX), delimiter=',', fmt='%f')
In [157]: cat test.txt
33.340000
33.330000
33.370000

Or if you want values on one line, make it a 2d array (or equivalent with extra []), so it writes one row per line:

In [160]: np.savetxt('test.txt',[[AVG, MN, MX]], delimiter=',', fmt='%f')
In [161]: cat test.txt
33.340000,33.330000,33.370000

There are other parameters that you can experiment with.

like image 61
hpaulj Avatar answered Oct 14 '22 08:10

hpaulj


You can use the CSV module

import csv
f = open('New file.csv',"wb")
writer = csv.writer(f)
for row in [AVG, MN, MX]:
    writer.writerow(row)

f.close()
like image 20
Josh Kidd Avatar answered Oct 14 '22 08:10

Josh Kidd