Home > Blockchain >  Apply NumPy repeat only on elements that are contained in a secondary list
Apply NumPy repeat only on elements that are contained in a secondary list

Time:11-23

I'm trying to repeat certain elements within a list n-times and so far I've come to this solution:

                _base = ["a", "z", "c", "c", "e"]
                for bump_element in ["a", "b", "c"]:
                    _base = np.repeat(
                        np.array(_base),
                        np.where(np.array(_base) == bump_element, 2, 1)
                    )

So far this works, _base will be ['a' 'a' 'z' 'c' 'c' 'c' 'c' 'e']. However, I'm trying to make it faster by removing the for loop so that within a single repeat I can catch all elements. Something like:

                    _base = np.repeat(
                        np.array(_base),
                        np.where(np.array(_base) in ["a", "b", "c"], 2, 1)
                    )

But that won't work since it will throw The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

Is there an easy way to make that where clause to check every item in the list against the one which contains the elements to be repeated?

CodePudding user response:

To avoid the for loop over the possible values in 'bump_element', you can use numpy isin.

_base = np.array(["a", "z", "c", "c", "e"])
bump = np.array(["a", "b", "c"])
np.repeat(_base, np.where(np.isin(_base, bump), 2, 1))
  • Related