如果用户流失游戏或他/她仍在玩游戏,我想计算二进制字段churn_flag。
我已计算数据最大日期
max_time = data['time'].max()
结果:
Timestamp('2017-07-12 01:18:50') (future date)
我已经计算了每个用户的最大日期:
data_max_time = pd.DataFrame(data.groupby(['id'])['time'].max()).reset_index()
data_max_time.columns = ['id','user_max_time']
结果:
2017-07-11 10:33:11 dtype:datetime64[ns]
我应该检查这两个日期之间的差异是否长于或短于2天。我试图解决它:
(np.datetime64(final_data['max_time'],'D')-np.datetime64(final_data['user_max_time'],'D'))< (np.timedelta64(2,'D'))
结果:
ValueError: Could not convert object to NumPy datetime
我如何计算每个用户的真/假(1/0)字段?
答案 0 :(得分:2)
我认为没有必要转换,只使用熊猫:
rng = pd.date_range('2017-04-03 15:00:07', periods=10, freq='28.5H')
data = pd.DataFrame({'time': rng, 'id': [1,1,2,2,2,5,5,5,1,2]})
print (data)
id time
0 1 2017-04-03 15:00:07
1 1 2017-04-04 19:30:07
2 2 2017-04-06 00:00:07
3 2 2017-04-07 04:30:07
4 2 2017-04-08 09:00:07
5 5 2017-04-09 13:30:07
6 5 2017-04-10 18:00:07
7 5 2017-04-11 22:30:07
8 1 2017-04-13 03:00:07
9 2 2017-04-14 07:30:07
max_time = data['time'].max()
data_max_time = data.groupby('id')['time'].max()
#data_max_time.columns = ['id','user_max_time']
print (data_max_time)
id
1 2017-04-13 03:00:07
2 2017-04-14 07:30:07
5 2017-04-11 22:30:07
Name: time, dtype: datetime64[ns]
print (max_time - data_max_time)
id
1 1 days 04:30:00
2 0 days 00:00:00
5 2 days 09:00:00
Name: time, dtype: timedelta64[ns]
df = (max_time - data_max_time < pd.Timedelta(2, unit='D')).reset_index(name='a')
print (df)
id a
0 1 True
1 2 True
2 5 False