从不同的数据帧计算单元的平均值

时间:2020-08-08 16:30:03

标签: python-3.x pandas dataframe

我想从不同的数据框中计算多个单元的平均值。我已经用df.corr()计算了变量之间的相关性,我必须再做9次并计算每个变量的相关性平均值。

例如,我得到的第一个具有相关性的数据帧可能是这样:

    a    b    c  
__________________

a  1   0.2   0.3

b  0.2   1   0.4

c  0.3   0.4  1   

第二个相关数据帧可能是这样:

    a    b    c  
__________________

a  1   0.3   0.2

b  0.3   1   0.4

c  0.2  0.4  1   

我想获得一个最终的数据帧,其中考虑到所有数据帧,每个单元格的均值。


df_result

    a    b    c  
__________________

a  1   0.25   0.25

b  0.25   1   0.4

c  0.25   0.4  1   

2 个答案:

答案 0 :(得分:1)

这很向前,您可以这样做:

(df1.corr() + df2.corr()) / 2

因为两个数据框具有相同的列

答案 1 :(得分:0)

Average of multiple dataframes with the same columns and indices中所述,最好使用内置的pandas mean()方法以获得更好的性能。

以下代码将迭代许多随机生成的数据帧,将每个相关矩阵附加到列表中,然后使用内置的mean()函数取平均值。

import pandas as pd
import numpy as np

rs = np.random.RandomState(0)
correlation_matrices = []

for _ in range(10):
    df = pd.DataFrame(rs.rand(3, 3))
    correlation_matrices.append(df.corr())

correlation = pd.concat(correlation_matrices).groupby(level=0)
mean_corr = correlation.mean()
std_corr = correlation.std()
相关问题