Find and replace multiple values in python

前端 未结 6 1329
攒了一身酷
攒了一身酷 2021-02-15 03:59

I want to find and replace multiple values in an 1D array / list with new ones.

In example for a list

a=[2, 3, 2, 5, 4, 4, 1, 2]

I woul

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-15 04:38

    The numpy_indexed package (disclaimer: I am its author) provides an elegant and efficient vectorized solution to this type of problem:

    import numpy_indexed as npi
    remapped_a = npi.remap(a, val_old, val_new)
    

    The method implemented is based on searchsorted like that of swenzel and should have similar good performance, but more general. For instance, the items of the array do not need to be ints, but can be any type, even nd-subarrays themselves.

    If all values in 'a' are expected to be present in 'val_old', you can set the optional 'missing' kwarg to 'raise' (default is 'ignore'). Performance will be slightly better, and you will get a KeyError if that assumption is not satisfied.

提交回复
热议问题