我有一个像这样的 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__
请您参考如下方法:
#user a dataframe to format the numbers and then convert back to a numpy array.
pd.DataFrame(x/float(np.sum(x))).applymap(lambda x: '{:.2%}'.format(x)).values
Out[367]:
array([['30.00%', '30.00%'],
['30.00%', '10.00%']], dtype=object)
