如何在 python 中生成随机的 20 位数字 uid(Unique Id)

How to generate random 20 digit uid(Unique Id) in python

如何在 python 中生成随机的 20 位 UID(唯一 ID)。我想为数据框中的每一行生成 UID。它应该正好是 20 位数字并且应该是唯一的。

我正在使用 uuid4() 但它会生成 32 位 UID,是否可以将其切片 [:21]?不想以后id重复了

如有任何建议,我们将不胜感激!

我肯定不是PythonPandas方面的专家,但下面一起困惑。您可能会发现一些有用的东西:


首先我尝试使用 Numpy 但我达到了上限:

import pandas as pd
import numpy as np
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'], 'ID':[0,0,0,0]}
df = pd.DataFrame(data)  
df.ID = np.random.randint(0, 9223372036854775807, len(df.index), np.int64)
df.ID = df.ID.map('{:020d}'.format)
print(df)

结果:

    Name                    ID
0    Tom  03486834039218164118
1   Jack  04374010880686283851
2  Steve  05353371839474377629
3  Ricky  01988404799025990141

然后我尝试了一个自定义函数并应用了它:

import pandas as pd
import random
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'], 'ID':[0,0,0,0]}
df = pd.DataFrame(data)

def UniqueID():
    UID = '{:020d}'.format(random.randint(0,99999999999999999999))
    while UniqueID in df.ID.unique():
        UID = '{:020d}'.format(random.randint(0,99999999999999999999))
    return UID

df.ID = df.apply(lambda row: UniqueID(), axis = 1)
print(df)

Returns:

    Name                    ID
0    Tom  46160813285603309146
1   Jack  88701982214887715400
2  Steve  50846419997696757412
3  Ricky  00786618836449823720

我认为 python 中的 uuid4() 有效,只需相应地切片即可