Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting attributes from arrays of objects in NumPy

Tags:

python

numpy

Let's say I have an class called Star which has an attribute color. I can get color with star.color.

But what if I have a NumPy array of these Star objects. What is the preferred way of getting an array of the colors?

I can do it with

colors = np.array([s.color for s in stars])

But is this the best way to do it? Would be great if I could just do colors = star.color or colors = star->color etc like in some other languages. Is there an easy way of doing this in numpy?

like image 402
Dave31415 Avatar asked Mar 20 '12 17:03

Dave31415


People also ask

What attribute is used to retrieve the number of elements in an array NumPy?

len() is the Python built-in function that returns the number of elements in a list or the number of characters in a string. For numpy. ndarray , len() returns the size of the first dimension.

How do you access an array of objects in Python?

In python, to access array items refer to the index number. we will use the index operator ” [] “ for accessing items from the array.

What is NumPy explain about array attributes?

ndarray. This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array.


2 Answers

The closest thing to what you want is to use a recarray instead of an ndarray of Python objects:

num_stars = 10
dtype = numpy.dtype([('x', float), ('y', float), ('colour', float)])
a = numpy.recarray(num_stars, dtype=dtype)
a.colour = numpy.arange(num_stars)
print a.colour

prints

[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]

Using a NumPy array of Python objects usually is less efficient than using a plain list, while a recarray stores the data in a more efficient format.

like image 75
Sven Marnach Avatar answered Sep 20 '22 05:09

Sven Marnach


You could use numpy.fromiter(s.color for s in stars) (note lack of square brackets). That will avoid creating the intermediate list, which I imagine you might care about if you are using numpy.

(Thanks to @SvenMarnach and @DSM for their corrections below).

like image 41
Marcin Avatar answered Sep 22 '22 05:09

Marcin