First row of numpy.ones is still populated after referencing another matrix

前端 未结 5 1000
说谎
说谎 2021-01-26 10:01

I have a matrix \'A\' whose values are shown below. After creating a matrix \'B\' of ones using numpy.ones and assigning the values from \'A\' to \'B\' by indexing \'i\' rows an

5条回答
  •  情深已故
    2021-01-26 10:56

    For one thing, as others have mentioned, NumPy uses 0-based indexing. But even once you fix that, this is not what you want to use:

    for i in np.arange(9):
        for j in np.arange(9):
            B[i:j] = A[i:j]
    

    The : indicates slicing, so i:j means "all items from the i-th, up to the j-th, excluding the last one." So your code is copying every row over several times, which is not a very efficient way of doing things.

    You probable wanted to use ,:

    for i in np.arange(8): # Notice the range only goes up to 8
        for j in np.arange(8): # ditto
            B[i, j] = A[i, j]
    

    This will work, but is also pretty wasteful performancewise when using NumPy. A much faster approach is to simply ask for:

    B[:] = A
    

提交回复
热议问题