【发布时间】:2017-05-16 04:17:26
【问题描述】:
我有一个 2D numpy 数组,例如
x = np.array([[3,3],[3,1]])
Out[107]:
array([[3, 3],
[3, 1]])
我想将其格式化为打印总数的百分比:
array([['33.3%', '33.3%'],
['33.3%', '10.0%']]
我已经尝试了here 和here 的一些解决方案,但还没有让它们起作用:
pct_formatter = lambda x: "{:.2%}".format(x/x.sum() * 100 )
pct_formatter(x)
TypeError: non-empty format string passed to object.__format__
又一次尝试:
with np.set_printoptions(formatter=pct_formatter):
print(pct_formatter(x))
AttributeError: __exit__
【问题讨论】:
标签: python numpy string-formatting