dcalmeida
dcalmeida

Reputation: 403

How to use np.where() inside an array with instances of a class?

I have the following class:

class IdFuns(object):
    def __init__(self,i,p,v,u):
        self.i = i
        self.p = p
        self.v = v
        self.u = u

When I put inside a loop I get the following array with instances of the class:

   array([
   <__main__.IdFuns object at 0x7fc8362e8250>,
   <__main__.IdFuns object at 0x7fc8362e8290>,
   <__main__.IdFuns object at 0x7fc8362e82d0>,
   <__main__.IdFuns object at 0x7fc8362e8310>,
   <__main__.IdFuns object at 0x7fc8362e8350>,
   <__main__.IdFuns object at 0x7fc8362e8390>,
   <__main__.IdFuns object at 0x7fc8362e83d0>,
   <__main__.IdFuns object at 0x7fc8362e8410>,
   <__main__.IdFuns object at 0x7fc8362e8450>,
   <__main__.IdFuns object at 0x7fc8362e8490>,
   <__main__.IdFuns object at 0x7fc8362e84d0>,
   <__main__.IdFuns object at 0x7fc8362e8510>,
   <__main__.IdFuns object at 0x7fc8362e8550>], dtype=object)

I want to know how do I use np.where() to search if I have an instance with .i = 1, for example.

Upvotes: 1

Views: 856

Answers (1)

ali_m
ali_m

Reputation: 74232

.i is an attribute of the individual items in your object array, rather than of the array itself. You therefore need to loop over these items in Python, for example using a list comprehension:

bool_idx = [item.i == 1 for item in object_array]

This can then be passed as the first argument to np.where:

locs = np.where(bool_idx)

In general I would suggest you avoid using np.object arrays. Since they don't support vectorized operations they don't really offer any significant performance improvement over a standard Python list. It looks to me as though you might be better off using a structured numpy array or a pandas.DataFrame.

Upvotes: 3

Related Questions