如何访问此数组或矩阵中的元素
array([[-0.0359075 , 0.09684904, -0.03384908, 0.11583249, -0.06620416,
0.31124461, 0.2244373 , -0.22074385, 0.2731958 , 0.35207385,
-0.0232635 , 0.01991997, -0.14457113, -0.22119096, -0.23231329,
-0.25554115, 0.20723027, 0.21642838, 0.17261602, -0.14479494,
-0.02729147, 0.28598186, -0.14462787, -0.06030619, 0.10610376,
0.04492712, -0.03452296, -0.079672 , -0.13708481, -0.04986167,
-0.25361556, -0.03039704]], dtype=float32)
如果这个矩阵是r,那么当我r[4]
访问我收到的元素时
IndexError: index 1 is out of bounds for axis 0 with size 1
当我尝试使用此命令访问时r(4)
我收到了
TypeError: 'numpy.ndarray' object is not callable
答案 0 :(得分:2)
你有一个索引错误,因为你有vector而不是array:
r = np.array([[-0.0359075 , 0.09684904, -0.03384908, 0.11583249, -0.06620416,
0.31124461, 0.2244373 , -0.22074385, 0.2731958 , 0.35207385,
-0.0232635 , 0.01991997, -0.14457113, -0.22119096, -0.23231329,
-0.25554115, 0.20723027, 0.21642838, 0.17261602, -0.14479494,
-0.02729147, 0.28598186, -0.14462787, -0.06030619, 0.10610376,
0.04492712, -0.03452296, -0.079672 , -0.13708481, -0.04986167,
-0.25361556, -0.03039704]], dtype=np.float32)
In [57]: r.shape
Out[57]: (1, 32)
要获得第4个元素,你需要为第2个轴调用3,因为索引从0开始:
In [58]: r[0,3]
Out[58]: 0.11583249
或者您可以使用reshape
从矢量中创建数组:
In [65]: r.reshape(r.size, 1)[3]
Out[65]: array([ 0.11583249], dtype=float32)
注意:您可以从docs找到很多有关索引的有用信息