简体   繁体   中英

Trying to understand this statement in Python

I came across the following statement in Python:

a = m[:,1].a - m[:,0].a

If I remove the .a parts, I understand that we are trying to subtract the first column in the array from the second column.

What does adding .a do?

Thanks.

When writing my comment I realized that this notation is consistent with a recarray .

Define a dtype with a couple of fields

In [28]: dt = np.dtype([('a',int),('b',float)])

Initialize a recarray with this dtype :

In [29]: arr = np.ones((3,2), dtype=dt).view(np.recarray)
In [30]: arr['a'] = np.arange(6).reshape(3,2)
In [31]: arr
Out[31]: 
rec.array([[(0,  1.), (1,  1.)],
           [(2,  1.), (3,  1.)],
           [(4,  1.), (5,  1.)]], 
          dtype=[('a', '<i4'), ('b', '<f8')])
In [32]: arr.a
Out[32]: 
array([[0, 1],
       [2, 3],
       [4, 5]])

The first field can be accessed with arr['a'] or arr.a (structured array or recarray attribute). Now we can write an expression like yours:

In [34]: arr[:,0].a - arr[:,1].a
Out[34]: array([-1, -1, -1])

Structured arrays are common on SO, especially when loading data from a CSV file. The recarray variant may actually be older, but has fallen out of use. For example, the recfunctions library requires a special import. Apparently the attribute notation isn't that special or useful.

If this isn't right, you need to tell us more about the source of the quote.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM