简体   繁体   English

根据python中的值获取数组行和列号

[英]Get array row and column number according to values in python

For example I have a 5*5 np.array like this: 例如,我有一个像这样的5*5 np.array

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? 如果我想获得number<=15的行和列的范围,我该怎么做?

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: 相反,如果我知道行和列的范围,比如ixrange(1,4)jxrange(1,4) ,我怎么能得到这样的数字:

[[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 : 要根据条件获取范围,可以直接应用条件,也可以使用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]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM