numpy.ma.masked_where
用于屏蔽单个值。还有用于屏蔽间隔的 numpy.ma.masked_inside
。
但是我不太明白它应该如何工作。
I found this snippet :
import numpy.ma as M
from pylab import *
figure()
xx = np.arange(-0.5,5.5,0.01)
vals = 1/(xx-2)
vals = M.array(vals)
mvals = M.masked_where(xx==2, vals)
subplot(121)
plot(xx, mvals, linewidth=3, color='red')
xlim(-1,6)
ylim(-5,5)
但是,我想做这样的事情(我知道这是行不通的):
mvals = M.masked_where(abs(xx) < 2.001 and abs(xx) > 1.999, vals)
因此我尝试使用 masked_inside
like this :
mvals = ma.masked_inside(xx, 1.999, 2.001)
但结果不是我想要的,它只是一条直线......我想要的是this之类的东西.
整个脚本是这样的:
def f(x):
return (x**3 - 3*x) / (x**2 - 4)
figure()
xx = np.arange(begin, end, precision)
vals = [f(x) for x in xx]
vals = M.array(vals)
mvals = ma.masked_inside(xx, 1.999, 2.001)
subplot(121)
plot(xx, mvals, linewidth=1, c='red')
xlim(-4,4)
ylim(-4,4)
gca().set_aspect('equal', adjustable='box')
show()
如何正确使用 masked_inside
?
问题不在于np.masked_inside
,而在于您在哪个点上以及在哪个数组上使用它(您在之后应用了您的函数!) .
np.ma.masked_inside
只是 np.ma.masked_where
的便利包装:
def masked_inside(x, v1, v2, copy=True):
# That's the actual source code
if v2 < v1:
(v1, v2) = (v2, v1)
xf = filled(x)
condition = (xf >= v1) & (xf <= v2)
return masked_where(condition, x, copy=copy)
如果你这样应用它:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return (x**3 - 3*x) / (x**2 - 4)
# linspace is much better suited than arange for such plots
x = np.linspace(-5, 5, 10000)
# mask the x values
mvals = np.ma.masked_inside(x, 1.999, 2.001)
mvals = np.ma.masked_inside(mvals, -2.001, -1.999)
# Instead of the masked_inside you could also use
# mvals = np.ma.masked_where(np.logical_and(abs(x) > 1.999, abs(x) < 2.001), x)
# then apply the function
vals = f(mvals)
plt.figure()
plt.plot(x, vals, linewidth=1, c='red')
plt.ylim(-6, 6)
然后输出看起来几乎与您链接的那个一样:
我是一名优秀的程序员,十分优秀!