我有一个如下所示的数据框:
ID Date Prize IfWon
1 01-01-20 5 1
2 01-01-20 8 1
1 01-03-20 3 0
1 01-04-20 10 1
1 01-07-20 5 0
2 01-10-20 5 1
3 01-10-20 10 1
我想添加一个新列,对于给定的ID,该列将包括他们在该日期之前7天内赢得的任何奖品的总和,而不包括该日期。目标是创建一个如下所示的数据帧:
ID Date Prize IfWon PrevWon
1 01-01-20 5 1 0
2 01-01-20 8 1 0
1 01-03-20 3 0 5
1 01-04-20 10 1 5
1 01-07-20 5 0 15
2 01-10-20 5 1 0
3 01-10-20 10 1 0
下面是我必须执行的代码,它是有效的,但我有两个问题:
def get_rolling_prize_sum(grp, freq):
return grp.rolling(freq, on = 'Date', closed = 'right')['CurrentWon'].sum()
processed_data_df['CurrentWon'] = processed_data_df['Prize'] * processed_data_df['IfWon'] # gets deleted later
processed_data_df['PrevWon'] = processed_data_df.groupby('ID', group_keys=False).apply(get_rolling_prize_sum, '7D').astype(float) - processed_data_df['CurrentWon']
# Not using closed right here, just subtracting
processed_data_df['PrevWon'] = processed_data_df.groupby('ID', group_keys=False).rolling('7D', on = 'Date')['CurrentWon'].sum() - processed_data_df['CurrentWon']
ValueError: cannot join with no overlapping index names
有什么想法吗
改进了以前的答案,并成功解决了groupby的排序问题
产出:
相关问题 更多 >
编程相关推荐