Find and sum all negative values Find and sum all positive values
DATA
ID value
A -1
B -5
AA 1
TT 3
UV 4
QA 50
WQ -40
QC 10
DESIRED
positive 68
negative -46
DOING
df.groupby(df['value'].agg([('value' , lambda x : x[x < 0].sum()) , ('positive' , lambda x : x[x > 0].sum())])
Any suggestion is appreciated
CodePudding user response:
First, you have to make a dataframe of your data using pandas.
import pandas as pd
df = pd.DataFrame({'ID': ['A', 'B', 'AA', 'TT', 'UV', 'QA', 'WQ', 'QC'],
'value': [-1, -5, 1, 3, 4, 50, -40, 10]})
Then, sum the values greater than 0 and less than 0.
positive_sum = df[df['value'] > 0]['value'].sum()
negative_sum = df[df['value'] < 0]['value'].sum()
And, print out the results.
print("positive: ", positive_sum)
print("negative: ", negative_sum)
Output
CodePudding user response:
Maybe
import pandas as pd
df = pd.DataFrame({'ID': ['A', 'B', 'AA', 'TT', 'UV', 'QA', 'WQ', 'QC'],
'value': [-1, -5, 1, 3, 4, 50, -40, 10]})
negative_sum = df[df['value'] < 0]['value'].sum()
positive_sum = df[df['value'] > 0]['value'].sum()
print("negative sum:", negative_sum)
print("positive sum:", positive_sum)