Python:将维度附加到二维数组

标签 python arrays numpy

假设你有一个数组 (m, m) 并且想把它变成 (n, n)。例如,将 2x2 矩阵转换为 6x6。所以:

[[ 1.  2.]
 [ 3.  4.]]

收件人:

[[ 1.  2.  0.  0.  0.  0.]
 [ 3.  4.  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.  0.  0.  0.]]

这就是我正在做的:

def array_append(old_array, new_shape):
    old_shape = old_array.shape
    dif = np.array(new_shape) - np.array(old_array.shape)
    rows = []
    for i in xrange(dif[0]):
        rows.append(np.zeros((old_array.shape[0])).tolist())
    new_array = np.append(old_array, rows, axis=0)
    columns = []
    for i in xrange(len(new_array)):
        columns.append(np.zeros(dif[1]).tolist())
    return np.append(new_array, columns, axis=1)

使用示例:

test1 = np.ones((2,2))
test2 = np.zeros((6,6))
print array_append(test1, test2.shape)

输出:

[[ 1.  1.  0.  0.  0.  0.]
 [ 1.  1.  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.  0.  0.  0.]]

基于 this回答。但这是一个(imho)简单操作的大量代码。有没有更简洁/pythonic 的方式来做到这一点?

最佳答案

为什么不使用array = numpy.zeros((6,6)),参见numpy docs ...

编辑,哎呀,问题已被编辑...我猜你是想把 ones 放在一个数组的一部分,里面全是 0?然后:

array = numpy.zeros((6,6))
array[0:2,0:2] = 1

如果小矩阵不都是1的值:

array[ystart:yend,xstart:xend] = smallermatrix

关于Python:将维度附加到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4867918/

相关文章:

ios - 如何快速循环保存在后台

python - 如何正确使用 cv2.imwrite 将图像保存在带有 cv2.selectROI 的 openCV 中

python - Keras:获取 imagenet 上预训练模型的标签名称

Python md5 密码值

c++ - 我对这个数组代码有问题,它应该输出用户之前输入的所有数字

C++ Wordsearch 拼图网格二维数组

python - 使用 scipy least_squares 时出现 ValueError

python - ValueError : X has 2 features, 但 MinMaxScaler 期望 1 个特征作为输入

python - 出于性能目的对 Tensorflow 中的一批图像进行推理的正确方法是什么

python - 如何更改txt文件Python中特定列中的行值?