Add uuid to a new column in a pandas DataFrame
This is one way:
df['uuid'] = [uuid.uuid4() for _ in range(len(df.index))]
I can't speak to computational efficiency here, but I prefer the syntax here, as it's consistent with the other apply-lambda modifications I usually use to generate new rows:
df['uuid'] = df.apply(lambda _: uuid.uuid4(), axis=1)
You can also pick a random column to remove the axis requirement (why axis=0
is the default, I'll never understand):
df['uuid'] = df['col'].apply(lambda _: uuid.uuid4())
The downside to these is technically you're passing in a variable (_
) that you don't actually use. It would be mildly nice to have the capability to do something like lambda: uuid.uuid4()
, but apply
doesn't support lambas with no args, which is reasonable given its use case would be rather limited.
from uuid import uuid4df['uuid'] = df.index.to_series().map(lambda x: uuid4())