简体   繁体   中英

How to find and replace specific elements in numpy array?

I have a numpy array: a = [[1, 999, 3], [-1, 1, 3], [2, 999, 6]]

I want to find every instance of number 999 and replace it with the average of the two neighbouring numbers ( 999 is always in the middle).

I used the following code to try and make this work: np.where(a == 999, .5 * (a[0] + a[2]), a)

But the output I get appends the value I calculate for the first array: [[1, 2, 3], [-1, 1, 3], [2, 2, 6]] instead of: [[1, 2, 3], [-1, 1, 3], [2, 4, 6]]

How can I fix that?

You can get the row indices where the second column equals 999 , and replace with the mean of the respective first and third columns. I'm using np.ix_ here to avoid integer based indexing, this will instead create a mesh from the input sequences:

a = np.array([[1, 999, 3], [-1, 1, 3], [2, 999, 6]])

ix = a[:,1] == 999
a[ix, 1] = a[np.ix_(ix, [0,2])].mean(1)

print(a)

array([[ 1,  2,  3],
       [-1,  1,  3],
       [ 2,  4,  6]])

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