Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show an array in format of scientific notation

Tags:

python

numpy

I would like to show my results in scientific notation (e.g., 1.2e3). My data is in array format. Is there a function like tolist() that can convert the array to float so I can use %E to format the output?

Here is my code:

import numpy as np
a=np.zeros(shape=(5,5), dtype=float)
b=a.tolist()
print a, type(a), b, type(b)
print '''%s''' % b 
# what I want is 
print '''%E''' % function_to_float(a or b)
like image 816
TTT Avatar asked Jul 26 '12 20:07

TTT


1 Answers

If your version of Numpy is 1.7 or greater, you should be able to use the formatter option to numpy.set_printoptions. 1.6 should definitely work -- 1.5.1 may work as well.

import numpy as np
a = np.zeros(shape=(5, 5), dtype=float)
np.set_printoptions(formatter={'float': lambda x: format(x, '6.3E')})
print a

Alternatively, if you don't have formatter, you can create a new array whose values are formatted strings in the format you want. This will create an entirely new array as big as your original array, so it's not the most memory-efficient way of doing this, but it may work if you can't upgrade numpy. (I tested this and it works on numpy 1.3.0.)

To use this strategy to get something similar to above:

import numpy as np
a = np.zeros(shape=(5, 5), dtype=float)
formatting_function = np.vectorize(lambda f: format(f, '6.3E'))
print formatting_function(a)

'6.3E' is the format you want each value printed as. You can consult the this documentation for more options.

In this case, 6 is the minimum width of the printed number and 3 is the number of digits displayed after the decimal point.

like image 175
Sam Mussmann Avatar answered Sep 18 '22 05:09

Sam Mussmann