Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum with rows from two dataframes

I have two dataframes. One has months 1-5 and a value for each month, which are the same for ever ID, the other has an ID and a unique multiplier e.g.:

data = [['m', 10], ['a', 15], ['c', 14]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['ID', 'Unique'])

data2=[[1,0.2],[2,0.3],[3,0.01],[4,0.5],[5,0.04]]
df2 = pd.DataFrame(data2, columns=['Month', 'Value'])

I want to do sum ( value / (1+unique)^(Month/12) ). E.g. for ID m, I want to do (value/(1+10)^(Month/12)), for every row in df2, and sum them. I wrote a for-loop to do this but since my real table has 277,000 entries this takes too long!

df['baseTotal']=0
for i in df.index.unique():
    for i in df2.Month.unique():
        df['base']= df2['Value']/pow(1+df.loc[i,'Unique'],df2['Month']/12.0)
        df['baseTotal']=df['baseTotal']+df['base']

Is there a more efficient way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

df['Unique'].apply(lambda x: (df2['Value']/((1+x) ** (df2['Month']/12))).sum())


0    0.609983
1    0.563753
2    0.571392
Name: Unique, dtype: float64
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading