[Numpy-discussion] Structured array? recarray? issue access by attribute name

Wai Yip Tung tungwaiyip@yahoo....
Sun Dec 5 21:44:25 CST 2010


I'm trying to use numpy to manipulate CSV file. I'm looking for feature  
similar to relational database. So I come across a class recarray that  
seems to meet my need. And then I see other references of structured  
array. Are these just different name of the same feature?

Also I encounter a problem trying to access an field by attribute name. I  
have


In [303]: arr = np.array([
    .....:     (1, 2.2, 0.0),
    .....:     (3, 4.5, 0.0)
    .....:     ],
    .....:     dtype=[
    .....:         ('unit',int),
    .....:         ('price',float),
    .....:         ('amount',float),
    .....:     ]
    .....: )

In [304]: data0 = arr.view(recarray)

In [305]: data0.price[0]
Out[305]: 2.2000000000000002



It works fine when I get a price vector and pick the first element of it.  
But if instead I select the first row and try to access its price  
attribute, it wouldn't work



In [306]: data0[0].price
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

c:\Python26\Lib\site-packages\numpy\<ipython console> in <module>()

AttributeError: 'numpy.void' object has no attribute 'price'



Then I come across an alternative way to build a recarray. In that case  
both usage work fine.



In [307]: data1 = np.rec.fromarrays(
    .....:     [[1,3],[2.2,4.5],[0.0,0.0]],
    .....:     names='unit,price,amount')

In [309]: data1.price[0]
Out[309]: 2.2000000000000002

In [310]: data1[0].price
Out[310]: 2.2000000000000002


What's going on here?


Wai Yip



More information about the NumPy-Discussion mailing list