python - numpy.where() 详细的分步说明/示例

尽管阅读了 the doc,但我无法正确理解 numpy.where() , this post和 this other post .

有人可以提供一维和二维数组的分步注释示例吗?

最佳答案

折腾了一阵子,我想通了,把它们贴在这里希望能帮助到其他人。

直观地说,np.where 就像在问“告诉我在这个数组中的哪个位置,条目满足给定条件”。

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

也可以用来获取数组中满足条件的条目:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

a为二维数组时,np.where()返回row idx的数组,col idx的数组:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))

与一维情况一样,我们可以使用 np.where() 来获取二维数组中满足条件的条目:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

数组([9])


注意,当 a 为 1d 时,np.where() 仍然返回 row idx 的数组和 col idx 的数组,但列的长度为 1,所以后者是空数组。

https://stackoverflow.com/questions/34667282/

相关文章:

linux - 选择 Linux I/O 调度程序

ruby - 找不到 gem 命令

android - adb 不显示 nexus 5 设备

python - 如何在不导入的情况下检查 Python 模块是否存在

python - 未找到 Virtualenv 命令

linux - 仅使用 shell 脚本从文本文件中获取特定行

python - 使用Python在SQLite中插入行后如何检索插入的ID?

linux - 什么包包括 AB Ubuntu 中的 Apache 服务器基准测试工具

python - ConfigParser 中的列表

python - bs4.FeatureNotFound : Couldn't find a tre