Sum with rows from two dataframes

Question:

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?

Asked By: user13948

||

Answers:

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
Answered By: Panda Kim
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.