为 Python 中的数据框计算每个月的计数器

Calculate counter for each month for dataframe in Python

我有以下数据框:

cluster_ID counter_1 counter_2 date
0 1 0 2021-01-02 10:00:00
0 1 2 2021-01-03 12:00:24
0 0 1 2021-01-04 09:10:30
0 2 1 2021-02-15 08:10:21
0 1 1 2021-03-04 14:23:43
1 2 0 2020-12-30 13:16:45
1 2 3 2021-01-07 12:13:23
1 1 2 2021-03-06 07:28:23
2 1 1 2021-01-10 14:24:23
2 1 0 2021-01-15 17:23:35
2 0 1 2021-01-20 13:28:13
2 1 2 2021-02-11 11:23:15
3 3 2 2021-04-13 21:14:19

我想定义一个生成新数据框的函数,该数据框包括 table 中每个现有月份的 2 个新列,用于从 counter_1 和 [=26= 生成的日期列] 信息。对于按 cluster_ID 的每个组,每个月分别对每个计数器的列 counter_1 和 counter_2 求和。如果该月不存在任何值,则结果 table 应填充为 0。date 的值是一个 Python 时间戳。

生成的数据框示例:

cluster_ID counter_1_2020-12 counter_2_2020-12 counter_1_2021-01 counter_2_2021-01 counter_1_2021-02 counter_2_2021-02 counter_1_2021-03 counter_2_2021-03 counter_1_2021-04 counter_2_2021-04
0 0 0 2 3 2 1 1 1 0 0
1 2 0 2 3 0 0 1 2 0 0
2 0 0 2 2 1 2 0 0 0 0
3 0 0 0 0 0 0 0 0 3 2

希望你能帮我解决我的问题。感谢您的帮助。

您可以将日期时间转换为 YYYY-MM 字符串,通过 DataFrame.pivot_tableaggfunc='sum' 旋转,按日期对列进行排序,并通过 map 展平 MultiIndex

df['date'] = pd.to_datetime(df['date'])

df1 = (df.assign(date = df['date'].dt.strftime('%Y-%m'))
         .pivot_table(index='cluster_ID', columns='date', fill_value=0, aggfunc='sum')
         .sort_index(level=[1,0], axis=1))
df1.columns = df1.columns.map(lambda x: f'{x[0]}_{x[1]}')
df1 = df1.reset_index()
print (df1)
   cluster_ID  counter_1_2020-12  counter_2_2020-12  counter_1_2021-01  \
0           0                  0                  0                  2   
1           1                  2                  0                  2   
2           2                  0                  0                  2   
3           3                  0                  0                  0   

   counter_2_2021-01  counter_1_2021-02  counter_2_2021-02  counter_1_2021-03  \
0                  3                  2                  1                  1   
1                  3                  0                  0                  1   
2                  2                  1                  2                  0   
3                  0                  0                  0                  0   

   counter_2_2021-03  counter_1_2021-04  counter_2_2021-04  
0                  1                  0                  0  
1                  2                  0                  0  
2                  0                  0                  0  
3                  0                  3                  2