1

I have 4 data frames:

df1 = pd.read_csv('values1.csv')
df2 = pd.read_csv('values2.csv')
df3 = pd.read_csv('values3.csv')
df4 = pd.read_csv('values4.csv')

each of them have a structure as follows: enter image description here

I want to create a new data frame such that it has aggregated values for each category in all the data frames. So, the new data frame should have values which are calculated using the formula :-

Total['values'][0] = df1['values'][0] / (df1['values'][0] + df2['values'][0]  + df3['values'][0]  + df4['values'][0] )

Like this it should generate values for all the rows. Can someone please help me out.

1

1 Answer 1

1

First join all DataFrames with concat and aggregate sum for Series and then convert column category to index for Series from df1 and divide by Series.div:

s = pd.concat([df1, df2, df3, df4]).groupby('category')['values'].sum()

out = df1.set_index('category')['values'].div(s).reset_index(name='total')

EDIT:

s = pd.concat([df1, df2, df3, df4]).groupby('category')['values'].sum()
s1 = pd.concat([df1, df2]).groupby('category')['values'].sum()

out = s1.div(s2).reset_index(name='new')
Sign up to request clarification or add additional context in comments.

6 Comments

what if I have to add df1 values and df2 values in the numerator and divide by the sum ?
Cool!!!!! Thanks alot! I thought I'll have to apply some very series for loops :p
Can you help me with one more thing.in each data frame I have 3 values columns, namely: value1, value2, value. I want to create a new data frame which has summed values row-wise for each category. I am not able to apply the above code for multiple columns
@user8306074 - I think you need s = pd.concat([df1, df2, df3, df4]).groupby('category')['value1','value2','value'].sum().sum(axis=1)
I think I'll create different lists and append them into one data frame
|

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.