2

I have one 2d array:

>>> input = np.array([[1,2],[3,4]])
>>> input
array([[1, 2],
       [3, 4]])

and I also have this array which has the same number of columns as the input array and each lines contain the index to extract from the matching column of the input array.

>>> indices = np.array([[0],[1]])
>>> indices
array([[0],
       [1]])

In this example I would like to get the following array as output:

array([[1],
       [4]])

Any way I can achieve that?

0

3 Answers 3

3

One way via NumPy array indexing.

A = np.array([[1,2],[3,4]])
idx = np.array([[0],[1]])

res = A[np.arange(A.shape[0])[:, None], idx]

print(res)

[[1]
 [4]]

Note we need to ensure both row and column indexers have the same shape, in this case (n, 1), where n is the number of rows.

Sign up to request clarification or add additional context in comments.

3 Comments

Why not just A[idx, idx]?
A = np.array([[1,2],[3,4]]); idx = np.array([[1],[1]]); res = A[idx, idx] gives [4, 4]. Unless I've misread, OP expects [2, 4].
Ok nvm, after reading OP for the 7th time I get your point ;-)
1

You can just slice the index first:

in_array=np.arange(20).reshape(4,5)
ind=np.array([[0,2],[1,3]])
in_array[ind[:,0],ind[:,1]]
array([2, 8])

Also don't use the names such as input as they're built-in functions of python and you are overwriting them.

Comments

1

You can try this:

#!python
# -*- coding: utf-8 -*-#
#
# Imports
import numpy as np

arr = np.array([[1,2],[3,4]])
idx = np.array([[0],[1]])

ans = arr[idx,idx]
print(ans)

This answers the OP's specific question, however, if we want to make it more general answer, follow the idea of @jpp, and do like this:

# Imports
import numpy as np

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

col_vec1 = np.arange(arr.shape[0])[:, None]
col_vec2 = idx[:, None]

ans = arr[col_vec1, col_vec2]

print(arr[0, 0])  # 1
print(arr[1, 1])  # 5
print(arr[2, 1])  # 8

print(ans)

3 Comments

Yes it works but I'm not sure I understand why though. Any information you could add as to why this works?
Does it work for idx = np.array([[1],[1]]) ?
Ah no you're right. I guess np.array([[0],[1]]) was just a special case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.