我想使用 Pandas 拆开看起来像这样的数据:
customer_ids | money spent
---------------------------
00001 | 1000
00001 | 1344
00001 | 1249
00002 | 2345
00003 | 1234
00003 | 1345
换句话说,每个客户的数据量(“访问量”)是可变的,了解每个客户拥有多少数据的唯一方法是查看客户 ID 何时发生变化。我希望数据看起来像这样:
00001 | 1000 | 1344 | 1249
00002 | 2345
00003 | 1234 | 1345
但我不知道该怎么做。如果可以使用 Pandas 之外的其他库,请告诉我。
谢谢!
拆垛(长到宽转换)时,您需要添加一个
visit
列。 visit
中的每个唯一值都将是所需宽数据框中的一个新列。
df['visit'] = df.groupby('customer_ids').cumcount() + 1
现在您可以取消堆叠以获得所需的输出
df_unstacked = df.set_index(['customer_ids', 'visit']).unstack('visit').reset_index()
这会产生
customer_ids money_spent
visit 1 2 3
0 00001 1000.0 1344.0 1249.0
1 00002 2345.0 NaN NaN
2 00003 1234.0 1345.0 NaN