Issue
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 pandas
import pandas as pd
import numpy as np
a = np.array([4141, 4265, 4285, 4, 41656])
x = 42
pd.Series(a).astype(str).str.startswith(str(x)).values # .values returns numpy array instead of pd.Series
[False True True False False]
This works and is also quite performant, but for educational purpose I was wondering if there is also an elegant solution doing it numerically in numpy only.
Solution
You can get the number of digits using the log10, then divide as integer:
# number of digits of x
n = int(np.ceil(np.log10(x+1)))
# number of digits in array
n2 = np.ceil(np.log10(a+1)).astype(int)
# get first n digits of numbers in array
out = a//10**np.clip((n2-n), 0, np.inf) == x
output: array([False, True, True, False, False])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.