Dan*_*Dan 17 python numpy matplotlib
我正在使用Matplotlib和Numpy来制作一些情节.我希望定义一个函数,给定一个数组返回另一个数组,其值为elementwise,例如:
def func(x):
return x*10
x = numpy.arrange(-1,1,0.01)
y = func(x)
Run Code Online (Sandbox Code Playgroud)
这可以.现在我希望在里面有一个if语句func
,例如:
def func(x):
if x<0:
return 0
else:
return x*10
x = numpy.arrange(-1,1,0.01)
y = func(x)
Run Code Online (Sandbox Code Playgroud)
不幸的是,这会引发以下错误
Traceback (most recent call last):
File "D:\Scripts\test.py", line 17, in <module>
y = func(x)
File "D:\Scripts\test.py", line 11, in func
if x<0:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)
我查看了文档all()
,any()
并且它们不适合我需要的账单.那么有没有一种很好的方法可以像第一个例子那样使函数处理数组元素?
Chr*_*icz 13
用于numpy.vectorize
在将func应用于数组之前将其包装x
:
from numpy import vectorize
vfunc = vectorize(func)
y = vfunc(x)
Run Code Online (Sandbox Code Playgroud)
hur*_*ght 12
我知道这个答案为时已晚,但我很高兴学习NumPy.您可以使用numpy.where自行向量化该函数.
def func(x):
import numpy as np
x = np.where(x<0, 0., x*10)
return x
Run Code Online (Sandbox Code Playgroud)
例子
使用标量作为数据输入:
x = 10
y = func(10)
y = array(100.0)
Run Code Online (Sandbox Code Playgroud)
使用数组作为数据输入:
x = np.arange(-1,1,0.1)
y = func(x)
y = array([ -1.00000000e+00, -9.00000000e-01, -8.00000000e-01,
-7.00000000e-01, -6.00000000e-01, -5.00000000e-01,
-4.00000000e-01, -3.00000000e-01, -2.00000000e-01,
-1.00000000e-01, -2.22044605e-16, 1.00000000e-01,
2.00000000e-01, 3.00000000e-01, 4.00000000e-01,
5.00000000e-01, 6.00000000e-01, 7.00000000e-01,
8.00000000e-01, 9.00000000e-01])
Run Code Online (Sandbox Code Playgroud)
警告:
1)如果x
是掩码数组,则需要使用np.ma.where
,因为这适用于掩码数组.
Bjö*_*lex 10
这应该做你想要的:
def func(x):
small_indices = x < 10
x[small_indices] = 0
x[invert(small_indices)] *= 10
return x
Run Code Online (Sandbox Code Playgroud)
invert
是一个Numpy功能.请注意,这会修改参数.为了防止这种情况,你必须修改和返回copy
的x
.
(我意识到这是一个老问题,但......)
还有一个选项在这里没有提到 - 使用np.choose
.
np.choose(
# the boolean condition
x < 0,
[
# index 0: value if condition is False
10 * x,
# index 1: value if condition is True
0
]
)
Run Code Online (Sandbox Code Playgroud)
虽然不是非常易读,但这只是一个表达式(不是一系列语句),并且不会影响numpy的固有速度(如同np.vectorize
).