12

我想以科学记数法(例如 1.2e3)显示我的结果。我的数据是数组格式。是否有类似的函数tolist()可以将数组转换为浮点数,以便我可以使用 %E 来格式化输出?

这是我的代码:

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

2 回答 2

13

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.

于 2012-07-26T22:31:27.917 回答
3

您可以用科学记数法格式化数组的每个元素,然后根据需要显示它们。列表不能转换为浮点数,它们内部可能有浮点数。

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

或者

print ["%E" % e for e in a.flat]
于 2012-07-26T21:31:56.947 回答