问题描述
用零填充矩阵数组的最有效方法是什么?
What's the most efficient way to pad an array of matrices with zeros?
示例:
# Lets construct an array of 2 matrices from 3 arrays of vectors
import numpy as np
A = np.array([[0,1,2],[3,4,5]]) # 2 vectors
B = np.array([[6,7,8],[9,10,11]]) # 2 vectors
C = np.array([[12,13,14],[15,16,17]]) # 2 vectors
M = np.dstack((A,B,C))
'''
# Result: array([[[ 0, 6, 12],
[ 1, 7, 13],
[ 2, 8, 14]],
[[ 3, 9, 15],
[ 4, 10, 16],
[ 5, 11, 17]]]) #
'''
我想向数组中的每个矩阵元素添加一列和/或一行零,例如:
I want to add a column and/or a row of zeros to every matrix element in the array such as:
'''
# Result: array([[[ 0, 6, 12, 0],
[ 1, 7, 13, 0],
[ 2, 8, 14, 0],
[ 0, 0, 0, 0]],
[[ 3, 9, 15, 0],
[ 4, 10, 16, 0],
[ 5, 11, 17, 0]
[ 0, 0, 0, 0]]]) #
'''
推荐答案
np.pad
可以工作,但是在这种情况下,它是过大的.我们可以直接使用:
np.pad
will work, but for this case it is overkill. We can do it directly with:
3d数组示例(不同的尺寸使更改更明显)
A sample 3d array (different dimensions make changes more obvious)
In [408]: M=np.arange(2*3*4).reshape((2,3,4))
In [409]: M
Out[409]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
具有所需目标形状的空白数组
A blank array of the desired target shape
In [410]: M1=np.zeros((2,4,5),M.dtype)
将M
中的值复制到正确的切片范围内的目标.
Copy values from M
to the target in the right slice range.
In [411]: M1[:,:-1,:-1]=M
In [412]: M1
Out[412]:
array([[[ 0, 1, 2, 3, 0],
[ 4, 5, 6, 7, 0],
[ 8, 9, 10, 11, 0],
[ 0, 0, 0, 0, 0]],
[[12, 13, 14, 15, 0],
[16, 17, 18, 19, 0],
[20, 21, 22, 23, 0],
[ 0, 0, 0, 0, 0]]])
需要这样的副本.无法扩展M
本身的大小. pad
也返回了一个新的数组,并执行了此分配和复制的常规版本.因此,效率问题不多.
A copy like this is required. There's no way of expanding the size of M
itself. pad
returns a new array as well, having performed a general version of this allocate and copy. So there isn't much of an efficiency issue.
您还可以在正确的维度中连接(或附加")0行或一列.但是我已经说明了一步.
You could also concatenate (or 'append') a 0 row or column in the right dimensions. But what I've illustrated does it in one step.
这篇关于用零扩展矩阵的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!