I have a list like this
key_fields = ['first_name', 'last_name']
And another code like this
df1 = df1.set_index(['first_name', 'last_name', df1.groupby(['first_name', 'last_name']).cumcount()])
I want to replace the hardcoded values in second line with first line
df1 = df1.set_index(key_fields + df1.groupby(key_fields).cumcount())
But it’s giving me error
numpy.core._exceptions._UFuncNoLoopError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U10'), dtype('int64')) -> None
>Solution :
In Python, you can’t directly concatenate a list and a Series in this way. Instead, you need to combine them correctly within the set_index function.
You can try:
df1 = df1.set_index(key_fields + [df1.groupby(key_fields).cumcount()])
As for the explanation, key_fields is a list of strings: ['first_name', 'last_name']. However, df1.groupby(key_fields).cumcount() is a Pandas Series, and you need to wrap it in a list [] to be able to concatenate it with key_fields.