在特定列上连接多行和总和

问题描述 投票:0回答:1

我想将多行连接成单行。我设法将行连接起来,但是,当我尝试基于特定列应用总和时,它给了我一个错误TypeError: can only concatenate str (not "float") to str

Item    Sum     Brand    Type    User   ID
ABC      5       High     Zinc   John   20A
CDD      3       Low      Iron   Bail   10B
ABC     10       High     Zinc   John   20A
CDD    200       Low      Iron   Bail   10B

下面是我的代码:

df = df.groupby(['ID','User','Type','Brand']).agg({'Item':''.join, 'Sum':'sum'}).reset_index()

所需的输出:

Item   Sum    Brand    Type   User   ID
ABC    15     High    Zinc   John   20A
CDD    203    Low     Iron    Bail  10B

提前谢谢!

pandas
1个回答
0
投票
df = df.pivot_table(index=['Brand', 'Type', 'User', 'ID'],values=['Sum'], columns=['Item'], aggfunc=sum).stack().reset_index()


            Brand   Type    User    ID  Item    Sum
    0       High    Zinc    John    20A ABC     15.0
    1       Low     Iron    Bail    10B CDD     203.0
© www.soinside.com 2019 - 2024. All rights reserved.