unpairestgood unpairestgood - 4 months ago 20
Python Question

Add UUID's to pandas DF

Say I have a pandas DataFrame like so:

df = pd.DataFrame({'Name': ['John Doe', 'Jane Smith', 'John Doe', 'Jane Smith','Jack Dawson','John Doe']})
df:
Name
0 John Doe
1 Jane Smith
2 John Doe
3 Jane Smith
4 Jack Dawson
5 John Doe


And I want to add a column with uuids that are the same if the name is the same. For example, the DataFrame above should become:

df:
Name UUID
0 John Doe 6d07cb5f-7faa-4893-9bad-d85d3c192f52
1 Jane Smith a709bd1a-5f98-4d29-81a8-09de6e675b56
2 John Doe 6d07cb5f-7faa-4893-9bad-d85d3c192f52
3 Jane Smith a709bd1a-5f98-4d29-81a8-09de6e675b56
4 Jack Dawson 6a495c95-dd68-4a7c-8109-43c2e32d5d42
5 John Doe 6d07cb5f-7faa-4893-9bad-d85d3c192f52


The uuid's should be generated from the uuid.uuid4() function.

My current idea is to use a groupby("Name").cumcount() to identify which rows have the same name and which are different. Then I'd create a dictionary with a key of the cumcount and a value of the uuid and use that to add the uuids to the DF.

While that would work, I'm wondering if there's a more efficient way to do this?

Answer

How about this

names = df['Name'].unique()
for name in names:
    df.loc[df['Name'] == name, 'UUID'] = uuid.uuid4()

could shorten it to

for name in df['Name'].unique():
    df.loc[df['Name'] == name, 'UUID'] = uuid.uuid4()