Copy numpy array into part of another array

后端 未结 2 2005
耶瑟儿~
耶瑟儿~ 2020-12-10 10:34

If I run the following:

import numpy as np
a = np.arange(9)
a = a.reshape((3,3))

I will get this:

a = [[0 1 2]
     [3 4 5]         


        
2条回答
  •  臣服心动
    2020-12-10 10:55

    You can specify b[1:4, 1:4] to denote the part:

    >>> import numpy as np
    >>> a = np.arange(9)
    >>> a = a.reshape((3, 3))
    >>> b = np.zeros((5, 5))
    >>> b[1:4, 1:4] = a
    >>> b
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  1.,  2.,  0.],
           [ 0.,  3.,  4.,  5.,  0.],
           [ 0.,  6.,  7.,  8.,  0.],
           [ 0.,  0.,  0.,  0.,  0.]])
    
    >>> b[1:4,1:4] = a + 1  # If you really meant `[1, 2, ..., 9]`
    >>> b
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  1.,  2.,  3.,  0.],
           [ 0.,  4.,  5.,  6.,  0.],
           [ 0.,  7.,  8.,  9.,  0.],
           [ 0.,  0.,  0.,  0.,  0.]])
    

提交回复
热议问题