用从索引到另一个的值填充numpy矩阵 [英] Fill numpy matrix with values from an index to another
问题描述
我的问题是用从索引到另一个索引的值填充一个numpy矩阵.
My question is about filling a numpy matrix with values from an index to another.
例如,我有这个矩阵:
> mat = np.zeros((0,5))
> mat
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
例如,假设我要在第一列的第1行到第3列填充mat,值是:1,所以它看起来像这样:
For example, Let's say I want to fill mat from row 1 to 3 at the first column with value : 1 so it will look like this :
> mat
0 0 0 0 0
1 0 0 0 0
1 0 0 0 0
1 0 0 0 0
0 0 0 0 0
这是我尝试过的方法,但是这里将1应用于所有列而不是一个列:
Here's what I have tried but here 1 is applied to all the columns instead of one column :
mat[1:3][1]=1
这是什么问题?
推荐答案
有两个问题:
首先,您没有创建所需的矩阵. np.zeros((0,5))
将不起作用.您应该改用mat = np.zeros((5,5))
.
first of all, you don't create the desired matrix. np.zeros((0,5))
will not work. You should try mat = np.zeros((5,5))
instead.
另一个问题是访问创建的矩阵.要访问从0(含1)到3(含3)的行的第0个元素,您需要调用:
The other issue is accessing created matrix. To access 0th elements of rows from 1 inclusive to 3 inclusive you need to call:
mat[1:4,0]=1
这篇关于用从索引到另一个的值填充numpy矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!