python-增加数组大小并将新元素初始化为零 [英] python - increase array size and initialize new elements to zero
问题描述
我有一个大小为2 x 2的数组,我想将大小更改为3 x4.
I have an array of a size 2 x 2 and I want to change the size to 3 x 4.
A = [[1 2 ],[2 3]]
A_new = [[1 2 0 0],[2 3 0 0],[0 0 0 0]]
我尝试了3个形状,但没有,附加只能附加行,不能附加列.我不想遍历每一行来添加列.
I tried 3 shape but it didn't and append can only append row, not column. I don't want to iterate through each row to add the column.
是否有任何矢量化方法可以像在MATLAB中那样:A(:,3:4) = 0;
和A(3,:) = 0;
将A
从2 x 2转换为3 x4.我在想是否有类似的方法在python中?
Is there any vectorized way to do this like that of in MATLAB: A(:,3:4) = 0;
and A(3,:) = 0;
this converted the A
from 2 x 2 to 3 x 4. I was thinking is there a similar way in python?
推荐答案
In Python, if the input is a numpy array, you can use np.lib.pad
to pad zeros around it -
import numpy as np
A = np.array([[1, 2 ],[2, 3]]) # Input
A_new = np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0)) # Output
样品运行-
In [7]: A # Input: A numpy array
Out[7]:
array([[1, 2],
[2, 3]])
In [8]: np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0))
Out[8]:
array([[1, 2, 0, 0],
[2, 3, 0, 0],
[0, 0, 0, 0]]) # Zero padded numpy array
如果您不想对要填充多少个零的 进行运算,则可以在给定输出数组大小的情况下让代码为您完成-
If you don't want to do the math of how many zeros to pad, you can let the code do it for you given the output array size -
In [29]: A
Out[29]:
array([[1, 2],
[2, 3]])
In [30]: new_shape = (3,4)
In [31]: shape_diff = np.array(new_shape) - np.array(A.shape)
In [32]: np.lib.pad(A, ((0,shape_diff[0]),(0,shape_diff[1])),
'constant', constant_values=(0))
Out[32]:
array([[1, 2, 0, 0],
[2, 3, 0, 0],
[0, 0, 0, 0]])
或者,您可以从零初始化输出数组开始,然后从A
-
Or, you can start off with a zero initialized output array and then put back those input elements from A
-
In [38]: A
Out[38]:
array([[1, 2],
[2, 3]])
In [39]: A_new = np.zeros(new_shape,dtype = A.dtype)
In [40]: A_new[0:A.shape[0],0:A.shape[1]] = A
In [41]: A_new
Out[41]:
array([[1, 2, 0, 0],
[2, 3, 0, 0],
[0, 0, 0, 0]])
在MATLAB中,您可以使用 padarray
-
In MATLAB, you can use padarray
-
A_new = padarray(A,[1 2],'post')
样品运行-
>> A
A =
1 2
2 3
>> A_new = padarray(A,[1 2],'post')
A_new =
1 2 0 0
2 3 0 0
0 0 0 0
这篇关于python-增加数组大小并将新元素初始化为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!