[英]Function that changes the sign of elements in array if the condition between a and b meet
将 numpy 数组中元素的符号从 a 更改为 b。 我试过这个。
import numpy as np
def do_negative(X, a, b):
lst = []
for i in X:
if (a<i<b):
lst.append(-i)
else:
lst.append(i)
return X
test = np.array(range(9)).reshape(3,3)
do_negative(test, -1, 3).all()
但这会返回错误ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
输入数据:从 -1 到 3。
输出应该是: np.array([[ 0, -1, -2], [-3, 4, 5], [ 6, 7, 8]])
尝试这个:
X
是 2D numpy 数组,您必须使用flatten()
使其成为 1D。此外,您返回X
而不是返回lst
def do_negative(X, a, b):
lst = []
for i in X.flatten():
if (a < i <= b):
lst.append(-1*i)
else:
lst.append(i)
return np.array(lst).reshape(3,3)
调用函数时删除.all()
do_negative(test, -1, 3)
输出:
array([[ 0, -1, -2],
[-3, 4, 5],
[ 6, 7, 8]])
使用for
循环对数组进行逐元素操作不是 NumPy 应该使用的方式。
这可以通过整个数组操作很容易地完成:
def do_negative(x, a, b):
result = x.copy()
result[(a < x) & (x < b)] *= -1
return result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.