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

DY92
  • 437
  • 5
  • 18
  • @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 – DY92 Apr 27 '20 at 12:48
  • @MercyDude Because see Edit section above – DY92 Apr 27 '20 at 13:02
  • @MercyDude it looks like yatu has understood the question. But thank you for your effort – DY92 Apr 27 '20 at 13:12

1 Answers1

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)
yatu
  • 86,083
  • 12
  • 84
  • 139