在pandas df上对过去x个月的数据进行汇总,其中包含startend日期范围和随机参考日期。

问题描述 投票:0回答:1

我有一个熊猫数据框架 df 连片 start_dateend_date 范围和一个单一的 ref_date 为每个用户。

users = {'user_id': ['A','A','A','A', 'B','B','B'],
         'start_date': ['2017-03-07', '2017-03-12', '2017-04-04', '2017-05-22', '2018-12-01', '2018-12-23', '2018-12-29'],
         'end_date': ['2017-03-11', '2017-04-03', '2017-05-21', '2222-12-31', '2018-12-22', '2018-12-28', '2222-12-31'],
         'status': ['S1', 'S2', 'S1', 'S3', 'S1', 'S2', 'S1'],
         'score': [1000, 1000, 1000, 1000, 900, 900, 1500],
         'ref_date': ['2017-05-22', '2017-05-22', '2017-05-22', '2017-05-22', '2019-01-19', '2019-01-19', '2019-01-19']
        }

df = pd.DataFrame(users, columns = ['user_id', 'start_date', 'end_date', 'status', 'score', 'ref_date'])
print(df)

  user_id  start_date    end_date status  score    ref_date
0       A  2017-03-07  2017-03-11     S1   1000  2017-05-22
1       A  2017-03-12  2017-04-03     S2   1000  2017-05-22
2       A  2017-04-04  2017-05-21     S1   1000  2017-05-22
3       A  2017-05-22  2222-12-31     S3   1000  2017-05-22
4       B  2018-12-01  2018-12-22     S1    900  2019-01-19
5       B  2018-12-23  2018-12-28     S2    900  2019-01-19
6       B  2018-12-29  2222-12-31     S1   1500  2019-01-19

我想计算每个用户在过去x个月的关键数字(x=1, 3, 6, 12) 在每个ref_date之前,例子有

  • 在过去x个月中,S1、S2、S3状态的天数,然后才是。ref_date
  • 在过去X个月中,在下列情况下的分数增长次数。ref_date
  • 前X个月的日均得分。ref_date

结果应该是这样的(我希望我的计算正确)。

user_id    ref_date  nday_s1_last3m  nday_s2_last3m  nday_s3_last3m  \
0       A  2017-05-22            53              23               0   
1       B  2019-01-19            43               6               0   

   ninc_score_last3m  avg_score_last3m  
0                  0           1000.00  
1                  1           1157.14  

问题是 ref_date - x个月可能会结束在现有的 start_dateend_date 间歇期或甚至在第一次 start_date在这种情况下,时间 "开始 "于第一个 start_date. 重新取样工作,但如果一个人有数百万用户和许多日期范围,会产生巨大的数据帧;我的内存用完了。有什么建议吗?

需要注意的一个细节。在... a ref_date 是指直至并包括 ref_date-1

python pandas datetime intervals aggregation
1个回答
1
投票

我会先计算出真正的开始日期和结束日期,分别为start_date和ref_date减去3个月,以及end_date和ref_date的孰高孰低。这样做了之后,计算天数、增分和平均值就很简单了。

代码可以是:

# convert date columns to datetimes
for col in ['start_date', 'end_date', 'ref_date']:
    df[col] = pd.to_datetime(df[col])

# compute ref_date minus 3 months
ref = df.ref_date - pd.offsets.MonthOffset(3)

# compute the real start and end dates
tmp = df.loc[(df.end_date >= ref)&(df.start_date < df.ref_date),
             ['start_date', 'end_date']].copy()
tmp.loc[df.start_date < ref, 'start_date'] = ref-pd.Timedelta('1D')
tmp.loc[df.end_date >= df.ref_date, 'end_date'] = df.ref_date-pd.Timedelta('1D')

# add the relevant columns to the temp dataframe
tmp['days'] = (tmp.end_date - tmp.start_date).dt.days + 1
tmp['score'] = df.score
tmp['status'] = df.status

# build a list of result fields per user
data =[]
for i in df.user_id.unique():
    # user_id, ref_date
    d = [i, df.loc[df.user_id == i, 'ref_date'].iat[0]]
    data.append(d)
    # extract data for that user
    x = tmp[df.loc[tmp.index,'user_id'] == i]
    # number of days per status
    d.extend(x.groupby('status')['days'].sum().reindex(df.status.unique())
          .fillna(0).astype('int').tolist())
    # increase and average score
    d.extend((np.sum(np.where(x.score > x.score.shift(), 1, 0)),
          np.average(x.score, weights=x.days)))


# build the resulting dataframe
resul = pd.DataFrame(data, columns=['user_id', 'ref_date', 'nday_s1_last3m',
                                    'nday_s2_last3m', 'nday_s3_last3m',
                                    'ninc_score_last3m', 'avg_score_last3m'])

它给出了预期的结果。

  user_id   ref_date  nday_s1_last3m  nday_s2_last3m  nday_s3_last3m  ninc_score_last3m  avg_score_last3m
0       A 2017-05-22              53              23               0                  0       1000.000000
1       B 2019-01-19              43               6               0                  1       1157.142857
© www.soinside.com 2019 - 2024. All rights reserved.