Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

python - How to make a 2d numpy array a 3d array?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...