[英]Numpy zeros 2d array: substituting elements at specific indices
For a function I have to write again for CodeSignal, I create an 'empty' matrix with numpy called 'result'.对于我必须为 CodeSignal 再次编写的函数,我创建了一个名为“result”的 numpy 的“空”矩阵。 During the course of a for loop, I want to add 1s to certain elements of this zeros matrix:
在 for 循环过程中,我想向这个零矩阵的某些元素添加 1:
matrix = [[True, False, False],
[False, True, False],
[False, False, False]]
matrix = np.array(matrix) ## input matrix
(row, col) = matrix.shape
result = np.zeros((row,col), dtype=int) ## made empty matrix of same size
for i in range(0, row):
for j in range(0, col):
mine = matrix[i,j],[i,j]
if mine[0] == True: ##for indices in input matrix where element is called True..
result[i+1,j+1][i+1,j+1] = 1 ##..replace neighbouring elements with 1 (under construction ;) )
print(result)
My very first problem comes with the last part, substituting elements at given indices with another value.我的第一个问题出现在最后一部分,用另一个值替换给定索引处的元素。 Eg result[1,1][1,1] = 1 I always get the error
例如 result[1,1][1,1] = 1 我总是得到错误
TypeError: object does not support item assignment
类型错误:对象不支持项目分配
and this happened after setting np.zeros to various object types - int32, int8, complex, float64...这发生在将 np.zeros 设置为各种对象类型之后 - int32、int8、complex、float64 ......
If I try:如果我尝试:
Eg result[1,1][1,1] == 1例如 result[1,1][1,1] == 1
I get:我得到:
IndexError: invalid index to scalar variable.
索引错误:标量变量的索引无效。
So what is the way to change or add elements to 2d np arrays at specific locations?那么在特定位置更改或添加元素到 2d np 数组的方法是什么?
It makes no sense t write:写是没有意义的:
matrix[i,j][i,j]
The matrix is a 2d array, so that means that matrix[i,j]
is a scalar, not an array.矩阵是一个二维数组,所以这意味着
matrix[i,j]
是一个标量,而不是一个数组。 Applying 0[i,j]
is non-sensical.应用
0[i,j]
是没有意义的。
You can implement this as:您可以将其实现为:
for i in range(row
-1):
for j in range(col
-1):
if matrix[i,j]:
result[i+1,j+1] = 1
here you thus will "shift" the values of matrix
one to the right, and one down.因此,您将在此处将
matrix
的值“移动”一到右侧,再向下移动一。 But then you better perform this with:但是,您最好使用以下方法执行此操作:
result[1:,1:] = matrix[:-1,:-1]
This then gives us:这给了我们:
>>> result
array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.