numpy:在新维度中堆叠矩阵重复项 [英] Numpy: stack duplicates of matrix in new dimension

查看:938
本文介绍了numpy:在新维度中堆叠矩阵重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3x3的numpy数组,我想创建一个3x3xC的矩阵,其中新维度由原始3x3数组的精确副本组成.我确定这是在某个地方被问到的,但是我找不到最佳的方法.我想出了如何对一个简单的一维数组x执行此操作:

I have a 3x3 numpy array and I want to create a 3x3xC matrix where the new dimension consists of exact copies of the original 3x3 array. I am sure this is asked somewhere but I couldn't find the best way. I worked out how to do this for a simple 1 dimensional array x:

new_x = np.tile(np.array(x, (C, 1))

重复该数组,然后执行:

which repeats the array, then do:

np.transpose(np.expand_dims(new_x, axis=2),(2,1,0))

会扩展尺寸并切换轴,以便在第3维中重复数组(尽管这样做有效,但我不确定这是否是最好的方法)-什么是最有效的方法这对于一般的nxn numpy数组?

which expands the dimension and switches the axis so that the array is repeated in the 3rd dimension (although this works I'm not sure if this is the best way to do it either) - what is the most efficient way to do this for a general n x n numpy array?

推荐答案

对于只读版本,可以使用broadcast_to:

For a readonly version, broadcast_to can be used:

In [370]: x = np.arange(9).reshape(3,3)
In [371]: x
Out[371]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
In [372]: x = np.broadcast_to(x[..., None],(3,3,10))
In [373]: x
Out[373]: 
array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]],

       [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
        [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]],

       [[6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
        [7, 7, 7, 7, 7, 7, 7, 7, 7, 7],
        [8, 8, 8, 8, 8, 8, 8, 8, 8, 8]]])

或使用repeat:

In [378]: x=np.repeat(x[...,None],10,2)
In [379]: x
Out[379]: 
array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]],

       [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
        [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]],

       [[6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
        [7, 7, 7, 7, 7, 7, 7, 7, 7, 7],
        [8, 8, 8, 8, 8, 8, 8, 8, 8, 8]]])

这是一个较大的数组,其元素可以单独更改.

This is a larger array, whose elements can be changed individually.

这篇关于numpy:在新维度中堆叠矩阵重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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