从NumPy中的对象数组获取属性 [英] Getting attributes from arrays of objects in NumPy
问题描述
比方说,我有一个名为Star
的类,它具有一个属性color
.我可以用star.color
获得颜色.
Let's say I have an class called Star
which has an attribute color
. I can get color with star.color
.
但是如果我有这些Star
对象的NumPy数组怎么办.获得颜色阵列的首选方法是什么?
But what if I have a NumPy array of these Star
objects. What is the preferred way of getting an array of the colors?
我可以做到
colors = np.array([s.color for s in stars])
但这是最好的方法吗?
如果我可以像其他一些语言一样执行colors = star.color
或colors = star->color
等功能,那就太好了.在那儿
numpy中这样做的简单方法?
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?
推荐答案
与您想要的内容最接近的是使用recarray
而不是Python对象的ndarray
:
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
打印
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
使用Python对象的NumPy数组通常比使用普通的list
效率低,而recarray
则以更有效的格式存储数据.
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.
这篇关于从NumPy中的对象数组获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!