[英]Python numpy array index can be -1?
I'm trying out opencv samples from https://github.com/Itseez/opencv/blob/master/samples/python2/letter_recog.py and I need help deciphering this code.. 我正在尝试从https://github.com/Itseez/opencv/blob/master/samples/python2/letter_recog.py获取 opencv示例,我需要帮助来解密此代码。
new_samples = np.zeros((sample_n * self.class_n, var_n+1), np.float32)
new_samples[:,:-1] = np.repeat(samples, self.class_n, axis=0)
new_samples[:,-1] = np.tile(np.arange(self.class_n), sample_n)
I know what np.repeat
and np.tile
are, but I'm not sure what new_samples[:,:-1]
or new_samples[:,-1]
are supposed to do, with the -1 index. 我知道
np.repeat
和np.tile
是什么,但是我不确定使用-1索引应该做什么new_samples[:,:-1]
或new_samples[:,-1]
。 I know how numpy
array indexing works, but have not seen this case. 我知道
numpy
数组索引的工作原理,但是没有看到这种情况。 I could not find solutions from searching. 我无法通过搜索找到解决方案。
Python slicing and numpy slicing are slightly different. Python切片和numpy切片略有不同。 But in general
-1
in arrays or lists means counting backwards (from last item). 但通常数组或列表中的
-1
表示倒数(从最后一项开始)。 It is mentioned in the Information Introduction for strings as: 在信息介绍中提到的字符串为:
>>> word = 'Python'
>>> word[-1] #last character
'n'
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
>>> squares[-1]
25
This can be also expanded to numpy array indexing as in your example. 就像您的示例一样,它也可以扩展为numpy数组索引 。
new_samples[:,:-1]
means all rows except the last columns new_samples[:,:-1]
表示除最后一列外的所有行
new_samples[:,-1]
means all rows and last column only new_samples[:,-1]
表示仅所有行和最后一列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.