如何获得每个组随时间的累计和?
How to get the accumulated sum over time for each group?
我正在处理我的个人音乐历史数据,其中 DataFrame 中的每一行都对应于一首已听过的歌曲。我想将数据结构化到 DataFrame 中,以便每个艺术家都是自己的行,而每一列都应对应一个唯一的日期。单元格中的值应对应于艺术家在给定日期的累计收听量。
我熟悉 Pandas 附带的 groupby 方法,但我仍然不完全确定应该如何适当地构建数据。我觉得和时间序列分析的逻辑应该差不多,但是我还不是很熟悉。
这是数据集相关列的片段:
print(df3[['artist', 'date_time', 'year', 'num_month', 'day']].head(20))
artist date_time year num_month day
0 Porcupine Tree 2019-09-10 2019 9 10
1 Porcupine Tree 2019-09-10 2019 9 10
2 Porcupine Tree 2019-09-09 2019 9 10
3 Rammstein 2019-08-10 2019 9 10
4 Tool 2019-08-10 2019 9 10
5 Tool 2019-08-09 2019 9 10
6 Tool 2019-08-09 2019 9 10
7 Tool 2019-08-08 2019 9 10
8 Tool 2019-08-08 2019 9 10
9 Tool 2019-08-08 2019 9 10
10 Tool 2019-08-08 2019 9 10
11 Rotting Christ 2019-07-10 2019 9 10
12 Rotting Christ 2019-07-10 2019 9 10
13 Amoral 2019-06-10 2019 9 10
14 Harry Gregson-Williams 2019-06-10 2019 9 10
15 Harry Gregson-Williams 2019-06-10 2019 9 10
16 Midge Ure 2018-09-10 2019 9 10
17 David Bowie 2018-09-10 2019 9 10
18 David Bowie 2018-09-10 2019 9 10
19 David Bowie 2018-09-10 2019 9 10
请注意 date_time 是 datetime64[ns] 类型。我还将日、月和年存储为整数。
已解决!
grouped_df = df.groupby(['artist', 'date_time']).size().unstack(-1)
grouped_df = grouped_df.fillna(0)
grouped_df_cumsum = grouped_df.cumsum(axis=1)
我正在处理我的个人音乐历史数据,其中 DataFrame 中的每一行都对应于一首已听过的歌曲。我想将数据结构化到 DataFrame 中,以便每个艺术家都是自己的行,而每一列都应对应一个唯一的日期。单元格中的值应对应于艺术家在给定日期的累计收听量。
我熟悉 Pandas 附带的 groupby 方法,但我仍然不完全确定应该如何适当地构建数据。我觉得和时间序列分析的逻辑应该差不多,但是我还不是很熟悉。
这是数据集相关列的片段:
print(df3[['artist', 'date_time', 'year', 'num_month', 'day']].head(20))
artist date_time year num_month day
0 Porcupine Tree 2019-09-10 2019 9 10
1 Porcupine Tree 2019-09-10 2019 9 10
2 Porcupine Tree 2019-09-09 2019 9 10
3 Rammstein 2019-08-10 2019 9 10
4 Tool 2019-08-10 2019 9 10
5 Tool 2019-08-09 2019 9 10
6 Tool 2019-08-09 2019 9 10
7 Tool 2019-08-08 2019 9 10
8 Tool 2019-08-08 2019 9 10
9 Tool 2019-08-08 2019 9 10
10 Tool 2019-08-08 2019 9 10
11 Rotting Christ 2019-07-10 2019 9 10
12 Rotting Christ 2019-07-10 2019 9 10
13 Amoral 2019-06-10 2019 9 10
14 Harry Gregson-Williams 2019-06-10 2019 9 10
15 Harry Gregson-Williams 2019-06-10 2019 9 10
16 Midge Ure 2018-09-10 2019 9 10
17 David Bowie 2018-09-10 2019 9 10
18 David Bowie 2018-09-10 2019 9 10
19 David Bowie 2018-09-10 2019 9 10
请注意 date_time 是 datetime64[ns] 类型。我还将日、月和年存储为整数。
已解决!
grouped_df = df.groupby(['artist', 'date_time']).size().unstack(-1)
grouped_df = grouped_df.fillna(0)
grouped_df_cumsum = grouped_df.cumsum(axis=1)