Petr Petrov
Petr Petrov

Reputation: 4442

Pandas: get average dataframe

I have 50 dataframes with one structures, but values are different. How can I get average dataframe from all this?

       active nodes
graph              
0               128
1               128
2               128
3               127
4               126
5               126
6               126
7               126
8               126
9               125
10              124

Upvotes: 2

Views: 134

Answers (2)

piRSquared
piRSquared

Reputation: 294278

Using numpy instead.

Assume the list of dataframes dfs

dfs = [pd.DataFrame(np.random.randint(10, size=(10, 10))) for _ in range(50)]

Then calculate the mean by using np.concatenate then taking the mean. But being numpy this should also be quicker.

pd.Series(np.concatenate([df.values for df in dfs], axis=1).mean(1), dfs[0].index)

0    4.472
1    4.722
2    4.644
3    4.574
4    4.624
5    4.446
6    4.548
7    4.606
8    4.440
9    4.442
dtype: float64

timing

enter image description here

Upvotes: 1

acidtobi
acidtobi

Reputation: 1365

Add all your DataFrames to a list, concatenate them and calculate the mean of each row:

dfs = [df1, df2, ... dfn]
pd.concat(dfs, axis=1).mean(axis=1)

Upvotes: 4

Related Questions