For example I have a 5*5 np.array
like this:
a=[[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]]
if I want to get the range of row and column where number<=15
, how can I do this?
On the contrary, if I know the range of row and column, like i
in xrange(1,4)
and j
in xrange(1,4)
, how can I get the number like:
[[7,8,9],
[12,13,14],
[17,18,19]]
To get the range based on a condition, you can either apply the condition directly, or use np.where
:
>>> a
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]])
>>> a < 15
array([[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, False],
[False, False, False, False, False],
[False, False, False, False, False]], dtype=bool)
>>> np.where(a < 15)
(array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]),
array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3]))
In the latter case, the return value is a tuple of the matching indices.
To achieve the opposite operation, you can simply slice your array :
>>> ar[1:4, 1:4]
array([[ 7, 8, 9],
[12, 13, 14],
[17, 18, 19]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.