如何为数据帧添加唯一的字母数字标识?

2024-09-29 02:23:59 发布

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

我需要一个解决方案,我可以生成唯一的字母数字id列为我的数据帧。我需要ID保持不变,即使我以后运行脚本

    Name
    Sam
    Pray
    Brad

我可以基于这个post生成ID,但我需要5位数字的数值,这些数值将始终保持不变

这是期望的输出:

    Name         ID
    Sam          X25TR
    Peter        WE558
    Pepe         TR589

Tags: 数据name脚本idsam字母数字解决方案
3条回答

这是我的尝试

import secrets

 ids = []
 while len(ids) < df.shape[0]:
     temp = secrets.token_hex(5)[:5]
     if temp not in ids:
         ids.append(temp)
         

df.merge(pd.DataFrame(ids).reset_index(), left_on = df.groupby(['Name']).ngroup(), right_on =  'index')

一种方法是通过任何哈希算法生成名称的哈希,并保留哈希的前五个字符。但您应该记住,如果您有足够的数据,使用短散列(shorthash)可能会导致冲突(多个不同输入的相同输出)

大致如下:

import hashlib

def get_id(name: str) -> str:
    hash = hashlib.md5(name.encode())
    return hash.hexdigest()[:5]

现在,对于给定的输入字符串,get_id返回一个字母数字的5字符字符串,该字符串对于相同的输入总是相同的

此函数用于生成具有给定长度的随机字母数字字符串:

import math
import secrets


def random_alphanum(length: int) -> str:
        text = secrets.token_hex(nbytes=math.ceil(length / 2))
        isEven = length % 2 == 0
        return text if isEven else text[1:]

df['ID'] == random_alphanum(5)

应用于整行:

df2['ID'] = df2.apply(lambda x: random_alphanum(5), axis=1, result_type="expand")

相关问题 更多 >