问题描述
Q1。给定数据框架1 , 我正在尝试按新的独特事件进行分组,并在另一列中为我提供每月的现有ID计数
ID Date
1 Jan-2020
2 Feb-2020
3 Feb-2020
1 Mar-2020
2 Mar-2020
3 Mar-2020
4 Apr-2020
5 Apr-2020
Date ID_Count Existing_count
Jan-2020 1 0
Feb-2020 2 1
Mar-2020 0 3
Apr-2020 2 3
注意:2020年3月ID_Count为零,因为前几个月存在ID 1、2和3。
注意:2020年1月的现有计数为0,因为1月之前的ID为零。2月2020年的现有计数为1,因为2月之前只有1。2020年3月具有3个现有计数,这是因为Jan + 2月等等
解决方法
我认为您可以这样做:
df['month'] = pd.to_datetime(df['Date'],format='%b-%Y')
# Find new IDs
df['new'] = df.groupby('ID').cumcount()==0
# Count new IDs by month
df_ct = df.groupby('month')['new'].sum().to_frame(name='ID_Count')
# Count all previous new IDs
df_ct['Existing_cnt'] = df_ct['ID_Count'].shift().cumsum().fillna(0).astype(int)
df_ct.index = df_ct.index.strftime('%b-%Y')
df_ct
输出:
ID_Count Existing_cnt
month
Jan-2020 1 0
Feb-2020 2 1
Mar-2020 0 3
Apr-2020 2 3