简体   繁体   中英

Combine rows in Dataframe column based on condition

I have the excerpt of the following df :

                     Causa de muerte   Sexo              Edad  Periodo   Total
39  001-102  I-XXII.Todas las causas  Total    Menos de 1 año     2018    1027
40  001-102  I-XXII.Todas las causas  Total    Menos de 1 año     2017    1092
41  001-102  I-XXII.Todas las causas  Total    Menos de 1 año     2016    1120
78  001-102  I-XXII.Todas las causas  Total     De 1 a 4 años     2018     240
79  001-102  I-XXII.Todas las causas  Total     De 1 a 4 años     2017     226
80  001-102  I-XXII.Todas las causas  Total     De 1 a 4 años     2016     248

Is there a way to combine/merge the rows where 'Edad' == 'Menos de 1 año' and 'Edad' == 'De 1 a 4 años' and rename the merged rows to 'De 0 a 4 años'. My goal is that the corresponding numbers in 'Total' add up:

                     Causa de muerte   Sexo              Edad  Periodo   Total
39  001-102  I-XXII.Todas las causas  Total     De 0 a 4 años     2018    1267
40  001-102  I-XXII.Todas las causas  Total     De 0 a 4 años     2017    1318
41  001-102  I-XXII.Todas las causas  Total     De 0 a 4 años     2016    1368

I'm assuming you'll do it with groupby, but I haven't figured out how.

Use Series.replace with aggregate sum :

df['Edad'] = df['Edad'].replace({'Menos de 1 año':'De 1 a 4 años'})

df = df.groupby(['Causa de muerte','Sexo','Edad','Periodo'], as_index=False)['Total'].sum()
print (df)
                    Causa de muerte   Sexo           Edad  Periodo  Total
0  001-102  I-XXII.Todas las causas  Total  De 1 a 4 años     2016   1368
1  001-102  I-XXII.Todas las causas  Total  De 1 a 4 años     2017   1318
2  001-102  I-XXII.Todas las causas  Total  De 1 a 4 años     2018   1267

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM