Apply numpy.where on condition with either list or numpy.array
<p>I discovered that <code>numpy.where</code> behaves differently when applied on a condition such as <code>foo==2</code> when <code>foo</code> is a list or <code>foo</code> is a <code>numpy.array</code></p>

<pre><code>foo = ["a","b","c"]
bar = numpy.array(["a","b","c"])
numpy.where(foo == "a") # Returns array([])
numpy.where(bar == "a") # Returns array([0])
</code></pre>

<p>I want the same command to make this applicable to either list or numpy.array, and I am concerned about how to perform this efficiently. Is the following ok ?</p>

<pre><code>numpy.where(numpy.array(foo, copy=False) == "a") # Returns array([0])
numpy.where(numpy.array(bar, copy=False) == "a") # Returns array([0])
</code></pre>

<p>Result is as expected, but is this the best way to answer my need ? Using each time <code>numpy.array</code> constructor is the best way to ensure object type ?</p>

<p>Thanks !</p>

<p>If you are really looking for the most <code>numpy</code>-esque solution, use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html" rel="nofollow"><code>np.asarray</code></a>:</p>

<pre><code>numpy.where(numpy.asarray(foo) == "a")
</code></pre>

<p>And if you also want your code to work with subclasses of <code>numpy.ndarray</code>, without "downconverting" them to their base class of <code>ndarray</code>, then use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.asanyarray.html#numpy.asanyarray" rel="nofollow"><code>np.asanyarray</code></a>:</p>

<pre><code>numpy.where(numpy.asanyarray(foo) == "a")
</code></pre>

<p>This works for <code>np.matrix</code> for instance, without converting it to an array. I suppose that this would also ensure that the <code>np.matrix</code> instance doesn't get copied or reconstructed into an array prior to checking.</p>

<p><strong>Note:</strong> I think that copies are made by <code>np.array</code> for lists, because it needs to construct the array object. This can be seen in the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html" rel="nofollow">documentation for <code>np.array</code></a>:</p>

<pre><code>copy : bool, optional
    If true (default), then the object is copied.
    Otherwise, a copy will only be made if __array__ returns a copy, if
    obj is a nested sequence, or if a copy is needed to satisfy any of the
    other requirements (dtype, order, etc.).
</code></pre>

<p><code>np.asarray</code> would also make a copy in this case.</p>

python arrays numpy