Getting attributes from arrays of objects in NumPy

后端 未结 2 1876
时光说笑
时光说笑 2020-12-09 20:26

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 Num

相关标签:
2条回答
  • 2020-12-09 21:25

    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.

    0 讨论(0)
  • 2020-12-09 21:26

    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).

    0 讨论(0)
提交回复
热议问题