Efficiently replace elements in array based on dictionary - NumPy / Python

前端 未结 4 1145
梦谈多话
梦谈多话 2020-12-10 05:22

First, of all, my apologies if this has been answered elsewhere. All I could find were questions about replacing elements of a given value, not elements of multiple values.<

4条回答
  •  天涯浪人
    2020-12-10 06:24

    Given that you're using numpy arrays, I'd suggest you do a mapping using numpy too. Here's a vectorized approach using np.select:

    mapping = {1:2, 5:3, 8:6}
    keys, choices = list(zip(*mapping.items()))
    # [(1, 5, 8), (2, 3, 6)]
    # we can use broadcasting to obtain a 3x100x100
    # array to use as condlist
    conds = np.array(keys)[:,None,None]  == input_array
    # use conds as arrays of conditions and the values 
    # as choices
    np.select(conds, choices)
    
    array([[2, 2, 2, ..., 0, 0, 0],
           [2, 2, 2, ..., 0, 0, 0],
           [2, 2, 2, ..., 0, 0, 0],
           ...,
           [0, 0, 0, ..., 0, 0, 0],
           [0, 0, 0, ..., 0, 0, 0],
           [0, 0, 0, ..., 0, 0, 0]])
    

提交回复
热议问题