You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:如何对指定3D数组进行重塑?

Reshaping a 3D Array in Python

Hey there! Let's work through this 3D array reshaping problem you're dealing with. First, let's break down what we're starting with and what we need to end up with:

Original Array (Shape: (3, 5, 3))

[
 [[ 1, 16, 31], [ 2, 17, 32], [ 3, 18, 33], [ 4, 19, 34], [ 5, 20, 35]],
 [[ 6, 21, 36], [ 7, 22, 37], [ 8, 23, 38], [ 9, 24, 39], [10, 25, 40]],
 [[11, 26, 41], [12, 27, 42], [13, 28, 43], [14, 29, 44], [15, 30, 45]]
]

Target Array (Shape: (3, 3, 5))

[
 [[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]],
 [[16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30]],
 [[31, 32, 33, 34, 35], [36, 37, 38, 39, 40], [41, 42, 43, 44, 45]]
]

Solution with NumPy (Most Efficient)

NumPy makes this kind of multidimensional array manipulation straightforward with axis transposition. Here's how to do it:

  1. Import NumPy and define your original array:
import numpy as np

original_array = np.array([
    [[ 1, 16, 31], [ 2, 17, 32], [ 3, 18, 33], [ 4, 19, 34], [ 5, 20, 35]],
    [[ 6, 21, 36], [ 7, 22, 37], [ 8, 23, 38], [ 9, 24, 39], [10, 25, 40]],
    [[11, 26, 41], [12, 27, 42], [13, 28, 43], [14, 29, 44], [15, 30, 45]]
])
  1. Transpose the axes to reorder the dimensions:
    We need to shift the third dimension (the inner-most values like 1,16,31) to the first position, while keeping the original first and second dimensions in the new second and third positions. This is done with transpose(2, 0, 1):
transformed_array = original_array.transpose(2, 0, 1)
  1. Check the result:
    Printing transformed_array will give you exactly the target structure you need.

Pure Python Solution (No Libraries)

If you prefer not to use NumPy, you can achieve the same result with nested list comprehensions:

original_list = [
    [[ 1, 16, 31], [ 2, 17, 32], [ 3, 18, 33], [ 4, 19, 34], [ 5, 20, 35]],
    [[ 6, 21, 36], [ 7, 22, 37], [ 8, 23, 38], [ 9, 24, 39], [10, 25, 40]],
    [[11, 26, 41], [12, 27, 42], [13, 28, 43], [14, 29, 44], [15, 30, 45]]
]

# Build the transformed list by grouping inner elements across blocks
transformed_list = [
    [
        [sub[elem_idx] for sub in block]
        for block in original_list
    ]
    for elem_idx in range(3)
]

print(transformed_list)

This works by iterating over each position in the inner-most subarrays (0, 1, 2), then collecting those values across all blocks and subarrays to form the new structure.

内容的提问来源于stack exchange,提问作者Luca Fichera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:16:22