Как я могу сгруппировать по приведенной ниже таблице из идентификатора клиента и кода продукта и получить их в одну строку, как показано ниже, с помощью Python?
Пользовательский ИД | Код продукта | Дней с момента последней транзакции |
---|---|---|
А | 1 | 10 |
А | 1 | 23 |
А | 1 | 7 |
А | 2 | 8 |
А | 2 | 9 |
А | 3 | 6 |
Б | 1 | 18 |
Б | 2 | 4 |
Б | 3 | 4 |
Б | 3 | 12 |
С | 2 | 27 |
С | 2 | 15 |
Необходимо получить таблицу ниже, сгруппировав их по идентификатору клиента и коду продукта.
Пользовательский ИД | Код продукта | Д1 | Д2 | Д3 |
---|---|---|---|---|
А | 1 | 10 | 23 | 7 |
А | 2 | 8 | 9 | Н/Д |
А | 3 | 6 | Н/Д | Н/Д |
Б | 1 | 18 | Н/Д | Н/Д |
Б | 2 | 4 | Н/Д | Н/Д |
Б | 3 | 4 | 12 | Н/Д |
С | 2 | 27 | 15 | Н/Д |
df[''] = df.groupby(['Customer ID', 'Product Code']).cumcount()
df = df.pivot(index=['Customer ID', 'Product Code'], columns='')
print(df)
Выход:
Days since the last transaction
0 1 2
Customer ID Product Code
A 1 10.0 23.0 7.0
2 8.0 9.0 NaN
3 6.0 NaN NaN
B 1 18.0 NaN NaN
2 4.0 NaN NaN
3 4.0 12.0 NaN
C 2 27.0 15.0 NaN
Ниже код Python также работал у меня.
#keep only the needed data
grouped = df.groupby(['Customer_ID','Product Code'], as_index=False).agg({"Days since the last transaction": lambda x: x.tolist()[:3]+[x.iat[-1]]}).explode("Days since the last transaction")
#get the count for the age columns
grouped["idx"] = grouped.groupby(['Customer_ID','Product Code']).cumcount().add(1)
#pivot to get the required structure
output = grouped.pivot(["Customer_ID","Product Code"],"idx","Days since the last transaction").add_prefix("Days since the last transaction").reset_index().rename_axis(None, axis=1)
output.head()