【问题标题】:Add vectors as objects to numpy array with boolean indexing - 2D arrays work, 1D arrays do not使用布尔索引将向量作为对象添加到 numpy 数组 - 二维数组有效,一维数组无效
【发布时间】:2021-10-24 13:59:33
【问题描述】:

我想将向量分配给一个 numpy 数组以方便使用布尔索引。它奏效了,直到我遇到了一个角落案例。最小的工作示例:

a = np.array([None] * 2)
b = [np.ones(shape=[1, 3]), np.ones(shape=[2, 4])]
a[True, True] = b  # Works as intended

print(a)

但是,当所有数组都是 1D 时,我得到一个错误:

a = np.array([None] * 2)
b = [np.ones(shape=[1, 3]), np.ones(shape=[1, 4])]  # shape of second array changed!
a[True, True] = b  # ValueError: cannot copy sequence with size 2 to array axis with dimension 1

有什么办法可以避免这种情况吗? (我检查了 numpy 版本 v1.19.5 和 v1.21.1)

【问题讨论】:

  • 这似乎是一种无意的行为。一种可行的解决方法是分配一个 [0] 一个扁平数组,然后对其进行整形并重新分配。
  • np.array(b) 是做什么的?
  • 在第二种情况下,它们仍然是二维数组。

标签: python arrays numpy boolean


【解决方案1】:

我解决了。如果您使用 np.where,代码将运行。不知道为什么。示例:

a = np.array([None] * 2)
b = [np.ones(shape=[1, 3]), np.ones(shape=[1, 4])]  # shape of second array changed!
a[np.where([True, True])] = b  # Works as intended.

print(a)

【讨论】:

    【解决方案2】:
    In [436]: a[True,True]=b
    Traceback (most recent call last):
      File "<ipython-input-436-7c0409496970>", line 1, in <module>
        a[True,True]=b
    ValueError: could not broadcast input array from shape (3,) into shape (1,)
    

    看起来这个掩码赋值首先将b 转换为一个数组:

    In [437]: np.array(b)
    <ipython-input-437-cbcacfae87b2>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
      np.array(b)
    Traceback (most recent call last):
      File "<ipython-input-437-cbcacfae87b2>", line 1, in <module>
        np.array(b)
    ValueError: could not broadcast input array from shape (3,) into shape (1,)
    

    但是(正如有经验的用户所知道的那样),尝试从匹配第一个维度 (1) 而不是第二个维度的数组创建一个数组会引发此错误。

    在您的第一种情况下,b 数组在第一个轴上不同,np.array(b) 生成一个 2 元素对象 dtype 数组。

    显然,这些作业不会执行np.array(b)

    In [439]: a[:]=b
    In [440]: a
    Out[440]: array([array([[1., 1., 1.]]), array([[1., 1., 1., 1.]])], dtype=object)
    In [441]: a[[0,1]]=b
    In [442]: a
    Out[442]: array([array([[1., 1., 1.]]), array([[1., 1., 1., 1.]])], dtype=object)
    

    分配一个“正确的”对象 dtype 数组确实有效:

    In [447]: a[[True,True]]=a.copy()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-11
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 2015-07-13
      • 2012-04-10
      • 2019-07-28
      相关资源
      最近更新 更多