0

Suppose I have the following numpy array:

array = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
                  ,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
                  ,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], np.int32)

Then if I use slicing I get:

array[1:5,1:5]

array([[2, 3, 4, 5],
       [2, 3, 4, 5],
       [2, 3, 4, 5],
       [2, 3, 4, 5]], dtype=int32)

I want the similar results, if I want to select rows and columns that have "gaps"(for example 1,3 and 5).

So I want select rows and columns 1,3,5 and get:

array([[2, 4, 6],
       [2, 4, 6],
       [2, 4, 6]], dtype=int32)

But I don't know how to do it.

I want to do the same in tensorflow 2.0 but tf.gather doesnt' help

EDIT: Slicing doesn't solve the problem, when there is no patter in rows and columns numbers

3
  • @yatu It doesn't solve the problem. For example, if i want to select rows and columns 1,2.4,10 there is no pattern and slicing doesn't solve the problem Commented Apr 27, 2020 at 12:48
  • @MercyDude Because see Edit section above Commented Apr 27, 2020 at 13:02
  • @MercyDude it looks like yatu has understood the question. But thank you for your effort Commented Apr 27, 2020 at 13:12

1 Answer 1

1

In the case of wanting to index on a given list of indices, and you're expecting the behavior you'd get with slicing, you have np.ix:

ix = [1,3,5]
array[np.ix_(ix,ix)]

array([[2, 4, 6],
       [2, 4, 6],
       [2, 4, 6]])

Not sure how this is exactly done in tensorflow, but the idea is to add a new axis to one of the arrays (this is internally handled by np.ix_). In pytorch this could be done with:

a[ix.view(-1,1), ix]

tensor([[2, 4, 6],
        [2, 4, 6],
        [2, 4, 6]], dtype=torch.int32)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.