Python 将 numpy 数组复制到另一个数组的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40690248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy numpy array into part of another array
提问by rlee827
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]
[6 7 8]]
If I create a larger array like this:
如果我像这样创建一个更大的数组:
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.]]
How do I efficiently copy a
into b
to get an array like this?
我如何有效地复制a
到b
这样的数组中?
# border of 0 surrounding a to be filled in with other data later
b = [[ 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.]]
I am looking for a function built into numpy
if it exists.
我正在寻找一个内置的函数,numpy
如果它存在的话。
回答by falsetru
You can specify b[1:4, 1:4]
to denote the part:
您可以指定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.]])
回答by NaN
Just as an alternative, should you want a different pad value other than zero, you can use this option
作为替代方案,如果您想要除零以外的不同填充值,您可以使用此选项
>>> 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.]])