Skip to main content
 首页 » 编程设计

python之花式索引中的多个条件

2025年05月04日11mate10pro

我是 python 的新手,正在尝试对光栅图像进行一些简单的分类。 基本上,我将 TIF 图像读取为二维数组,并对其进行一些计算和操作。对于分类部分,我正在尝试为陆地、水和云创建 3 个空数组。这些类会在多个条件下被赋值1,最终分别赋值为landclass=1,waterclass=2,cloudclass=3。

显然我可以在一种情况下将数组中的所有值赋给 1 像这样:

     crop = gdal.Open(crop,GA_ReadOnly) 
     crop = crop.ReadAsArray() 
     rows,cols = crop.shape 
     mode = int(stats.mode(crop, axis=None)[0]) 
     water = np.empty(shape(row,cols),dtype=float32) 
     land = water 
     clouds = water 

比我有这样的东西(输出):

     >>> land 
     array([[ 0.,  0.,  0., ...,  0.,  0.,  0.], 
           [ 0.,  0.,  0., ...,  0.,  0.,  0.], 
           [ 0.,  0.,  0., ...,  0.,  0.,  0.], 
           ...,  
           [ 0.,  0.,  0., ...,  0.,  0.,  0.], 
           [ 0.,  0.,  0., ...,  0.,  0.,  0.], 
           [ 0.,  0.,  0., ...,  0.,  0.,  0.]], dtype=float32) 
     >>> land[water==0]=1 
     >>> land 
     array([[ 0.,  0.,  0., ...,  1.,  1.,  1.], 
            [ 0.,  0.,  0., ...,  1.,  1.,  1.], 
            [ 0.,  0.,  0., ...,  1.,  1.,  1.], 
            ...,  
            [ 1.,  1.,  1., ...,  0.,  0.,  0.], 
            [ 1.,  1.,  1., ...,  0.,  0.,  0.], 
            [ 1.,  1.,  1., ...,  0.,  0.,  0.]], dtype=float32) 
     >>> land[crop>mode]=1 
     >>> land 
     array([[ 0.,  0.,  0., ...,  1.,  1.,  1.], 
            [ 0.,  0.,  0., ...,  1.,  1.,  1.], 
            [ 0.,  0.,  0., ...,  1.,  1.,  1.], 
            ...,  
            [ 1.,  1.,  1., ...,  0.,  0.,  0.], 
            [ 1.,  1.,  1., ...,  0.,  0.,  0.], 
            [ 1.,  1.,  1., ...,  0.,  0.,  0.]], dtype=float32) 

但是,在不改变数组形状的情况下,我如何才能在某些条件下使“land”中的值等于 1? 我试着这样做

land[water==0,crop>mode]=1 

我得到了 ValueError。我试过了

land[water==0 and crop>mode]=1 

python 要求我使用 a.all() 或 a.all()....

只有一种情况,结果正是我想要的,我必须这样做才能得到结果。例如(这是我实际代码中的内容):

water[band6 < b6_threshold]=1 
water[band7 < b7_threshold_1]=1 
water[band6 > b6_threshold]=1 
water[band7 < b7_threshold_2]=1 
 
land[band6 > b6_threshold]=1 
land[band7 > b7_threshold_2]=1 
land[clouds == 1]=1 
land[water == 1]=1 
land[b1b4 < 0.5]=1 
land[band3 < 0.1)]=1     
 
clouds[land == 0]=1 
clouds[water == 0]=1 
clouds[band6 < (b6_mode-4)]=1 

我发现这有点令人困惑,我想将所有条件组合在一个语句中...对此有什么建议吗?

非常感谢!

请您参考如下方法:

您可以将 bool 数组乘以“和”之类的东西:

>>> import numpy as np 
>>> a = np.array([1,2,3,4]) 
>>> a[(a > 1) * (a < 3)] = 99 
>>> a 
array([ 1, 99,  3,  4]) 

你可以为“或”之类的东西添加它们:

>>> a[(a > 1) + (a < 3)] = 123 
>>> a 
array([123, 123, 123, 123]) 

或者,如果您更喜欢将 bool 逻辑视为 0 和 1 而不是 True 和 False,您也可以使用运算符 & 和 | 来达到相同的效果.