How to evaluate and add string to numpy array element
<p>Have this piece of code that I am trying to optimize.
It uses list comprehensions and works. </p>

<pre><code>series1 = np.asarray(range(10)).astype(float)
series2 = series1[::-1]

ntup = zip(series1,series2)
[['', 't:'+str(series2)][series1 &gt; series2] for series1,series2 in ntup ]
 #['', '', '', '', '', 't:4.0', 't:3.0', 't:2.0', 't:1.0', 't:0.0']
</code></pre>

<p>Trying to use <code>np.where()</code> here. Is there a solution with <code>numpy</code>. (Without series being consumed)</p>

<pre><code>series1 = np.asarray(range(10)).astype(float)
series2 = series1[::-1]  

np.where(series1 &gt;  series2 ,'t:'+ str(series2),'' )
</code></pre>

<p>The results is this: </p>

<pre><code>array(['', '', '', '', '', 't:[ 9.  8.  7.  6.  5.  4.  3.  2.  1.  0.]',
       't:[ 9.  8.  7.  6.  5.  4.  3.  2.  1.  0.]',
       't:[ 9.  8.  7.  6.  5.  4.  3.  2.  1.  0.]',
       't:[ 9.  8.  7.  6.  5.  4.  3.  2.  1.  0.]',
       't:[ 9.  8.  7.  6.  5.  4.  3.  2.  1.  0.]'], 
      dtype='|S43')
</code></pre>

<p>Your list comprehensions work just fine for lists, not really need to use arrays.  And for operations like this arrays probably won't give any speed advantage.</p>

<pre><code>In [521]: series1=[float(i) for i in range(10)]
In [522]: series2=series1[::-1]
In [523]: [['', 't:'+str(s2)][s1 &gt; s2] for s1,s2 in zip(series1, series2)]
Out[523]: ['', '', '', '', '', 't:4.0', 't:3.0', 't:2.0', 't:1.0', 't:0.0']
</code></pre>

<p>As @Divaker noted there is a <code>np.char.add</code> function that will perform string operations.  My experience is that they are marginally faster than list operations.  And when you take into account the overhead of creating arrays, they may be slower.</p>

<p>=========</p>

<p>The <code>array</code> version as shown by @Divakar</p>

<pre><code>In [539]: aseries1=np.array(series1)
In [540]: aseries2=np.array(series2)
In [541]: np.where(aseries1&gt;aseries2, np.char.add('t:',aseries2.astype('U3')), '
     ...: ')
Out[541]: 
array(['', '', '', '', '', 't:4.0', 't:3.0', 't:2.0', 't:1.0', 't:0.0'], 
      dtype='&lt;U5')
</code></pre>

<p>A couple of time tests:</p>

<pre><code>In [542]: timeit [['', 't:'+str(s2)][s1 &gt; s2] for s1,s2 in zip(series1, series2)
     ...: ]
100000 loops, best of 3: 15.5 Âµs per loop

In [543]: timeit np.where(aseries1&gt;aseries2, np.char.add('t:',aseries2.astype('U3')), '')
10000 loops, best of 3: 63 Âµs per loop
</code></pre>

python string performance numpy