1

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?

2
  • Are all of your arrays 3x3, or do you need a more general solution? Commented Feb 3, 2020 at 11:41
  • For this specific problem they are all 3x3 yes, but more general solution would be good too (since I'm learning). Commented Feb 3, 2020 at 11:42

1 Answer 1

4

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]])
Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain np.ix_ a bit more? I am not sure I understand it?
What np.ix_ does here is create an array containing all the pairs of indexes. ix is a list containing the index of the rows where there is a 999. So by giving np.ix_ ix and [0, 2] we are asking np.ix_ to generate the indexes of the values. In that case: ix => [0, 2], np.ix_(ix, [0, 2]) => [[0], [2]], [[0, 2]], a[np.ix_(ix, [0, 2])] => [[a[0, 0], a[0, 2]], [a[2, 0], a[2, 2]]]
You might find useful to check this section of the docs: docs.scipy.org/doc/numpy/reference/… @urbanpečoler

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.