【问题标题】:Aggregating over two columns (sum and min) [duplicate]聚合两列(总和和最小值)[重复]
【发布时间】:2021-09-22 20:39:20
【问题描述】:

给出以下数据框:

name    item        price   timestamp
______________________________________
Elliot   a            10        12312
Sara     b            20        45654
Elliot   a            30        15000
Tom      a            5         43423

例如,Elliot 消费了 'a' 项两次,现在我想汇总所有此类情况,这样最后我只有一次出现的 'name-item' 对,但这样 'price ' 相加,'timestamp' 对应于找到的最小值:

name    item        price   timestamp
______________________________________
Elliot   a            40        12312
Sara     b            20        45654
Tom      a            5         43423

如何有效地做到这一点?

【问题讨论】:

    标签: python python-3.x dataframe


    【解决方案1】:

    您可以使用groupby.agg,它使用您的列名称为keys 和操作为values 的字典。

    calcs = {'item':'first','price':'sum','timestamp':'min'}
    df.groupby('name').agg(calcs).reset_index()
    

    哪个打印:

         name item  price  timestamp
    0  Elliot    a     40      12312
    1    Sara    b     20      45654
    2     Tom    a      5      43423
    

    您还可以使用Named.Agg 来控制每列具有不同聚合的输出名称,如下所示:

    >>> df.groupby('name').agg( 
        total_price_per_customer=pd.NamedAgg(column='price', aggfunc='sum'), 
        minimum_timestamp_per_customer=pd.NamedAgg(column='timestamp', aggfunc='min'))
    
            total_price_per_customer  minimum_timestamp_per_customer
    name                                                            
    Elliot                        40                           12312
    Sara                          20                           45654
    Tom                            5                           43423
    

    【讨论】:

    • 您可以添加“项目”列吗?
    • 是的,你可以。我更新了答案,您也可以轻松更改第二部分。我认为first 应该在此示例中涵盖您,但请考虑您希望在您的项目列上进行什么聚合。
    • 但是为什么通过 df.shape 的列数现在不同了,尽管 df.head 显示了所有四列?
    • 因为您的name 列已变为index。在 groupby 语句的末尾添加 reset_index() - 还更新了答案以表明这一点。
    猜你喜欢
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 2019-03-28
    • 2012-05-04
    • 2017-08-31
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多