Python - Sum negative and positive values using GroupBy in Pandas


Let us see how to find the sum of negative and positive values. At first, create a dataframe with positive and negative values −

dataFrame = pd.DataFrame({'Place': ['Chicago', 'Denver', 'Atlanta', 'Chicago', 'Dallas', 'Denver','Dallas', 'Atlanta'], 'Temperature': [-2, 30, -5, 10, 30, -5, 20, -10]})

Next, use groupby to group on the basis of Place column −

groupRes = dataFrame.groupby(dataFrame['Place'])

Use lambda function to return the positive and negative values. We have also added the positive and negative values individually −

# lambda function
def plus(val):
   return val[val > 0].sum()
def minus(val):
   return val[val < 0].sum()

Example

Following is the complete code −

import pandas as pd

# create a DataFrame with temperature in celsius
dataFrame = pd.DataFrame({'Place': ['Chicago', 'Denver', 'Atlanta', 'Chicago', 'Dallas', 'Denver','Dallas', 'Atlanta'], 'Temperature': [-2, 30, -5, 10, 30, -5, 20, -10]})
print(dataFrame)

# using groupby to group on the basis of place
groupRes = dataFrame.groupby(dataFrame['Place'])

# lambda function
def plus(val):
   return val[val > 0].sum()
def minus(val):
   return val[val < 0].sum()

print(groupRes['Temperature'].agg([('negTemp', minus), ('posTemp', plus)]))

Output

This will produce the following code −

      Place      Temperature
0   Chicago               -2
1    Denver               30
2   Atlanta               -5
3   Chicago               10
4    Dallas               30
5    Denver               -5
6    Dallas               20
7   Atlanta              -10
           negTemp  posTemp
Place
Atlanta        -15       0
Chicago         -2      10
Dallas           0      50
Denver          -5      30

Updated on: 09-Sep-2021

945 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements