如何在python中消除由双三个连续数字组成的数据?

2024-04-25 13:56:41 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据

id
123246512378
632746378456
378256364036
159204652855
327445634589

我想把由两个三个连续的数字组成的数据,比如123246512378,3274456 | 34589减少

id
632746378456
378256364036
159204652855

Tags: 数据id数字
2条回答

不确定这是否比@piRSquared快,因为我没有足够好的pandas来生成我自己的测试数据,但看起来应该是:

def mask_cons(df):
    a = np.array(list(map(list, df.id.astype(str))), dtype = float) 
    # same as piRSquared, but float
    g_a = np.gradient(a, axis = 1)[:,1:-1] 
    # 3 consecutive values will give grad(a) = +/-1
    mask = (np.abs(g_a) == 1).sum(1) > 1
    # this assumes 4 consecutive values count as 2 instances of 3 consecutive values
    # otherwise more complicated methods are needed (probably @jit)
    return df[mask]

首先,将df.id转换为一个单位数整数数组。你知道吗

a = np.array(list(map(list, map(str, df.id))), dtype=int)

然后检查一个数字是否比下一个数字少一个。。。两次

first = a[:, :-2] == a[:, 1:-1] - 1
second = a[:, 1:-1] == a[:, 2:] - 1

创建一个面具,当我们有这种事情发生不止一次

mask = np.count_nonzero(first & second, axis=1) < 2
df[mask]

             id
1  632746378456
2  378256364036
3  159204652855

相关问题 更多 >