Home > Back-end >  How do I generate a uuid for each group in a pandas dataframe
How do I generate a uuid for each group in a pandas dataframe

Time:10-23

I have a dataframe such that

x.groupby(by='basket').ngroup()
Out[15]: 
0    1
1    3
2    1
3    2
4    0

I want to generate uuids for each group so index 0 and 2 shuld have the same uuid. Is there an easy way to do so. Thanks.

Essentially an equivalent of the following if there's a cleaner way:

y = x.drop_duplicates(subset=['basket'])
y['basket_id'] = y['basket'].apply(lambda x: hashlib.shake_256(json.dumps(sorted(x)).encode('utf-8')).hexdigest(10))
y = y[['basket', 'basket_id']]
x = x.merge(y, how='left', on='basket')

CodePudding user response:

Yes, that's possible:

# generate the uuid
ids = {basket: str(uuid.uuid4()) for basket in x['basket'].unique()}


# map uuid
x['uuid'] = x['basket'].map(ids)

Output:

   basket                                  uuid
0       1  e36436ed-7773-44de-9e53-7618cb18d8de
1       3  9cf6902e-4153-4187-8ff8-004a8ec3d2cc
2       1  e36436ed-7773-44de-9e53-7618cb18d8de
3       2  5fc27664-888e-48d2-b348-d18b0089d704
4       0  667f6055-f6b2-45a6-9022-b91ab421ffad

Update: in the general case, you can use numpy indexing:

g = x.groupby(['basket','duration','duration_type'])
# number of unique class
ngroups = g.ngroups()

# generate the uuid
uuids = np.array([str(uuid.uuid4()) for _ in range(ngroups)])

# map the group number to uuid
x['uuid'] = uuids[g.ngroup()]
  • Related