Pandas随机ID类别

2024-09-29 01:30:23 发布

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

我希望能够将PRNG分配给一个数据帧。在

我可以使用cat.codesngroup()分配一个唯一的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循环。在


Tags: 数据nameimportidjohncodescatpd
2条回答

gourpby+transform

df1['random id'] = df1.groupby('idz').idz.transform(lambda x : id_generator(3))
df1
Out[657]: 
    Name  id  idz random id
0   John   2    2       35P
1  Susie   3    3       6UU
2   Jack   0    0       XGF
3   Jill   1    1       5LC
4   John   2    2       35P

在前面加上“这可能不是最有效的选择”。在

我将通过首先找到每个唯一用户来为每个唯一用户生成随机ID。在

# Finding unique users and storing in a new DataFrame
df_unique_users = pd.DataFrame({'Name':[x for x in set(df['Name'])]})

# Generating unique user ID's for length of data frame 
# By using a set you are guaranteed unique values. You just need to make sure
# you have enough permutations of the unique random_id so that your rand_set 
# will eventually be longer than your unique Names DataFrame. 

rand_set = set()
while(len(rand_set)<len(df_unique_users)):
    rand_set = rand_set.union([id_generator(3)])

df_unique_users['Rand_ID'] = rand_set

### Mapping the random ID's over to the original DataFrame
df = df.merge(df_unique_users, how='left', left_on='Name', right_on='Name')

类似地,您可以使用原始ID列而不是Name列来获取唯一值。在

相关问题 更多 >