python - 分组数据框以获取带有时间戳排序的最新消息
问题描述
我有上面的数据框:
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
我想groupby
按customer_id和message获取数据帧,并按时间戳排序,这样我就可以得到每个月的最新消息,比如 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)
但我没有得到想要的结果。
解决方案
此行将按 和 分组customer_id
,Month
连接message
字段:
df = df.groupby(['customer_id', 'Month'])['message'].apply(lambda x: ', '.join(x))
如果要在分组依据之后保持排序,则需要在最终数据框中使用一列进行排序,例如年份列。
推荐阅读
- python-3.x - 从多个页面抓取数据,然后将其附加到 csv 文件
- python - 用于 ssh 到多个交换机的 Python 脚本发送命令输出
- android - 什么是 Android SDK 附加组件?
- django - 浏览器是否使用 POST 请求删除资源?
- sapui5 - 使用一个功能设置组件的多个属性
- vb.net - 我的 Windows 服务启动时如何打开网络浏览器?
- java - How to keep java.lang.reflect when use proGuard
- javascript - 如果使用 angular2 未完成该过程,如何重定向到登录页面
- c++ - 对于普通类型和类,C++ 函数特化的行为不同
- sql - Are these queries the same? If not how to make more simple query