从NumPy中的对象数组获取属性 [英] Getting attributes from arrays of objects in NumPy

查看:142
本文介绍了从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.colorcolors = 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆