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 ?
2 Answers
$\begingroup$
$\endgroup$
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)
$\begingroup$
$\endgroup$
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.