0

I have a matrix of float numbers which i'm trying to write into a csv file, however csv writer writes it in scientific notation, i would like to leave the numbers in the original notation, i tried adding "%.2f" % but that resulted in the following error:

"TypeError: only length-1 arrays can be converted to Python scalars"

for item in string_color_Values:
   avg_color_values = [ float(item) for item in string_color_Values]

array1t = np.array(avg_color_values)
np.savetxt("test.csv", array1t, delimiter=",")

original:

 [ 0.5258  1.    ]
 [ 0.528   1.    ]
 [ 0.5486  1.    ]
 [ 0.5545  1.    ]
 [ 0.732   1.    ]
 [ 0.7872  1.    ]
 [ 1.      1.    ]]

Csv which i obtain:

1.2270000000035e-01,1.0000000000e+00
2.7639999999790e-01,1.0000000000e+00
etc..
2
  • 1
    Are you using numpy soley to write a CSV file? You should just use the csv module. Commented May 1, 2017 at 5:11
  • Are you sure you have used the correct syntax: np.savetxt("test.csv", array1l, "%f.2", delimiter=",") works for me. Commented May 1, 2017 at 5:17

1 Answer 1

1

You need to have fmt="%g" in the call to np.savetxt. That will write the numbers without trailing zeroes. Alternatively if you want "cleanly" formatted nubmers you could use e.g. fmt="%.4f" (or any other format that takes your fancy).

import numpy as np
avg_color_Values = np.random.random((10,3))
array1t = np.array(avg_color_Values)
np.savetxt("test.csv", array1t, delimiter=",", fmt = "%g")

By default np.savetxt defaults to a format of %.18e, which will allows float64s to be written without loss of precicion.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.