我希望能够将PRNG分配给一个数据帧。在
我可以使用cat.codes
或ngroup()
分配一个唯一的ID
import pandas as pd
import random
import string
df1 = pd.DataFrame({'Name': ['John', 'Susie', 'Jack', 'Jill', 'John']})
df1['id'] = df1.groupby('Name').ngroup()
df1['idz'] = df1['Name'].astype('category').cat.codes
Name id idz
0 John 2 2
1 Susie 3 3
2 Jack 0 0
3 Jill 1 1
4 John 2 2
我使用了一个来自this post的函数来逐行创建这个惟一的ID。在
^{pr2}$但是我如何将这两者结合在一起,以便这个小用例中的John将获得相同的ID?如果可能的话,由于数据的大小,我希望避免长的if ID not used, then ID, and if name has ID, use existing ID
循环。在
gourpby
+transform
在前面加上“这可能不是最有效的选择”。在
我将通过首先找到每个唯一用户来为每个唯一用户生成随机ID。在
类似地,您可以使用原始ID列而不是Name列来获取唯一值。在
相关问题 更多 >
编程相关推荐