python - 以数字方式检查数组中的数字是否以给定数字开头

标签 python numpy

我有一个 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/

相关文章:

python - 如何计算语料库文档中的单词

python - 如何解决 "HttpError: Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object., 401"错误?

python - grpcio-tools protoc.main 给出 'missing output directives' 错误

Python代码重构问题。将函数应用于多个元素

python - 神经网络 : avoid bias in any direction for output

python - 为什么 int numpy 数组的逆幂为 0,尽管 "from __future__ import division"?

python - 替换日期大于其他日期的 DateTime 列值

python - Pandas 数据框中点坐标的欧几里得距离

python - 我如何在 Numpy 的矩阵中计算 xi^j

python - 在 numpy.interp 与 scipy.interpolate.interp1d 之间进行选择(种类为 ='linear' )