python - 如何使用特定规则在 Python 中按元素比较两个数组?

标签 python arrays numpy compare

假设我有:

numpy.random.seed(20)
a=numpy.random.rand(5000)
b=numpy.random.rand(5000)

我想获得 a[x] > b[x] 的索引,即所有 x 的

此外,我想获得一个 where (a[x-1] < b[x-1]) && (a[x] > b[x]) 的索引.

有人可以帮忙吗?我觉得我必须使用掩码数组,但我不太清楚如何使用。

最佳答案

首先很简单,使用numpy.where:

>>> numpy.where(a>b)
(array([   0,    1,    2, ..., 4993, 4994, 4999]),)

你可以从第二个开始

>>> np.where((a>b) & (np.roll(a, 1) < np.roll(b, 1)))
(array([   5,    9,   17, ..., 4988, 4991, 4999]),)

但是你必须单独处理极端情况。

再一次,@askewchan 给出了 second 的正确表达式,而我没能正确地加 1 :)

>>> np.where((a[1:] > b[1:]) & (a[:-1] < b[:-1]))[0] + 1
array([   5,    9,   17, ..., 4988, 4991, 4999])

关于python - 如何使用特定规则在 Python 中按元素比较两个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20293218/

相关文章:

python-3.x - 如何将 4d numpy 数组转换为 PIL 图像?

python - 具有多个列表和条件的排列

python - 如何从Python中的特定点开始Itertools循环?

c - 用 C 语言逐个读取句子中的单词

python - PCA fit() 运行时警告(在 true_divide 中遇到无效值)

python - 使用 scipy.optimize.root 查找根

python - 打包 Python egg 时如何排除 .gitignore 中的文件?

python - 如何使用 Python 将 NULL 数据插入 MySQL 数据库?

c# - 将多波段 16 位 tiff 图像转换为 8 位 tiff 图像

python - 任何加速 itertool.product 的方法