Compare two values in pandas dataframe and if they are equal add it

98 views Asked by At

I am having a dataframe and while grouping on it, I get the below result set.

Name | Score | Salary A | SALARY B
ABC  | 20    | 300      | 500
XYZ  | 30    | 400      | 600
PQR  | 40    | 300      | 500
TFW  | 50    | 0        | 0
OIP  | 60    | 0        | 0
QWE  | 50    | None     | None
UYT  | 40    | None     | None

I need to compare the salaryA and salaryB values(salaryA v/s salaryA and salaryB v/s salaryB). If Salary is the same then I want to SUM the score else I have to take MAX of the score.

Expected output

Name     | Score
ABC, PQR | 60
XYZ      | 30
TFW      | 50
OIP      | 60
QWE      | 50
UYT      | 40
1

There are 1 answers

0
Lee On

I did it like this:

a = pd.read_csv('yourdata.dat',sep='|')
a['total'] = a.iloc[:,2] + a.iloc[:,3]
a.groupby('total').agg({'Name ':','.join,' Score ':'sum'}).reset_index()[['Name ',' Score ']]


         Name    Score 
0  ABC  ,PQR         60
1        XYZ         30