VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-sum-negative-and-positive-values-using-groupby-in-pandas/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 30 May, 2021

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

Output:

👁 Image
👁 Image
👁 Image

Example 2:

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

Output:

👁 Image
DataFrame
👁 Image
X Output
👁 Image
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.

Output:

👁 Image
Names
👁 Image
Marks
Comment