【问题标题】:numpy filtering 2Dnumpy 过滤 2D
【发布时间】:2021-09-06 14:52:00
【问题描述】:

我有一个示例 2D np 数组,如下所示:

x = np.random.normal(loc = -1, scale = 0.2, size = (100, 2))

x.shape
# (100, 2)

# Visualizing the distribution:
plt.scatter(x[:, 0], x[:, 1])
plt.show()

我想过滤值: 选择沿 x 轴小于或等于 -1.3 的所有值以及沿 y 轴小于或等于 -0.9 的所有值。基本上就是把图左下角方框内的4个点拍下来。

这是我的代码:

x[x[:, 0] <= -1.3, x[:, 1] <= -0.9]

但这给出了错误:

IndexError:布尔索引与维度上的索引数组不匹配 1个;维度为 2,但对应的布尔维度为 100

【问题讨论】:

  • 错误信息表明:您正试图在布尔表达式的索引处访问数组x

标签: python python-3.x numpy numpy-slicing


【解决方案1】:

您可以使用元素乘积组合两个布尔掩码,然后用它索引x

>>> x[(x[:, 0] <= -1.3)*(x[:, 1] <= -0.9)]
array([[-1.41242713, -1.0017676 ],
       [-1.30424828, -1.20114282],
       [-1.3234422 , -1.29396616]])

【讨论】:

    【解决方案2】:

    您可以尝试只添加运算符 for 和 &amp;,如下所示:

    x[(x[:, 0] <= -1.3) & (x[:, 1] <= -0.9)]
    

    【讨论】:

    • 正确的代码应该是x[(x[:, 0] &lt;= -1.3) &amp; (x[:, 1] &lt;= -0.9)]。您的代码给出了错误:“TypeError: ufunc 'bitwise_and' not supported for the input types, and the input could not be safe to force to any supported types based on the cast rule ''safe''”
    猜你喜欢
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2020-02-13
    • 2022-12-13
    • 1970-01-01
    相关资源
    最近更新 更多