首页 > 解决方案 > 如何为 numpy 元素添加维度?

问题描述

我有一个像这样的 numpy.array

[[1,2,3]
 [4,5,6]
 [7,8,9]]

我怎样才能将其更改为:-

[[[1,0], [2,0], [3,0]]
 [[4,0], [5,0], [6,0]]
 [[7,0], [8,0], [9,0]]]

提前致谢。

标签: pythonarraysnumpy

解决方案


作为a输入数组,您可以使用array-assignment这将适用于通用n-dim输入 -

out = np.zeros(a.shape+(2,),dtype=a.dtype)
out[...,0] = a

样品运行 -

In [81]: a
Out[81]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [82]: out = np.zeros(a.shape+(2,),dtype=a.dtype)
    ...: out[...,0] = a

In [83]: out
Out[83]: 
array([[[1, 0],
        [2, 0],
        [3, 0]],

       [[4, 0],
        [5, 0],
        [6, 0]],

       [[7, 0],
        [8, 0],
        [9, 0]]])

如果你玩broadcasting,这里有一个紧凑的 -

a[...,None]*[1,0]

推荐阅读