【问题标题】:Groupby without an aggregation function and sort that dataGroupby 没有聚合函数并对数据进行排序
【发布时间】:2019-10-28 01:37:41
【问题描述】:

我有客户 ID 和购买日期。我需要分别为每个客户 ID 排序购买日期。 我需要一个 groupby 操作,但没有聚合,并对每个客户的购买日期进行排序。

试过了

new_data = data.groupby('custID').sort_values('purchase_date')

AttributeError:无法访问的可调用属性“sort_values” 'DataFrameGroupBy' 对象,尝试使用 'apply' 方法

预期结果如下:

custID  purchase_date
100     23/01/2019
100     29/01/2019
100     03/04/2019
120     02/05/2018
120     09/03/2019
120     11/05/2019

【问题讨论】:

    标签: python-3.x


    【解决方案1】:
    # import the pandas library
    import pandas as pd
    
    data = {
        'purchase_date': ['23/01/2019', '19/01/2019', '12/01/2019', '23/01/2019', '11/01/2019', '23/01/2019', '06/05/2019', '05/05/2019', '05/01/2019', '02/07/2019',],
        'custID': [100, 160, 100, 110, 160, 110, 110, 110, 110, 160]
    }
    
    df = pd.DataFrame(data)
    
    
    sortedData = df.groupby('custID').apply(
    lambda x: x.sort_values(by = 'purchase_date', ascending = True))
    
    sortedData=sortedData.reset_index(drop=True, inplace=False)
    

    输出:

    print(sortedData)

    Index  custID  purchase_date
    
     0     100    12/01/2019
     1     100    23/01/2019
     2     110    05/01/2019
     3     110    05/05/2019
     4     110    06/05/2019
     5     110    23/01/2019
     6     110    23/01/2019
     7     160    02/07/2019
     8     160    11/01/2019
     9     160    19/01/2019
    

    print(sortedData.to_string(index=False))

    custID purchase_date
     100    12/01/2019
     100    23/01/2019
     110    05/01/2019
     110    05/05/2019
     110    06/05/2019
     110    23/01/2019
     110    23/01/2019
     160    02/07/2019
     160    11/01/2019
     160    19/01/2019
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-22
      • 2021-11-04
      • 1970-01-01
      • 2015-09-16
      • 2021-03-30
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多