![]() |
VOOZH | about |
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)
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)
]))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:
👁 ImageExample 2:
Calculate the sum of all positive as well as negative values of a, b for both columns i.e., X and 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.