【问题标题】:Python numpy reshape 3d list into 2d arrayPython numpy 将 3d 列表重塑为 2d 数组
【发布时间】:2019-09-12 14:37:19
【问题描述】:

我想转换

编辑:下面的代码是列表的 3D 列表,

[
    [ 
        [
            [1,2,3,],
            [4,5,6,],
        ],
        [
            [7,8,9,],
            [10,11,12,], 
        ],
    ],
    [ 
        [
            [A,B,C,],
            [D,E,F,], 
        ],
        [
            [G,H,I,],
            [J,K,L,], 
        ],
    ],
]

进入

[

[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12],
[A,B,C],
[D,E,F],
[G,H,I],
[J,K,L]

]

我试过 numpy.flatten 但没有成功 https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html

【问题讨论】:

  • 你试过my_array.reshape(8, 3)吗?
  • 由于列表中有字符和数字,我建议使用 pandas 而不是 numpy
  • 你想要什么dtype?什么是AB 等。如图所示,这些是变量,而不是字符串。因此,它们必须具有值,在 Python 中可以是任何值。变量 id 不会显示在实际列表(或数组)中。

标签: python numpy reshape flatten


【解决方案1】:

重塑是你的工具。

这是一个独立的例子:

import numpy as np
a = np.array([
    [[[1,2,3] , [4,5,6]],
     [[7,8,9] , [10,11,12]]],
    [[[13,14,15] , [16,17,18]],
     [[19,20,21] , [22,23,24]]]
    ])

a.shape
>>> (2, 2, 2, 3)

a.reshape(8,3)
>>> array([[ 1,  2,  3],
>>>        [ 4,  5,  6],
>>>        [ 7,  8,  9],
>>>        [10, 11, 12],
>>>        [13, 14, 15],
>>>        [16, 17, 18],
>>>        [19, 20, 21],
>>>        [22, 23, 24]])

【讨论】:

  • a.reshape(-1,3) 如果您不想预先计算行数。
  • 感谢 Jurgen 和@Dan。但我发现我的代码是列表的 3D 列表,而不是 3D 数组。我编辑了我的问题:如何将列表的 3D 光照转换为 2D 数组。
  • @BrigitteCharpent 你可以使用np.array()list在两者之间进行转换,仍然使用这种方法
  • 感谢大家。我很难将每个列表级别转换为数组级别。最后,我用简单的 Python 简单地遍历了我的列表。
猜你喜欢
  • 2017-09-18
  • 2016-05-22
  • 2016-01-17
  • 2021-03-21
  • 1970-01-01
  • 2015-10-19
  • 2019-06-26
  • 2019-07-10
  • 1970-01-01
相关资源
最近更新 更多