-1

How do I achieve this with pandas

inputindex  |country_id|country_name|  value | desc
1            2                 JAV       3         a
2            3                 GBR       7         b
3            4                 GBR       5         e
4            7                  BDI      6         r

output

index | country_id|country_name| value| desc
1              2       JAV       3       a
2              3       GBR       12     b,e
4              7       BDI       6       r
2
  • 1
    simple groupby+agg with sum and list or str.join Commented Jan 28, 2022 at 8:12
  • 1
    @mozway - and first Commented Jan 28, 2022 at 8:13

1 Answer 1

1

Use GroupBy.agg with 3 different functions - GroupBy.first, sum and join:

df = (df.groupby('country_name', as_index=False, sort=False)
        .agg(country_id = ('country_id', 'first'),
             value = ('value','sum'),
             desc = ('desc', ','.join)))
print (df)
  country_name  country_id  value desc
0          JAV           2      3    a
1          GBR           3     12  b,e
2          BDI           7      6    r
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.