以科学计数形式显示数组 [英] Show an array in format of scientific notation

查看:76
本文介绍了以科学计数形式显示数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

这是我的代码:

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)

推荐答案

如果您的Numpy版本为1.7或更高版本,则应该可以将formatter选项用于

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

或者,如果您没有formatter,则可以创建一个新数组,其值是所需格式的格式化字符串.这将创建一个与原始数组一样大的全新数组,因此这不是内存效率最高的方法,但是如果您不能升级numpy,它可能会起作用. (我对此进行了测试,并且可以在numpy 1.3.0上使用.)

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'是您希望每个值打印为的格式.您可以查阅本文档以获取更多选项.

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

在这种情况下,6是打印数字的最小宽度,而3是小数点后显示的位数.

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

这篇关于以科学计数形式显示数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆