简体   繁体   中英

Show an array in format of scientific notation

I would like to show my results in scientific notation (eg, 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)

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.

You can format each of the elements of an array in scientific notation and then display them as you'd like. Lists cannot be converted to floats, they have floats inside them potentially.

import numpy as np
a = np.zeroes(shape=(5, 5), dtype=float)
for e in a.flat:
    print "%E" % e

or

print ["%E" % e for e in a.flat]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM