gpt4 book ai didi

python - python 中带有掩码数组的 if 语句

转载 作者:行者123 更新时间:2023-11-30 23:05:17 25 4
gpt4 key购买 nike

我正在尝试使用掩码数组运行(嵌套条件)程序。我使用了相同的函数,没有屏蔽数组并且工作正常。该函数如下所示:

import numpy as np
x = np.random.rand(100)
x = x.reshape(4,25)
x = np.ma.masked_less(x,0.2)
y = np.random.rand(100)
y = y.reshape(4,25)
y = np.ma.masked_less(y,0.2)
z = np.zeros_like(x)

#say that both arrays are masked in the same positions.

for i in range(len(x)):
for j in range(len(y)):
if x[i,j] >= y[i,j]:
if (x[i,j]-y[i,j]) > (z[i,j-1]):
z[i,j] = 0.
else:
z[i,j] = 1.
else:
z[i,j] = z[i,j-1] - (x[i,j]-y[i,j])

我确实希望得到一个具有与输入数据(本例中为 x,y)相同特征(即也被屏蔽)的数组。然而,我得到的结果是,或者是一个完全屏蔽的数组,或者是一个填充了没有屏蔽的值的数组,如下所示:

z = 
masked_array(data =
[[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
...,
[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]],
mask =
[[ True True True ..., True True True]
[ True True True ..., True True True]
[ True True True ..., True True True]
...,
[ True True True ..., True True True]
[ True True True ..., True True True]
[ True True True ..., True True True]],
fill_value = 9.96920996839e+36)

z =
masked_array(data =
[[9.0 9.0 9.0 ..., 9.0 9.0 9.0]
[9.0 9.0 9.0 ..., 9.0 9.0 9.0]
[9.0 9.0 9.0 ..., 9.0 9.0 9.0]
...,
[9.0 9.0 9.0 ..., 9.0 9.0 9.0]
[9.0 9.0 9.0 ..., 9.0 9.0 9.0]
[9.0 9.0 9.0 ..., 9.0 9.0 9.0]],
mask =
[[False False False ..., False False False]
[False False False ..., False False False]
[False False False ..., False False False]
...,
[False False False ..., False False False]
[False False False ..., False False False]
[False False False ..., False False False]],
fill_value = 9.96920996839e+36)

当我实际上想要这样的东西时:

z = 
masked_array(data =
[[9.0 -- -- ..., -- -- --]
[8.7 -- -- ..., -- -- --]
[-- -- -- ..., -- -- --]
...,
[1.0 -- -- ..., -- -- --]
[-- 3.6 -- ..., -- -- --]
[-- -- -- ..., -- -- --]],
mask =
[[ False True True ..., True True True]
[ False True True ..., True True True]
[ True True True ..., True True True]
...,
[ False True True ..., True True True]
[ True False True ..., True True True]
[ True True True ..., True True True]],
fill_value = 9.96920996839e+36)

我已阅读有关屏蔽数组的可用信息以及此处的类似问题,但没有一个对此有令人满意的解释。我想知道条件语句是否有可能以类似于 numpy.where 的方式工作,即它们仅显示此类条件的索引?

最佳答案

还有另一种方法可以进行计算,无需屏蔽数组。如果需要,您仍然可以最后屏蔽 z 数组。

    x = np.random.rand(100)
x = x.reshape(4,25)
y = np.random.rand(100)
y = y.reshape(4,25)

# first if- first if
idxs_1 = ( x >= y) & ((x-y) > (z-1))
z[idxs_1] = 0

# second if-else
idxs_2 = (x>=y) & ((x-y) <= z-1)
z[idxs_2] = 1

# final else
idxs_3 = x < y
idxs_3_p = np.hstack((idxs_3[:, 1:], idxs_3[:,0][:,None])) # reshape so that we shift z by one column left

z[idxs_3] = z[idxs_3_p] - (x[idxs_3] - y[idxs_3])

您需要仔细检查某些测试数据的 bool 索引的正确性。

关于python - python 中带有掩码数组的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33226752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com