Logical operations with array of strings in Python
<p>I know the following logical operation works with numpy: </p>

<pre><code>A = np.array([True, False, True])
B = np.array([1.0, 2.0, 3.0])
C = A*B = array([1.0, 0.0, 3.0])
</code></pre>

<p>But the same isn't true if B is an array of strings. Is it possible to do the following:   </p>

<pre><code>A = np.array([True, False, True])
B = np.array(['eggs', 'milk', 'cheese'])
C = A*B = array(['eggs', '', 'cheese'])
</code></pre>

<p>That is a string multiplied with False should equal an empty string. Can this be done without a loop in Python (doesn't have to use numpy)?</p>

<p>Thanks!</p>

<p><code>np.char</code> applies string methods to elements of an array:</p>

<pre><code>In [301]: np.char.multiply(B, A.astype(int))
Out[301]: 
array(['eggs', '', 'cheese'], 
      dtype='&lt;U6')
</code></pre>

<p>I had to convert the boolean to integer, and place it second.</p>

<p>Timing in other questions indicates that <code>np.char</code> iterates and applies the Python methods.  Speed's about the same as for list comprehension.</p>

<p>For in-place change, use masked assignment instead of <code>where</code></p>

<pre><code>In [306]: B[~A]=''
In [307]: B
Out[307]: 
array(['eggs', '', 'cheese'], 
      dtype='&lt;U6')
</code></pre>

python string numpy logical-operators