【问题标题】:Agreggate rows on dataframe with python使用python聚合数据框上的行
【发布时间】:2021-11-24 21:47:28
【问题描述】:

我有一个很大的 parquet 文件,其中有很多行包含重复的字段:

client_identifier_1 client_identifier_2 value_a value_b product_identifier
a c 12 22 au
a c 11 12 au
a c 5 12 au
b a 4 21 ag
b a 3 1 ag

我需要对 client_identifier_1、client_identifier_1 和 product_identifier 匹配的 value_a 和 value_b 行求和和转换。

预期输出:

client_identifier_1 client_identifier_2 value_a value_b product_identifier
a c 28 46 au
b a 7 22 ag

【问题讨论】:

    标签: python pandas parquet


    【解决方案1】:

    Groupby 和 agg

    df.groupby(['client_identifier_1','client_identifier_2','product_identifier']).agg('sum').reset_index()
    

    【讨论】:

    • 你能解释一下这是怎么回事吗?
    • 我所做的只是对列表中的列进行分组。然后我找到总和。 pandas 所做的是将列表中指定的列中指定的每个组的所有其他剩余列单独相加。
    • 此数据框包含其他列,但我只需要将 value_a 和 value_b 相加。有办法明确总结这些字段吗?
    • 请根据您的需要从以下s =df.groupby(['client_identifier_1','client_identifier_2','product_identifier'])[['value_a','value_b']].agg('sum').reset_index()df[['value_a','value_b']] =df.groupby(['client_identifier_1','client_identifier_2','product_identifier'])[['value_a','value_b']].transform('sum') df=df.drop_duplicates()尝试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2021-06-16
    相关资源
    最近更新 更多