2

Please use the image attached as reference .

I have two dataframes

df_class_a

with data :

Subject maximum minimum
Physics  98      50 
Maths    100     45 
Chem     99      65  

df_class_b with data

Subject maximum minimum
Maths    100     45 
Physics  98      44 
Chem     85      50 
language 88      54 

and I want to merge them to form a new data frame say df_add

Subject maximum minimum
Maths    200     90 
Physics  196     94 
Chem     184     115 
Language  88     54

which will be sum of the dataframes but both of them do not have same rows of data. How can I do it using .add functionality in pandas.

enter image description here

3 Answers 3

1

Another solution:

m = pd.merge(df1, df2, on='Subject', how='outer')
m['maximum'] = m[['maximum_x', 'maximum_y']].sum(axis=1)
m['minimum'] = m[['minimum_x', 'minimum_y']].sum(axis=1)

print(m[['Subject', 'maximum', 'minimum']])

Prints:

    Subject  maximum  minimum
0     Maths    200.0     90.0
1   Physics    196.0     94.0
2      Chem    184.0    115.0
3  language     88.0     54.0
Sign up to request clarification or add additional context in comments.

Comments

1

Convert Subject to index in both DataFrames by DataFrame.set_index and then use DataFrame.add with fill_value=0):

df = df_class_a.set_index('Subject').add(df_class_b.set_index('Subject'), fill_value=0)
print (df)
          maximum  minimum
Subject                   
Chem        184.0    115.0
Maths       200.0     90.0
Physics     196.0     94.0
language     88.0     54.0

Or use concat with aggregate sum:

df = pd.concat([df_class_a, df_class_b]).groupby('Subject', as_index=False).sum()
print (df)
    Subject  maximum  minimum
0      Chem      184      115
1     Maths      200       90
2   Physics      196       94
3  language       88       54

Comments

0

You can try:

df_add = pd.DataFrame({
'Subject': df_class_a['Subject'],
'Maximum': df_class_a['Maximum']+df_class_b['Maximum'],
'Minimum': df_class_a['Minimum']+df_class_b['Minimum']
})

1 Comment

I chnage data in question for see, why your solution is bad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.