【问题标题】:ValueError: operands could not be broadcast together with shapes (2501,201) (2501,)ValueError:操作数无法与形状一起广播 (2501,201) (2501,)
【发布时间】:2018-12-26 13:09:00
【问题描述】:

我是 python 新手,所以请善待。

我正在尝试将两个 Numpy 数组与 np.logical_or 函数进行比较。当我运行以下代码时,
Percentile = np.logical_or(data2 > Per1, data2 < Per2) 上出现错误 行说明

ValueError: 操作数不能与形状一起广播 (2501,201) (2501,)

data = 1st Array

data2 = 2nd Array

Per1 = np.percentile(data, 10, axis=1)

Per2 = np.percentile(data, 90, axis=1)

Percentile = np.logical_or(data2 > Per1, data2 < Per2)

print(Percentile)

我检查了两个数组的形状,它们看起来都具有相同的形状(2501,201)(2501,201)。因此,我很难理解为什么会发生此错误,任何帮助将不胜感激。

【问题讨论】:

    标签: python numpy valueerror array-broadcasting operands


    【解决方案1】:

    如果您检查 Per1 或 Per2 的形状,您会看到它的值为 (2501,)(因为您沿轴 1 取百分位数),因此这两个表达式 data2 &gt; Per1data2 &lt; Per2 都会引发错误,为了使您的代码正常工作,您需要使用reshape 使两个操作数的形状兼容,这会将您的行向量转换为列向量:

    Per1 = np.percentile(data, 10, axis=1).reshape(-1, 1)
    Per2 = np.percentile(data, 90, axis=1).reshape(-1, 1)
    

    【讨论】:

      【解决方案2】:

      您需要添加一个维度(通过使用[:, None]Per1Per2 使它们可广播到数据。

      Percentile = np.logical_or(data2 > Per1[:, None], data2 < Per2[:, None])
      

      【讨论】:

      • 这样排序了。非常感谢。
      猜你喜欢
      • 2017-09-09
      • 2012-10-31
      • 2013-04-07
      • 2012-08-05
      • 2018-08-18
      • 2020-06-20
      • 2014-08-24
      • 2018-02-01
      • 2018-04-25
      相关资源
      最近更新 更多