rle*_*827 17 python arrays numpy
如果我运行以下内容:
import numpy as np
a = np.arange(9)
a = a.reshape((3,3))
Run Code Online (Sandbox Code Playgroud)
我会得到这个:
a = [[0 1 2]
[3 4 5]
[6 7 8]]
Run Code Online (Sandbox Code Playgroud)
如果我像这样创建一个更大的数组:
b = np.zeros((5,5))
b = [[ 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.]]
Run Code Online (Sandbox Code Playgroud)
如何有效地复制a到b这样的数组?
# border of 0 surrounding a to be filled in with other data later
b = [[ 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.]]
Run Code Online (Sandbox Code Playgroud)
我正在寻找一个内置的功能,numpy如果它存在.
fal*_*tru 21
您可以指定b[1:4, 1:4]表示该部分:
>>> 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.]])
Run Code Online (Sandbox Code Playgroud)
作为替代方案,如果您想要一个非零的填充值,则可以使用此选项
>>> a = np.arange(9.).reshape(3,3)
>>> np.pad(a, 1, 'constant', constant_values=0)
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.]])
>>> np.pad(a, 1, 'constant', constant_values=5)
array([[ 5., 5., 5., 5., 5.],
[ 5., 0., 1., 2., 5.],
[ 5., 3., 4., 5., 5.],
[ 5., 6., 7., 8., 5.],
[ 5., 5., 5., 5., 5.]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22517 次 |
| 最近记录: |