0

Is there an easy way of creating a summed aggregate table in Python from columns in an existing table? I have only used SQL previously and this would be done with a code such as:

select AreaCode, Measure, sum(Value) as 'VALUE'

from Table

group by AreaCode, Measure

In my current table (sticking with the example above) I have hundreds of rows containing AreaCode, Measure and Value that i want to aggregate in a new table in Python

nnn1234
  • 67
  • 6

1 Answers1

0

Given a pandas dataframe named table looking like this:

table
#  AreaCode Measure  Value
#0        A      M1     13
#1        A      M1      1
#2        B      M1     15
#3        B      M1      1
#4        A      M2     54
#5        A      M2      1
#6        B      M2     17
#7        B      M2      1

The code to perform the aggregation would be:

table.groupby(['AreaCode', 'Measure'], as_index=False).sum()
#  AreaCode Measure  Value
#0        A      M1     14
#1        A      M2     55
#2        B      M1     16
#3        B      M2     18

Code to generate table and test this solution:

table = pd.DataFrame({'AreaCode': {0: 'A', 1: 'A', 2: 'B', 3: 'B', 4: 'A', 5: 'A', 6: 'B', 7: 'B'}, 'Measure': {0: 'M1', 1: 'M1', 2: 'M1', 3: 'M1', 4: 'M2', 5: 'M2', 6: 'M2', 7: 'M2'}, 'Value': {0: 13, 1: 1, 2: 15, 3: 1, 4: 54, 5: 1, 6: 17, 7: 1}})
ibarrond
  • 6,617
  • 4
  • 26
  • 45