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?
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.
In python, to access array items refer to the index number. we will use the index operator ” [] “ for accessing items from the array.
ndarray. This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With