1

I am looking for an easy way to modify one field of a numpy structured array of a selected line of it. 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)
b=a.copy()
a[a['name']=='a']['x']=1
print a==b # return [ True  True  True]

In this example, the a==b results should return [False True True].Actually, I would like to selected the line of my array from the 'name' field and modify the value of one field of it (here 'x').

1
  • It's time to go to pandas ;). df=pandas.Dataframe(a) ; df.loc[df.name=='a','x']=1. Commented Apr 18, 2016 at 17:05

1 Answer 1

2

I found the answer... The point is the position of the field and of the mask. You need to apply the mask to the field column, not looking for the field of the masked array :

a['x'][a['name']=='a']=1
print a==b # returns [False  True  True]
Sign up to request clarification or add additional context in comments.

1 Comment

The order of indexing matters because "advanced indexing", such as a[a['name']=='a'], always returns a copy, while "basic indexing" such as a['x'] always returns view. Modifying the view with a['x'][a['name']=='a']=1 affects the original array a, while modifying the copy with a[a['name']=='a']['x']=1 does not affect a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.