【问题标题】:Python: How can I force 1-element NumPy arrays to be two-dimensional?Python:如何强制 1 元素 NumPy 数组为二维?
【发布时间】:2015-07-29 10:44:37
【问题描述】:

我有一段代码可以分割二维 NumPy 数组并返回结果(子)数组。在某些情况下,切片仅索引一个元素,在这种情况下,结果是一个元素数组:

>>> sub_array = orig_array[indices_h, indices_w]
>>> sub_array.shape
(1,)

我怎样才能以一般的方式强制这个数组是二维的?即:

>>> sub_array.shape
(1,1)

我知道sub_array.reshape(1,1) 有效,但我希望能够将它应用到sub_array,一般不用担心其中的元素数量。换句话说,我想编写一个(轻量级)操作,将 shape-(1,) 数组转换为 shape-(1,1) 数组,将 shape-(2,2) 数组转换为一个形状(2,2)数组等。我可以做一个函数:

def twodimensionalise(input_array):
     if input_array.shape == (1,):
         return input_array.reshape(1,1)
     else:
         return input_array

这是我能得到的最好的,还是 NumPy 有更“原生”的东西?

加法:

正如https://stackoverflow.com/a/31698471/865169 中指出的那样,我做错了索引。我真的很想做:

sub_array = orig_array[indices_h][:, indices_w]

indices_h 中只有一个条目时,这不起作用,但是将它与另一个答案中建议的np.atleast_2d 结合起来,我得出:

sub_array = np.atleast_2d(orig_array[indices_h])[:, indices_w]

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

听起来您可能正在寻找atleast_2d。此函数将一维数组的视图作为二维数组返回:

>>> arr1 = np.array([1.7]) # shape (1,)
>>> np.atleast_2d(arr1)
array([[ 1.7]])
>>> _.shape
(1, 1)

已经是 2D(或具有更多维度)的数组保持不变:

>>> arr2 = np.arange(4).reshape(2,2) # shape (2, 2)
>>> np.atleast_2d(arr2)
array([[0, 1],
       [2, 3]])
>>> _.shape
(2, 2)

【讨论】:

    【解决方案2】:

    在定义 numpy 数组时,您可以使用关键字参数ndmin 来指定您需要至少两个维度。 例如

    arr = np.array(item_list, ndmin=2)
    arr.shape
    >>> (100, 1) # if item_list is 100 elements long etc
    

    在问题的示例中,只需执行

    sub_array = np.array(orig_array[indices_h, indices_w], ndmin=2)
    sub_array.shape
    >>> (1,1)
    

    这也可以扩展到更高的维度,不像np.atleast_2d()

    【讨论】:

      【解决方案3】:

      您确定以您想要的方式编制索引吗?在indices_hindices_w 是可广播整数索引数组的情况下,结果将具有indices_hindices_w 的广播形状。因此,如果您想确保结果是 2D,请将索引数组设置为 2D。

      否则,如果您想要 indices_h[i] 和 indices_w[j] 的所有组合(对于所有 i、j),请执行例如顺序索引:

      sub_array = orig_array[indices_h][:, indices_w]
      

      查看documentation 了解有关高级索引的详细信息。

      【讨论】:

      • 你是对的。我没有在这里按我想要的方式索引。我现在看到我可能应该使用网格进行索引。
      • 我现在看到你建议的索引是我想用np.meshgrid做的。
      猜你喜欢
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 2020-09-29
      • 2021-05-13
      • 2021-07-20
      • 1970-01-01
      • 2021-01-17
      • 2015-01-23
      相关资源
      最近更新 更多