Python: Check if a numpy array contains an object with specific attribute
<p>I want to check if there is any object with a specific attribute in my numpy array:</p>

<pre><code>class Test:
def __init__(self, name):
    self.name = name

l = numpy.empty( (2,2), dtype=object)
l[0][0] = Test("A")
l[0][1] = Test("B")
l[1][0] = Test("C")
l[1][1] = Test("D")
</code></pre>

<p>I know that following line of code working for a list, but what is the alternative process for a numpy array?</p>

<pre><code>print numpy.any(l[:,0].name == "A")
</code></pre>

<p>One simple way would be creating your array object by inheriting from Numpy's ndarray object. Then use a custom function for checking the existence of your object based on the name attribute:</p>

<pre><code>In [71]: class Myarray(np.ndarray):
   ....:         def __new__(cls, inputarr):
   ....:                 obj = np.asarray(inputarr).view(cls)
   ....:                 return obj
   ....:         def custom_contain(self, name):
   ....:                 return any(obj.name == name for obj in self.flat)
</code></pre>

<p>Demo:</p>

<pre><code>In [4]: A = np.empty((2,2),dtype=object)    
In [8]: A.flat[:] = [Test("A"), Test("B"), Test("C"), Test("D")]

In [9]: A
Out[9]: 
array([[&lt;__main__.Test instance at 0x7fae0a14ddd0&gt;,
        &lt;__main__.Test instance at 0x7fae0a14de18&gt;],
       [&lt;__main__.Test instance at 0x7fae0a14de60&gt;,
        &lt;__main__.Test instance at 0x7fae0a14dea8&gt;]], dtype=object)

In [11]: A = Myarray(A)

In [12]: A.custom_contain('C')
Out[12]: True

In [13]: A.custom_contain('K')
Out[13]: False
</code></pre>

python python-2.7 numpy