Python 嵌套np.where和布尔数组索引问题
概述:我很难理解使用np.where的嵌套掩码会出现什么问题。我希望的是-如果snow为真,则赋值1,如果为假,则评估第二个np。其中,测试snow是否为真,赋值0,如果为假(意味着snow为假,如果为假,则无雪),然后赋值2Python 嵌套np.where和布尔数组索引问题,python,python-2.7,numpy,Python,Python 2.7,Numpy,概述:我很难理解使用np.where的嵌套掩码会出现什么问题。我希望的是-如果snow为真,则赋值1,如果为假,则评估第二个np。其中,测试snow是否为真,赋值0,如果为假(意味着snow为假,如果为假,则无雪),然后赋值2 # open IMS & pull necessary keys. hf = h5py.File(ims_dir + 'ims_daily_snow_cover.h5', 'r') ims = hf['snow_cover'][...] # create an
# open IMS & pull necessary keys.
hf = h5py.File(ims_dir + 'ims_daily_snow_cover.h5', 'r')
ims = hf['snow_cover'][...]
# create an empty parameter to be later written to new hdf file as gap_fill_flag.
dataset_fill = np.zeros(ims.shape)
# loop through fill - branch based on temporal fill or merra fill.
for day in range(len(fill)):
# print len(day)
print day
fill[day] == 2
year = days[day][:4]
# merra fill - more than one consecutive day missing.
if (fill[day-1] == 2) | (fill[day+1] == 2):
# run merra_fill function
# fill with a 2 to signify data are filled from merra.
ims[day, :] = merra_fill(days[day], ims[day, :])
dataset_fill[day, :] = 2
else:
# temporal_fill - less than one consecutive day missing.
snow = ((ims[day - 1:day+2, :] == 1).sum(axis=0)) == 2
no_snow = ((ims[day - 1:day+2, :] == 0).sum(axis=0)) == 2
# nested np.where.
ims[day, :] = np.where(snow == True, 1, np.where(no_snow == True, 0, 2))
dataset_fill[day, :][ims[day, :] < 2] = 1
dataset_fill[day, :][ims[day, :] == 2] = 2
ims[day, :][ims[day, :] == 2] = merra_fill(days[day], ims[day, :])
帮帮我,斯塔克。你是我唯一的希望。来自帮助(np.where):
我怀疑np.where(no_snow…
与帮助(np.where)中的snow==True
具有相同的形状:
我怀疑
np.where(no_snow…
的形状与snow==True
@Jérôme ims是hdf文件中的一个属性,该文件的形状为(65742005409),表示积雪。它被称为一个全局变量。PyCharm建议我使用如果cond为真:
或如果cond:
这将如何应用于这一行代码,结果是否相同?难道no_snow
不是一个空数组吗?@Mahdi我不这么认为?。。。它的长度是2005409
,打印到控制台会呈现[False-False…,False-False-False]
隔离问题表达式,并使用一些小数组对其进行测试。确保您了解在哪里执行的操作。该表达式的用途不明显。@Jérôme ims是hdf文件中的一个属性,其形状为(65742005409),表示积雪。它被称为一个全局变量。PyCharm建议我使用如果cond为真:
或如果cond:
这将如何应用于这一行代码,结果是否相同?难道no_snow
不是一个空数组吗?@Mahdi我不这么认为?。。。它的长度是2005409
,打印到控制台会呈现[False-False…,False-False-False]
隔离问题表达式,并使用一些小数组对其进行测试。确保您了解在哪里执行的操作。该表达式的用途不明显。
ims[day, :] = np.where(snow == True, 1, np.where(no_snow == True, 0, 2))
ValueError: NumPy boolean array indexing assignment cannot assign 2005409 input values to the 0 output values where the mask is true
where(condition, [x, y])
Return elements, either from `x` or `y`, depending on `condition`.
If only `condition` is given, return ``condition.nonzero()``.
Parameters
----------
condition : array_like, bool
When True, yield `x`, otherwise yield `y`.
x, y : array_like, optional
Values from which to choose. `x` and `y` need to have the same
shape as `condition`.