Python 函数,该函数用于在a和b之间的条件满足时更改数组中元素的符号
将numpy数组中元素的符号从a更改为b。 我试过这个Python 函数,该函数用于在a和b之间的条件满足时更改数组中元素的符号,python,numpy,Python,Numpy,将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(tes
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()
将numpy导入为np
def do_负片(X、a、b):
lst=[]
对于X中的i:
如果(a试试这个:
X
是2D numpy数组,您必须使用flant()
将其设置为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)
输出:
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
def do_阴性(x,a,b):
结果=x.copy()
结果[(a
def do_negative(x, a, b):
result = x.copy()
result[(a < x) & (x < b)] *= -1
return result