将 numpy 数组复制到另一个数组的一部分 [英] Copy numpy array into part of another array
本文介绍了将 numpy 数组复制到另一个数组的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我运行以下:
将 numpy 导入为 npa = np.arange(9)a = a.reshape((3,3))
我会得到这个:
a = [[0 1 2][3 4 5][6 7 8]]
如果我像这样创建一个更大的数组:
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.]]
如何有效地将 a
复制到 b
以获得这样的数组?
#a 周围的 0 边框,稍后填充其他数据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.]]
我正在寻找内置于 numpy
中的函数(如果存在).
解决方案
您可以指定b[1:4, 1:4]
来表示部分:
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?
# 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.
解决方案
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.]])
这篇关于将 numpy 数组复制到另一个数组的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文