How to concatenate strings in numpy (to create percentages)?
<p>I have a matrix created by the following code:</p>

<pre><code>import numpy as np
table_vals = np.random.randn(4,4).round(4) * 100
</code></pre>

<p>and I've tried to convert numbers into percentages like this:</p>

<pre><code>&gt;&gt;&gt; table_vals.astype(np.string_) + '%'
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('&lt;U32') dtype('&lt;U32') dtype('&lt;U32')
</code></pre>

<p>and like this:</p>

<pre><code>&gt;&gt;&gt; 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]]%"
</code></pre>

<p>but all of them failed. So what should I do?</p>

<p>The <a href="http://docs.scipy.org/doc/numpy/reference/routines.char.html" rel="nofollow"><code>np.char</code> module</a> can help here:</p>

<pre><code>np.char.add(table_vals.astype(np.bytes_), b'%')
</code></pre>

<p>Using an object array also works well:</p>

<pre><code>np.array("%.2f%%") % table_vals.astype(np.object_)
</code></pre>

python numpy