首页 > 解决方案 > 分组数据框以获取带有时间戳排序的最新消息

问题描述

我有上面的数据框:

    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

我想groupbycustomer_idmessage获取数据帧,并按时间戳排序,这样我就可以得到每个月的最新消息,比如 inid: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)

但我没有得到想要的结果。

标签: pythonpandaspandas-groupby

解决方案


此行将按 和 分组customer_idMonth连接message字段:

df = df.groupby(['customer_id', 'Month'])['message'].apply(lambda x: ', '.join(x))

如果要在分组依据之后保持排序,则需要在最终数据框中使用一列进行排序,例如年份列。


推荐阅读