从NumPy中的对象数组中获取属性

Dav*_*415 6 python numpy

假设我有一个叫Star有属性的类color.我可以得到颜色star.color.

但是如果我有这些Star对象的NumPy数组怎么办呢.获取颜色数组的首选方法是什么?

我可以做到

colors = np.array([s.color for s in stars])
Run Code Online (Sandbox Code Playgroud)

但这是最好的方法吗?如果我可以像其他语言那样做colors = star.colorcolors = star->color其他语言,那将会很棒.在numpy中有一种简单的方法吗?

Sve*_*ach 7

最接近你想要的是使用一个recarray而不是ndarrayPython对象:

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
Run Code Online (Sandbox Code Playgroud)

版画

[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
Run Code Online (Sandbox Code Playgroud)

使用NumPy Python对象数组通常比使用普通对象效率低list,而recarray以更高效的格式存储数据.