Access line by line to a numpy structured array

2019-09-04 07:24发布

问题:

I am trying to access to a structured array line by line by iterating on the values of one field of it but even if the value iterate well, the slice of the array doesn't change. Here is my SWE :

import numpy as np
dt=np.dtype([('name',np.unicode,80),('x',np.float),('y',np.float)])
a=np.array( [('a',0.,0.),('b',0.,0.),('c',0.,0.) ],dtype=dt)
for n in a['name']:
  print n,a['name'==n]

gives me :

a (u'a', 0.0, 0.0)
b (u'a', 0.0, 0.0)
c (u'a', 0.0, 0.0)

At each iteration, I always have the same slice of the array... strange ?

回答1:

The last line is not right. The array index evaluates to True or False rather than doing a lookup of a named column. Try this:

for n in a['name']:
    print n,a[a['name']==n]