2016-09-23 38 views
0

我有下面的代码创建了一个矩阵:如何连接numpy中的字符串(创建百分比)?

import numpy as np 
table_vals = np.random.randn(4,4).round(4) * 100 

,我一直试图数字转换成百分比是这样的:

>>> table_vals.astype(np.string_) + '%' 
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32') 

像这样:

>>> np.str(table_vals) + '%' 
"[[ 137.08 120.31 -55.73 43.6 ]\n [ -94.35 -105.27 -23.31 59.16]\n [-132.9 12.04 -36.69 106.52]\n [ 126.11 -91.38 -29.16 -138.01]]%" 

但他们都失败了。所以我该怎么做?

回答

0

您可以使用格式为:

[["%.2f%%" % number for number in row] for row in table_vals] 

如果你想把它当作一个numpy的数组,然后把它包在np.array方法,因此就变成了:

np.array([["%.2f%%" % number for number in row] for row in table_vals]) 
+0

这太酷了!非常感谢〜 – DachuanZhao

0

np.char module可以帮助在这里:

np.char.add(table_vals.astype(np.bytes_), b'%') 

使用对象数组也很好:

np.array("%.2f%%") % table_vals.astype(np.object_)