本文介绍了如何使2d numpy数组成为3d数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个形状为(x,y)的2d数组,我想将其转换为形状为(x,y,1)的3d数组.有没有一种很好的Pythonic方式可以做到这一点?
I have a 2d array with shape (x, y) which I want to convert to a 3d array with shape (x, y, 1). Is there a nice Pythonic way to do this?
推荐答案
除了其他答案,您还可以将切片与:
In addition to the other answers, you can also use slicing with numpy.newaxis
:
>>> from numpy import zeros, newaxis
>>> a = zeros((6, 8))
>>> a.shape
(6, 8)
>>> b = a[:, :, newaxis]
>>> b.shape
(6, 8, 1)
甚至是这样(可以使用任意数量的尺寸):
Or even this (which will work with an arbitrary number of dimensions):
>>> b = a[..., newaxis]
>>> b.shape
(6, 8, 1)
这篇关于如何使2d numpy数组成为3d数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!