【发布时间】:2018-12-25 07:31:18
【问题描述】:
我有上面的数据框:
customer_id message timestamp Month
0 9683 txn of INR 234.00 1525266558487 May
1 9683 txn of INR 975.00 1525192344719 May
2 7596 txn of INR 1,363.80 1524905898745 April
3 10661 txn of INR 200.00 1525262750075 May
4 10661 txn of INR 300.00 1524894609266 April
我想通过 customer_id 和 message 来groupby 数据框,并按 timestamp 排序,这样我就可以得到每个月的最新消息如id:9683 和不同月份的不同消息,以便我们获得最新消息。
输出如下所示
customer_id message month
9683 txn of INR 234.00, txn of INR 975.00 May
7596 txn of INR 1,363.80 April
10661 txn of INR 200.00 May
10661 txn of INR 300.00 April
我的代码如下:
f = lambda x: x.sort('timestamp', ascending=False)
agg_funcs = {'message':lambda x:','.join(map(str, x))}
df1 = df.groupby(['customer_id','Month']).agg(agg_funcs).apply(f)
但我没有得到想要的结果。
【问题讨论】:
-
你能告诉我们你得到了什么结果吗?
-
您不是在检索最新的 message,而是将所有 message 加入客户/月份分组中,并且您没有按 message 分组i> 本身。
-
我得到了这个结果:message None dtype: object
-
@Parfait 我将它们分组为 f = lambda x: x.sort('timestamp', ascending=False) df.groupby(['customer_id','sender_name','Month'])。 apply(f) 但以堆叠形式获得结果,我希望逐行排列,以便我获取对应 customer_id 月份的第一条记录
标签: python pandas pandas-groupby