【问题标题】:How to split/reshape a numpy array如何拆分/重塑一个numpy数组
【发布时间】:2015-01-05 06:06:28
【问题描述】:

我有一个名为“结果”的 numpy 数组,其定义如下

array([1, 2, 3, 4, 5, 6])

但我需要它看起来像这样:

array([1, 2], [3, 4], [5, 6])

如何在 Python 中将“结果”转换为这个新数组?我最终得到的数组仍然需要是一个 numpy 数组。

【问题讨论】:

  • 你想要的结果是不可能的,你缺少一个外部列表:array([[1, 2], [3, 4], [5, 6]])。

标签: python arrays numpy reshape


【解决方案1】:

您可以通过使用reshape 方法直接实现此目的。

例如:

In [1]: import numpy as np

In [2]: arr = np.array([1, 2, 3, 4, 5, 6])

In [3]: reshaped = arr.reshape((3, 2))

In [4]: reshaped
Out[4]: 
array([[1, 2],
       [3, 4],
       [5, 6]])

请注意,在可能的情况下,reshape 将为您提供数组的视图。换句话说,您正在查看与原始数组相同的基础数据:

In [5]: reshaped[0][0] = 7

In [6]: reshaped
Out[6]: 
array([[7, 2],
       [3, 4],
       [5, 6]])

In [7]: arr
Out[7]: array([7, 2, 3, 4, 5, 6])

这几乎总是一个优势。但是,如果您不想要这种行为,您可以随时复制一份:

In [8]: copy = np.copy(reshaped)

In [9]: copy[0][0] = 9

In [10]: copy
Out[10]: 
array([[9, 2],
       [3, 4],
       [5, 6]])

In [11]: reshaped
Out[11]: 
array([[7, 2],
       [3, 4],
       [5, 6]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2017-08-15
    • 2011-10-01
    • 1970-01-01
    • 2017-12-27
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多