添加3D掩码数组会导致TypeError:“numpy.bool_”对象不可迭代

ryhaxcpt  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(102)

我有两个3D掩码数组(从气候模型输出的netCDF4文件),我想加在一起。我跟踪了this thread并从中得到了以下(简化)代码:

import numpy as np
from netCDF4 import Dataset
from operator import and_
from numpy.ma.core import MaskedArray

with Dataset(dir + 'V10.nc') as file_V10:
    with Dataset(dir + 'U10.nc') as file_U10:
        raw_V10 = file_V10.variables['V10'][744 : 9503, :, :] ** 2
        raw_U10 = file_U10.variables['U10'][744 : 9503, :, :] ** 2                                                                                                                                                                                                               
        10m_raw_squared = MaskedArray(raw_V10[:].data + raw_U10[:].data, mask=list(map(and_,raw_V10.mask, raw_U10.mask)))

但是,我得到错误消息:

Traceback (most recent call last):
  File "code.py", line 92, in <module>
    10m_raw_squared = MaskedArray(raw_V10[:].data + raw_U10[:].data, mask=list(map(and_,raw_V10.mask, raw_U10.mask)))    
TypeError: 'numpy.bool_' object is not iterable

如果我尝试通过添加mask.astype('str ')将掩码从布尔值更改为字符串(以便使其可迭代),我会得到以下错误消息:

Traceback (most recent call last):
  File "code.py", line 92, in <module>
    10m_raw_squared = MaskedArray(raw_V10[:].data + raw_U10[:].data, mask=list(map(and_,raw_V10.mask.astype('str'),raw_U10.mask.astype('str'))))    
TypeError: unsupported operand type(s) for &: 'str' and 'str'

我还尝试使用for循环将数组添加到一起,但不知何故,无法在不丢失维度和数据的大部分数组元素的情况下使其工作。
如何将两个数据集合并在一起?
编辑:我调用了数据集的类,得到了以下输出:

<class 'numpy.ma.core.MaskedArray'>
eoxn13cs

eoxn13cs1#

您可以使用np.logical_and创建遮罩。

with Dataset(dir + 'V10.nc') as file_V10:
    with Dataset(dir + 'U10.nc') as file_U10:
        raw_V10 = file_V10.variables['V10'][744 : 9503, :, :] ** 2
        raw_U10 = file_U10.variables['U10'][744 : 9503, :, :] ** 2
        mask = np.logical_and(raw_V10.mask, raw_U10.mask)
        10m_raw_squared = MaskedArray(raw_V10[:].data + raw_U10[:].data, mask=mask)

相关问题