我有2个数据框,一个是按user_id分组的,并计数显示user_id的次数。另一个数据框是用户使用服务的时间和日期。我想做的是按照最早的日期-最晚的日期从第二个数据帧中计算出时间增量,然后将时间增量添加到第一个数据帧中,甚至还有一列可以从时间增量中提取日期。我认为可能需要进行循环以迭代user_id。我已经尝试了很多次,但无法获得想要的结果。
df1 = pd.DataFrame({'user_id': ['8', '2','5', '1', '10', '4'], 'usage_times':[466,423,401,350,352,333]})
df2 = pd.DataFrame({'user_id': ['1', '5','5', '8', '8', '1'], 'Date':['2010-11-16 16:44:52','2010-06-01 00:34:38','2010-05-31 05:01:24','2010-06-01 00:29:30','2010-09-11 23:55:00','2010-08-10 13:00:00']})
df1:
user_id usage_times
8 466
2 423
5 401
1 350
10 352
4 333
df2:
user_id Date
1 2010-11-16 16:44:52
5 2010-06-01 00:34:38
5 2010-05-31 05:01:24
8 2010-06-01 00:29:30
8 2010-09-11 23:55:00
1 2010-08-10 13:00:00
我尝试过的代码是:
for users in top_users.user_id:
latest_trip = df_final[(df_final['user_id'] == users)]['start_at'].max()
earliest_trip = df_final[(df_final['user_id'] == users)]['start_at'].min()
usage_period = earliest_trip - latest_trip
times = days_hours_minutes(usage_period)
top_users['period'] = top_users.apply(lambda x: list(x) for x in times)
我想要的数据框变成这样:
df1:
user_id usage_times period days
8 466 100 days, 00:23:45 100
2 423 15 days, 00:05:45 15
5 401 104 days, 00:23:45 104
1 350 72 days, 00:15:45 72
10 352 40 days, 00:23:45 40
4 333 28 days, 00:43:45 28
答案 0 :(得分:0)
IIUC,您可以merge
df1和df2,并使用groupby
df = df1.merge(df2, on='user_id')
df['period'] = df.groupby('user_id')['Date'].transform(lambda x: x.max() - x.min() )
df['days'] = df['period'].dt.days
df.drop_duplicates('user_id', inplace=True)
df.drop(columns=['Date'], inplace = True)
df.head()
user_id usage_times period days
0 8 466 102 days 23:25:30 102
2 5 401 0 days 19:33:14 0
4 1 350 98 days 03:44:52 98
答案 1 :(得分:0)
必须完成两个不同的步骤。
首先,您需要获取期间。为此,您可以在df2上使用groupby
,然后在日期差处使用aggregate
:
df2 = df2.groupby(["user_id"]).agg(lambda x: x.max() - x.min())
然后,您可以merge
df1和df2:
df_res = df1.merge(df2, on='user_id')