gpt4 book ai didi

python - 在 Python 中查找数组中满足 inf < element < sup 的元素

转载 作者:行者123 更新时间:2023-11-28 22:18:17 25 4
gpt4 key购买 nike

给定一组未排序的点,我需要在给定的时间间隔内替换它们。我想到的最简单的方法是

import numpy as np

def v1(array,inf,sup):
for i in range(len(array)):
if inf<array[i]<sup:
array[i]-=10
return array

有人建议我使用 np.where。如果只有一个 bool 条件,它可以顺利运行:

def v2(array,sup):
array[np.where(array < sup)[0]]-=10
return array

但与 infsup 值相同的设置,即

array[np.where(inf < array < sup)[0]]-=10

会报错

ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all().

我必须做一些笨拙的事情,比如在两个条件下使用 np.where 两次,然后将两个结果索引数组相交......

def v2(array,inf,sup):
i=list(set.intersection(set(np.where(array>inf)[0]),set(np.where(array<sup)[0])))
array[i]-=10
return array

建议?

最佳答案

使用 &np.where 有多个条件:

array[np.where((inf < array) & (array < sup))[0]] -= 10

或者没有np.where:

array[(inf < array) & (array < sup)] -= 10

关于python - 在 Python 中查找数组中满足 inf < element < sup 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50644639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com