0
$\begingroup$

I have 5 Dataframe with same index and columns . but the numbers is them is different , I want to average it out . Is there any way to do that ?

$\endgroup$

2 Answers 2

0
$\begingroup$

Since in pandas the addition goes by index and columns, it is enough to simply add up all the dataframes and divide by their number.

import pandas as pd
a=pd.DataFrame([[1,2,3],[4,5,6]])
b=pd.DataFrame([[10,20,30],[40,50,60]],index=[1,0])
list_of_dataframes:list=[a,b]
sum(list_of_dataframes)/len(list_of_dataframes)
$\endgroup$
0
$\begingroup$

I am posting the answer that I came up with. A better and efficient answers are always welcomed.

def avg_dataframe(list_of_dataframes:list, common_index_column:str = 'Model') -> pd.DataFrame :
    scoresheet = None
    for num,i in enumerate(list_of_dataframes):
        i = i.reset_index()
        i = i.sort_values(common_index_column)
        
        if num == 0:
            scoresheet = i
        else:
            scoresheet = pd.concat([scoresheet, i], ignore_index=True)
    return scoresheet

and then use groupby method as;

new_scoresheet = avg_dataframe(data_list)

new_scoresheet.groupby('Model').mean()

this worked for me.

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.