2016-09-23 43 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_)