处理蒙面纽比阵列

2024-05-14 01:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我蒙蔽了鬼魂阵。在处理每个元素时,我需要首先检查特定元素是否被屏蔽,如果被屏蔽,则需要跳过这些元素。在

我试过这样做:

from netCDF4 import dataset

data=Dataset('test.nc')
dim_size=len(data.dimensions[nc_dims[0]])
model_dry_tropo_corr=data.variables['model_dry_tropo_corr'][:]
solid_earth_tide=data.variables['solid_earth_tide'][:]

for i in range(0,dim_size)
    try :
        model_dry_tropo_corr[i].mask=True
       continue

    except :
        Pass

    try:
         solid_earth_tide[i].mask=True
         continue
    except:
         Pass

     correction=model_dry_tropo_corr[i]/2+solid_earth_tide[i]

有没有其他有效的方法,请告诉我。非常感谢您的建议或意见。在


Tags: 元素datasizemodelvariables屏蔽drync
2条回答

而不是你可以使用的循环

correction = model_dry_tropo_corr/2 + solid_earth_tide

这将创建一个新的掩码数组,其中包含您的答案和掩码。然后可以从新数组访问未屏蔽的值。在

我对这个密码感到困惑

try :
    model_dry_tropo_corr[i].mask=True
   continue

except :
    Pass

我没有安装netCDF4,但是从文档中可以看出,您的变量看起来像是一个numpy.ma掩码数组。在

如果打印此变量的全部或部分内容,并带有shape和dtype之类的属性,则会很有帮助。在

我可以用如下表达式创建一个掩码数组:

^{pr2}$

我可以测试给定元素的掩码是否为真/假:

In [748]: M.mask[2]
Out[748]: False

In [749]: M.mask[3]
Out[749]: True

但如果我先索引

In [754]: M[2]
Out[754]: 2

In [755]: M[3]
Out[755]: masked

In [756]: M[2].mask=True
...
AttributeError: 'numpy.int32' object has no attribute 'mask'

In [757]: M[3].mask=True

所以是的,try/except将跳过掩码设置为True的元素。在

但我认为这样做是很清楚的:

 if model_dry_tropo_corr.mask[i]:
     continue

但这仍然是反复的。在

但是,正如@user3404344所示,您可以用变量执行数学运算。掩蔽会继续下去。但是,如果被屏蔽的值是“坏的”并导致计算中的错误,那么这可能是一个问题。在

如果我定义另一个屏蔽数组

In [764]: N=np.ma.masked_where(np.arange(10)%4==0,np.arange(10))

In [765]: N+M
Out[765]: 
masked_array(data = [  2 4     10   14    ],
             mask = [ True False False  True  True False  True False  True  True],
       fill_value = 999999)

您可以看到在MN中被屏蔽的元素是如何在结果中被屏蔽的

我可以使用compressed方法只给出有效的元素

In [766]: (N+M).compressed()
Out[766]: array([ 2,  4, 10, 14])

在使用遮罩数组进行数学运算时,填充也很方便:

In [779]: N.filled(0)+M.filled(0)
Out[779]: array([ 0,  2,  4,  3,  4, 10,  6, 14,  8,  9])

我可以使用filled来中和问题计算,并仍然屏蔽这些值

In [785]: z=np.ma.masked_array(N.filled(0)+M.filled(0),mask=N.mask|M.mask)

In [786]: z
Out[786]: 
masked_array(data = [  2 4     10   14    ],
             mask = [ True False False  True  True False  True False  True  True],
       fill_value = 999999)

哎哟,我不需要担心隐藏的值会扰乱计算。那个蒙面的人在替我补课

In [787]: (N+M).data   
Out[787]: array([ 0,  2,  4,  3,  4, 10,  6, 14,  8,  9])

In [788]: N.data+M.data    # raw unmasked addition
Out[788]: array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

In [789]: z.data     # same as the (N+M).data
Out[789]: array([ 0,  2,  4,  3,  4, 10,  6, 14,  8,  9])

相关问题 更多 >