2

numpy.ma.masked_where用于屏蔽单个值。还有numpy.ma.masked_inside用于掩蔽间隔。

但是我不太明白它应该如何工作。

我发现了这个片段

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使用

mvals = ma.masked_inside(xx, 1.999, 2.001)

但结果不是我想要的,它只是一条直线......我想要这样的东西

整个脚本是这样的:

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正确使用?

4

1 回答 1

2

问题不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)

然后输出看起来几乎就像你链接的那个:

在此处输入图像描述

于 2017-01-17T01:07:28.520 回答