The Wayback Machine - https://web.archive.org/web/20240624161923/https://www.geeksforgeeks.org/how-to-sum-negative-and-positive-values-using-groupby-in-pandas/
Open In App

How to sum negative and positive values using GroupBy in Pandas?

Last Updated : 30 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to calculate the sum of all negative numbers and positive numbers in DataFrame using the GroupBy method in Pandas.

To use the groupby() method use the given below syntax.

Syntax: df.groupby(column_name)

Stepwise Implementation

Step 1: Creating lambda functions to calculate positive-sum and negative-sum values.

pos = lambda col : col[col > 0].sum()
neg = lambda col : col[col < 0].sum()

Step 2: We will use the groupby() method and apply the lambda function to calculate the sum.

d = df.groupby(df['Alphabet'])
print(d['Frequency'].agg([('negative_values', neg),
                         ('positive_values', pos)
                         ]))
print(d['Bandwidth'].agg([('negative_values', neg),
                         ('positive_values', pos)
                         ]))

Examples

Example 1: 

Calculate the sum of all positive as well as negative values of a, b, c for both columns i.e., Frequency and bandwidth

Python3




# Import Necessary Libraries
import pandas as pd
import numpy as np
  
# Creating a DataFrame with 
# random values
df = pd.DataFrame({'Alphabet': ['a', 'b', 'c', 'c',
                                'a', 'a', 'c', 'b'],
                     
                   'Frequency': [-10, 29, -12, -190,
                                 72, -98, -12, 0],
                     
                   'BandWidth': [10, 34, 23, -10, -87,
                                 -76, 365, 10]})
  
print(df)
  
# Group By dataframe on categorical
# values
d = df.groupby(df['Alphabet'])
  
# creating lambda function to calculate
# positive as well as negative values
def pos(col): 
  return col[col > 0].sum()
  
def neg(col): 
  return col[col < 0].sum()
  
  
# Apply lambda function to particular 
# column
print(d['Frequency'].agg([('negative_values', neg),
                          ('positive_values', pos)
                          ]))
  
print(d['Bandwidth'].agg([('negative_values', neg),
                          ('positive_values', pos)
                          ]))


Output:

Example 2:

Calculate the sum of all positive as well as negative values of a, b for both columns i.e., X and Y

Python3




# Import Necessary Libraries
import pandas as pd
import numpy as np
  
# Creating a DataFrame with random values
df = pd.DataFrame({'Function': ['F(x)', 'F(x)', 'F(y)',
                                'F(x)', 'F(y)', 'F(x)',
                                'F(x)', 'F(y)'],
                     
                   'X': [-10, 29, -12, -190, 72, -98,
                         -12, 0],
                     
                   'Y': [10, 34, 23, -10, -87, -76, 
                         365, 10]})
  
print(df)
  
# Group By dataframe on categorical values
d = df.groupby(df['Function'])
  
# creating lambda function to calculate
# positive as well as negative values
def pos(col): 
  return col[col > 0].sum()
  
def neg(col): 
  return col[col < 0].sum()
  
# Apply lambda function to particular 
# column
print(d['X'].agg([('negative_values', neg),
                  ('positive_values', pos)
                  ]))
  
print(d['Y'].agg([('negative_values', neg),
                  ('positive_values', pos)
                  ]))


Output:

DataFrame

X Output

Y Output

Example 3:

Calculate the sum of all positive as well as negative values of every name i.e., Marks. The next step is to make the lambda function to calculate the sum. In the last step, we will group the data according to the names and call the lambda functions to calculate the sum of the values.

Python3




# Import Necessary Libraries
import pandas as pd
import numpy as np
  
# Creating a DataFrame with random values
df = pd.DataFrame({'Name': ['Aryan', 'Nityaa', 'Dhruv',
                            'Dhruv', 'Nityaa', 'Aryan',
                            'Nityaa', 'Aryan', 'Aryan', 
                            'Dhruv', 'Nityaa', 'Dhruv', 
                            'Dhruv'],
                   'Marks': [90, 93, 78, 56, 34, 12, 67, 
                             45, 78, 92, 29, 88, 81]})
print(df)
  
# Group By dataframe on categorical values
d = df.groupby(df['Name'])
  
# creating lambda function to calculate
# positive as well as negative values
def pos(col): 
  return col[col > 0].sum()
  
def neg(col): 
  return col[col < 0].sum()
  
  
# Apply lambda function to particular
# column
print(d['Marks'].agg([('negative_values', neg),
                      ('positive_values', pos)
                      ]))


Output:

Names

Marks



Previous Article
Next Article

Similar Reads

Highlight the negative values red and positive values black in Pandas Dataframe
Let's see various methods to Highlight the positive values red and negative values black in Pandas Dataframe.First, Let's make a Dataframe: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], '
3 min read
Pandas - GroupBy One Column and Get Mean, Min, and Max values
We can use Groupby function to split dataframe into groups and apply different operations on it. One of them is Aggregation. Aggregation i.e. computing statistical parameters for each group created example - mean, min, max, or sums. Let's have a look at how we can group a dataframe by one column and get their mean, min, and max values. Example 1: i
2 min read
Python Program to find Sum of Negative, Positive Even and Positive Odd numbers in a List
Given a list. The task is to find the sum of Negative, Positive Even, and Positive Odd numbers present in the List. Examples: Input: -7 5 60 -34 1 Output: Sum of negative numbers is -41 Sum of even positive numbers is 60 Sum of odd positive numbers is 6 Input: 1 -1 50 -2 0 -3 Output: Sum of negative numbers is -6 Sum of even positive numbers is 50
7 min read
Pandas - Groupby multiple values and plotting results
In this article, we will learn how to groupby multiple values and plotting the results in one go. Here, we take "exercise.csv" file of a dataset from seaborn library then formed different groupby data and visualize the result. For this procedure, the steps required are given below : Import libraries for data and its visualization.Create and import
4 min read
Replace negative values with latest preceding positive value in Pandas DataFrame
In this article, we will discuss how to replace the negative value in Pandas DataFrame Column with the latest preceding positive value. While doing this there may arise two situations - Value remains unmodified if no proceeding positive value existsValue update to 0 if no proceeding positive value exists Let's discuss these cases in detail. Case 1:
3 min read
How to count unique values in a Pandas Groupby object?
Here, we can count the unique values in Pandas groupby object using different methods. This article depicts how the count of unique values of some attribute in a data frame can be retrieved using Pandas. Method 1: Count unique values using nunique() The Pandas dataframe.nunique() function returns a series with the specified axis's total number of u
3 min read
Pandas Groupby and Sum
It's a simple concept but it's an extremely valuable technique that's widely used in data science. It is helpful in the sense that we can : Compute summary statistics for every groupPerform group-specific transformationsDo the filtration of data The dataframe.groupby() involves a combination of splitting the object, applying a function, and combini
2 min read
Concatenate strings from several rows using Pandas groupby
Pandas Dataframe.groupby() method is used to split the data into groups based on some criteria. The abstract definition of grouping is to provide a mapping of labels to the group name. To concatenate string from several rows using Dataframe.groupby(), perform the following steps: Group the data using Dataframe.groupby() method whose attributes you
1 min read
Max and Min date in Pandas GroupBy
Prerequisites: Pandas Pandas GroupBy is very powerful function. This function is capable of splitting a dataset into various groups for analysis. Syntax: dataframe.groupby([column names]) Along with groupby function we can use agg() function of pandas library. Agg() function aggregates the data that is being used for finding minimum value, maximum
1 min read
How to combine Groupby and Multiple Aggregate Functions in Pandas?
Pandas is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. It is an open-source library that is built on top of NumPy library. Groupby() Pandas dataframe.groupby() function is used to split the data in dataframe int
1 min read
three90RightbarBannerImg