python - 增加数组大小并将新元素初始化为零

标签 python arrays

我有一个大小为 2 x 2 的数组,我想将大小更改为 3 x 4。

A = [[1 2 ],[2 3]]
A_new = [[1 2 0 0],[2 3 0 0],[0 0 0 0]]

我尝试了 3 种形状,但它没有,而且追加只能追加行,不能追加列。我不想遍历每一行来添加列。

有没有像 MATLAB 中那样的矢量化方法:A(:,3:4) = 0;A(3,:) = 0; 这将 A 从 2 x 2 转换为 3 x 4。我在想在 python 中有类似的方法吗?

最佳答案

在Python中,如果输入是一个numpy数组,可以使用np.lib.pad在它周围填充零 -

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

sample 运行-

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

如果您不想计算要填充多少个零的数学,您可以让代码在给定输出数组大小的情况下为您完成 -

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 -

放回那些输入元素
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 -

A_new  = padarray(A,[1 2],'post')

sample 运行-

>> 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 - 增加数组大小并将新元素初始化为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30229104/

相关文章:

python - 如何使用 Python 在 OpenCV 中裁剪图像

c - 通过循环将数组传递给 "isalpha"

python - 从子类中的属性中删除属性(getter/setter)

python - Maya Python 更新属性

python - 如何使用 py2exe 将我的 scrapy spider 构建为 exe 文件?

javascript - Angular 数组不更新 View

c++ - 计算数组中的反转次数

python - 扩展 numpy 掩码

c# - 哪个更好?数组、ArrayList 或 List<T>(在性能和速度方面)

javascript - 正则表达式:如何删除所有未连接到图形的字符(特定字符旁边)