大量对象属性 [英] Numpy array of object attributes

查看:79
本文介绍了大量对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维的对象数组,类似:

I have a multi-dimensional array of objects, something like:

 a = np.array([obj1,obj2,obj3])

对象是具有多个属性的类的实例.假设其中之一是高度,其中之一是长度.要获取相应的长度和高度的多维数组,我要做:

The objects are instances of a class which has several attributes. Let's say one of them is heights and one of them is lengths. To get the corresponding multi-dimensional array of lengths and heights I do:

 lengths = np.array([obj1.length,obj2.length,obj3.length])

 heights = np.array([obj1.height,obj2.height,obj3.height])

这开始使我的代码混乱很多.有更有效的方法吗?例如,我有类似

This is starting to clutter up my code quite a lot. Is there a more efficient way of doing this? For instance, I had something like

 heights = a.height

记住

,但显然不起作用,因为a是我的对象而不是我的对象的数组.但是,有没有类似的事情我可以做,既高效又pythonic?我尝试过类似的

in mind but obviously it doesn't work because a is an array of my objects and not my object. But is there something similar I can do that is efficient and pythonic? I tried something like

 for x in np.nditer(a,flags=['refs_ok']):
    print x.length

看看会发生什么,但是它不起作用,因为nditer以某种方式返回了一个元组.

to see what would happen but it doesn't work because nditer returns a tuple somehow.

有什么想法吗?

推荐答案

您可以向量化函数:

>>> import numpy
>>> 
>>> class Obj(object):
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
... 
>>> arr = numpy.array([Obj(1, 2), Obj(3, 4), Obj(5, 6)])
>>> 
>>> vectorized_x = numpy.vectorize(lambda obj: obj.x)
>>> 
>>> vectorized_x(arr)
array([1, 3, 5])

尽管我不确定您是否真的应该首先存储一个NumPy数组的Python对象.向量化没有比Python循环更有效.存储(n + 1)-D数组会更有效,因为我们可以简单地通过切片来轻松提取内容,这是本机操作,例如

Although I'm not sure if you should really store a NumPy array of Python objects in the first place. Vectorize is no more efficient than a Python loop. It would be more efficient to store an (n+1)-D array, as we could easily extract the contents simply by slicing which is a native operation, e.g.

>>> a = numpy.array([[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10), (11, 12)], [(-13, -14), (-15, -16), (-17, -18)]])
>>> a[:,:,0]
array([[  1,   3,   5],
       [  7,   9,  11],
       [-13, -15, -17]])
>>> a[:,:,1]
array([[  2,   4,   6],
       [  8,  10,  12],
       [-14, -16, -18]])

这篇关于大量对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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