【问题标题】:Is it possible to reshape a Python array stacked in one way into another stacked type? [duplicate]是否可以将以一种方式堆叠的 Python 数组重塑为另一种堆叠类型? [复制]
【发布时间】:2018-06-17 21:06:59
【问题描述】:

我有这个数组:

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)

我想转换成这个数组:

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)

我试过了:

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))

输出:

(3, 2, 2, 4)
(3, 2, 2, 4)
False
True

所以我的两次尝试都没有奏效。我错过了什么?可以只用first_stacked 上的reshape 来完成吗?我担心我的数组是否太大,如果它不仅仅是重塑,这可能是个问题,尽管我的担心可能是没有根据的。

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

所以,工作代码:

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))

输出:

(4, 3, 2, 2)
(3, 2, 2, 4)
(3, 2, 2, 4)
(3, 2, 2, 4)
True
True

【问题讨论】:

    标签: python arrays python-3.x numpy multidimensional-array


    【解决方案1】:

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

    np.moveaxis(first_stacked, 0, -1)
    

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

    np.rollaxis(first_stacked, 0, first_stacked.ndim)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 2014-08-30
    • 1970-01-01
    相关资源
    最近更新 更多