首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >可以将以一种方式堆叠的Python数组重塑为另一种堆叠类型吗?

可以将以一种方式堆叠的Python数组重塑为另一种堆叠类型吗?
EN

Stack Overflow用户
提问于 2018-06-18 05:06:59
回答 1查看 36关注 0票数 2

我有这个数组:

代码语言:javascript
复制
import numpy as np
shape = (3, 2, 2)
x = np.round(np.random.rand(*shape) * 100)
y = np.round(np.random.rand(*shape) * 100)
z = np.round(np.random.rand(*shape) * 100)
w = np.round(np.random.rand(*shape) * 100)
first_stacked = np.stack((x, y, z, w), axis=0)
print(first_stacked.shape)  # (4, 3, 2, 2)

我想转换成这个数组:

代码语言:javascript
复制
import numpy as np
shape = (3, 2, 2)
x = np.round(np.random.rand(*shape) * 100)
y = np.round(np.random.rand(*shape) * 100)
z = np.round(np.random.rand(*shape) * 100)
w = np.round(np.random.rand(*shape) * 100)
last_stacked = np.stack((x, y, z, w), axis=-1)
print(last_stacked.shape)  # (3, 2, 2, 4)

我试过这个:

代码语言:javascript
复制
new_stacked = [i for i in first_stacked]
new_stacked = np.stack(new_stacked, axis=-1)
other_stacked = np.stack(first_stacked, axis=-1)
print(new_stacked.shape)
print(other_stacked.shape)
print(np.array_equal(new_stacked, last_stacked))
print(np.array_equal(new_stacked, other_stacked))

输出:

代码语言:javascript
复制
(3, 2, 2, 4)
(3, 2, 2, 4)
False
True

所以我的两次尝试都没有成功。我遗漏了什么?在first_stacked上只需要一个reshape就可以做到吗?我担心如果我的数组太大,如果它不仅仅是一个重塑,这可能是一个问题,尽管我的担心可能是没有根据的。

编辑:我在Jupyter Notebook中对x,y,z,w数组进行了两次随机化,第二个值显然不等于第一个值。我很抱歉。不过,如果有更好的办法,我还是很感兴趣。

因此,工作代码:

代码语言:javascript
复制
import numpy as np
shape = (3, 2, 2)
x = np.round(np.random.rand(*shape) * 100)
y = np.round(np.random.rand(*shape) * 100)
z = np.round(np.random.rand(*shape) * 100)
w = np.round(np.random.rand(*shape) * 100)
first_stacked = np.stack((x, y, z, w), axis=0)
print(first_stacked.shape)
last_stacked = np.stack((x, y, z, w), axis=-1)
print(last_stacked.shape)

new_stacked = [i for i in first_stacked]
new_stacked = np.stack(new_stacked, axis=-1)
other_stacked = np.stack(first_stacked, axis=-1)
print(new_stacked.shape)
print(other_stacked.shape)
print(np.array_equal(new_stacked, last_stacked))
print(np.array_equal(new_stacked, other_stacked))

输出:

代码语言:javascript
复制
(4, 3, 2, 2)
(3, 2, 2, 4)
(3, 2, 2, 4)
(3, 2, 2, 4)
True
True
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-18 05:12:31

可以使用numpy.moveaxis将第一个轴移动到最后一个位置。

代码语言:javascript
复制
np.moveaxis(first_stacked, 0, -1)

或者,您可以将轴滚动到所需位置

代码语言:javascript
复制
np.rollaxis(first_stacked, 0, first_stacked.ndim)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50900476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档