简体   繁体   中英

Group by two columns and get sum?

x1 = [{'id1': 'Africa', 'id2': 'Europe', 'v': 1}, 
      {'id1': 'Europe', 'id2': 'North America', 'v': 5},
      {'id1': 'North America', 'id2': 'Asia', 'v': 2,}, 
      {'id1': 'North America', 'id2': 'Asia', 'v': 3}]

df = pd.DataFrame(x1)

How would I group by continents and get the total sum based on column 'v'?

For example, I would expect to get sum of values for each continent as follow:

Africa: 1 (1)
Europe: 6 (1 + 5)
North America: 10 (5 + 2 + 3)
Europe: 6 (1 + 5)

Use melt and aggregate sum :

s = df.melt('v').groupby('value')['v'].sum()
print (s)
value
Africa            1
Asia              5
Europe            6
North America    10
Name: v, dtype: int64

For DataFrame :

df = df.melt('v', value_name='a').groupby('a', as_index=False)['v'].sum()
print (df)
               a   v
0         Africa   1
1           Asia   5
2         Europe   6
3  North America  10

Group by each column and then add the results:

df.groupby('id1').sum().add(df.groupby('id2').sum(), fill_value=0).astype(int)
#                v
#Africa          1
#Asia            5
#Europe          6
#North America  10

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