Check if values in a set are in a numpy array in python

后端 未结 3 1794
借酒劲吻你
借酒劲吻你 2021-01-12 11:32

I want to check if a NumPyArray has values in it that are in a set, and if so set that area in an array = 1. If not set a keepRaster = 2.

numpyArray = #some          


        
3条回答
  •  时光说笑
    2021-01-12 12:34

    In recent numpy you could use a combination of np.isin and np.where to achieve this result. The first method outputs a boolean numpy array that evaluates to True where its vlaues are equal to an array-like specified test element (see doc), while with the second you could create a new array that set some a value where the specified confition evaluates to True and another value where False.

    Example

    I'll make an example with a random array but using the specific values you provided.

    import numpy as np
    
    repeatSet = ([2, 5, 6, 8])
    
    arr = np.array([[1,5,1],
                    [0,1,0],
                    [0,0,0],
                    [2,2,2]])
    
    out = np.where(np.isin(arr, repeatSet), 1, 77)
    
    > out
    array([[77,  1, 77],
           [77, 77, 77],
           [77, 77, 77],
           [ 1,  1,  1]])
    

提交回复
热议问题