将numpy数组复制到另一个数组的一部分 [英] Copy numpy array into part of another array

查看:1465
本文介绍了将numpy数组复制到另一个数组的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行以下命令:

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

我会得到这个:

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.]]

如何有效地将a复制到b中以获得这样的数组?

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.]]

我正在寻找numpy内置的功能(如果存在).

I am looking for a function built into numpy if it exists.

推荐答案

您可以指定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.]])

这篇关于将numpy数组复制到另一个数组的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆