1

How can I use range in numpy to get the cell in a area? I can use from:to but it is possible for me to use a list to set the row range?

import numpy as np
mx = np.arange(25).reshape(5,5)
print(mx)
print(mx[1:3, 2:4])
k = 1
print(mx[range(k, k+3), range(k+1, k+5)])

2 Answers 2

2

I don't think you can use range or arange in that way (though see @hpaulj's answer), but you could use slice, which uses the same syntax as range (i.e. you give it a start, a stop, and optionally a step argument):

mx[slice(k, k+3), slice(k+1,k+5)]

This is equivalent to:

mx[k:k+3, k+1:k+5]

For example:

>>> mx[slice(k, k+3), slice(k+1,k+5)]
array([[ 7,  8,  9],
       [12, 13, 14],
       [17, 18, 19]])

>>> mx[k:k+3, k+1:k+5]
array([[ 7,  8,  9],
       [12, 13, 14],
       [17, 18, 19]])

For more info see also the glossary entry for slice objects

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

1 Comment

Actually, mx[1:3,2:4] seems the simplest here.
1

To use a list or array in indexing 2d, you need to think in terms of broadcasting:

In [263]: mx = np.arange(25).reshape(5,5)
In [264]: mx[1:3, 2:4]
Out[264]: 
array([[ 7,  8],
       [12, 13]])
In [265]: mx[np.arange(1,3)[:,None], np.arange(2,4)]
Out[265]: 
array([[ 7,  8],
       [12, 13]])

np.ix_ makes that easier:

In [266]: np.ix_(np.arange(1,3), np.arange(2,4))
Out[266]: 
(array([[1],
        [2]]), array([[2, 3]]))
In [267]: mx[np.ix_(np.arange(1,3), np.arange(2,4))]
Out[267]: 
array([[ 7,  8],
       [12, 13]])

or the same thing with lists:

In [268]: mx[[[1],[2]], [2,3]]
Out[268]: 
array([[ 7,  8],
       [12, 13]])

This is indexing rows 1 and 2, and columns 2 and 3 - in a cartesian sense, not pairwise.

In [269]: mx[[1,2], [2,3]]     # diagonal of the block
Out[269]: array([ 7, 13])

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.