2

If I have a multi-dimensional numpy array like:

a = np.array([[0, 1, 2], 
              [3, 4, 5], 
              [6, 7, 8]])

How can I get the values at certain index positions in one step? For example, if were to define pairs of indices like:

indices = [[0,0], [1,1], [2,2]]

I would like:

a[indices] = [0, 4, 8]

Note that this does work for one-dimensional arrays (Python: How to get values of an array at certain index positions?), but I cannot see how to get this to work in more than one dimension. I am using Python 3.7.

3
  • 1
    [ a[pair[0]][pair[1]] for pair in indices ] Commented Feb 5, 2020 at 15:59
  • 2
    a[ [0,1,2], [0,1,2] ]. Use a list or array for each dimensiion. Commented Feb 5, 2020 at 16:38
  • 1
    docs.scipy.org/doc/numpy/reference/… Commented Feb 5, 2020 at 17:01

2 Answers 2

1

As in the one-dimensional answer you linked, you can do this elegantly in 2 dimensions with numpy:

a = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
rows, columns = zip([0, 0], [1, 1], [2, 2])
print(a[rows, columns])

The output of the print will be:

array([0, 4, 8])
Sign up to request clarification or add additional context in comments.

Comments

1

Adapted from Prasanna's comment

a = [[0 1 2]
     [3 4 5]
     [6 7 8]]
indices = [[0,0], [1,1], [2,2]]

a[indices] = [a[pair[0]][pair[1]] for pair in indices]

This works by using a for each loop, iterating through each pair in the array of indices, and then adding the values at each given index to your final result.

pair is each pair in the indices array, and represents each index pair in indices. In your example, it will be [0,0] in the first iteration, [1,1] in the second, and [2,2] in the third.

2 Comments

Just so you know, you can not do a[indices]. Although the RHS of the assignment will give you the things you need, the LHS of the assignment doesn't make sense.
I'm not in my best state of mind right now, but I will take a look at it and update my answer accordingly once I get a bit of sleep and can wrap my mind around what you're saying. Just to clarify, LHS/RHS = left/right hand side? Also, how tf do I add a line break to a comment. \n and <br> aren't working, and enter key just saves the comment.

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.