I have a numpy array of integers a and an integer x. For each element in a I want to check whether it starts with x (so the elements of a usually have more digits than x, but that's not guaranteed for every element).
I was thinking of converting the integers to strings and then checking it with

CodePudding user response:
You can use numpy.char.startswith as an alternative.
import numpy as np
a = np.array([4141, 4265, 4285, 4, 41656])
x = 42
res = np.char.startswith(a.astype(str), str(x))
print(res)
# [False True True False False]
CodePudding user response:
Numerically, the number n = xy...z matches the prefix m = uv...w if, after dividing n by a suitable power of 10 to get the same number of digits, n/10^k = m (integer division).
You have the option of determining k by trial and error (linear search or even dichotomic search), but this is not efficient. Another option is to use logarithms to find the number of digits of n and m.
I would not call such a solution elegant.
