我有一个 numpy 整数数组 a
和一个整数 x
。对于 a
中的每个元素,我想检查它是否以 x
开头(因此 a
的元素通常比 x
,但不能保证每个元素都如此)。
我正在考虑将整数转换为字符串,然后使用 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]
这很有效,而且性能也很好,但出于教育目的,我想知道是否还有一个优雅的解决方案,仅在 numpy 中以数字方式进行。
最佳答案
你可以使用log10得到位数,然后除以整数:
# 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
输出:array([False, True, True, False, False])
关于python - 以数字方式检查数组中的数字是否以给定数字开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73539783/