0

Suppose inputs are like below.

indexSet1 = [0,1,2]
indexSet2 = [1,2]
A = [[1,2,3],[4,5,6],[7,8,9]]

Then I want to get a matrix whose height is 3 and width is 2 respectively and elements corresponds to indexSet1's value and indexSet2's one. In short, I want to a array [[2,3],[4,5],[7,8]] from A by indexSet1 and indexSet2.

When I code like below, I can not get my desire result.

>>> import numpy as np
>>> np.array(A)[np.array(indexSet1),np.array(indexSet2)]
array([5, 9])

Can anyone know wise methods? Sorry for my poor English. And thank you in advance.

2
  • 2
    Do you mean [[2, 3], [5, 6], [8, 9]] ? or indexSet2 = [0, 1] ? Commented Dec 15, 2014 at 16:33
  • @falsetru Ahh, [[2, 3], [5, 6], [8, 9]] is correct. Commented Dec 15, 2014 at 16:37

2 Answers 2

1

Using nested list comprehension:

>>> indexSet1 = [0,1,2]
>>> indexSet2 = [1,2]
>>> A = [[1,2,3],[4,5,6],[7,8,9]]
>>> [[A[i][j] for j in indexSet2] for i in indexSet1]
[[2, 3], [5, 6], [8, 9]]
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I want!
1

In NumPy you can do something like this:

>>> A = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> A[np.array(indexSet1)[:, None], indexSet2]
array([[2, 3],
       [5, 6],
       [8, 9]])

Comments

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.