Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing numpy array based on attribute of object

Tags:

python

numpy

I have a numpy array that contains a list of objects.

x = np.array([obj1,obj2,obj3])

Here is the definition of the object:

class obj():
    def __init__(self,id):
        self.id = id

obj1 = obj(6)
obj2 = obj(4)
obj3 = obj(2)

Instead of accessing the numpy array based on the position of the object, i want to access it based on the value of id.

For example:

# x[2] = obj3
# x[4] = obj2
# x[6] = obj1

After doing some research, I learned that i could make a structured array:

x = np.array([(3,2,1)],dtype=[('2', 'i4'),('4', 'i4'), ('6', 'i4')])

# x['2'] --> 3

However, the problem with this is that i want the array to take integers as indexes, and dtypes must have a name of type str. Furthermore, i don't think structured arrays can be lists of objects.

like image 701
snowleopard Avatar asked May 17 '26 20:05

snowleopard


1 Answers

You should be able to use filter() here, along with a lambda expression:

np.array(filter(lambda o: o.id == 1, x))

However, as filter() returns a list (in Python 3+, it should return an iterator), you may want to generate a new np.array from the result.

But this does not take care of duplicate keys, if you want to access your data key-like. It is possible to have more than one object with the same id attribute. You might want to control uniqueness of keys.

like image 101
jbndlr Avatar answered May 20 '26 10:05

jbndlr