【问题标题】:Grouping dataframe to get latest message with timestamp sort分组数据框以获取带有时间戳排序的最新消息
【发布时间】: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_idmessagegroupby 数据框,并按 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


【解决方案1】:

这样的事情怎么样:

df = df.sort_values('timestamp', ascending = False)
df = df.drop_duplicates(subset = ['customer_id', 'month'], keep = 'first')
df = df.sort_values('customer_id').reset_index()

这给出了:

   customer_id message      timestamp  month
2         7596    msg3  1524905898745  April
0         9683    msg1  1525266558487    May
3        10661    msg4  1525262750075    May
4        10661    msg5  1524894609266  April

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      相关资源
      最近更新 更多