在Python Pandas中计算多个数据框的平均/均值

4
我有一个数据框列表。每个数据框最初都是从中获取的数字数据,所有数据框都具有相同的形状,即21行5列。第一列是索引(索引0到索引20)。我想计算平均值并将其存储在单个数据框中。然后我想将该数据框导出到Excel。
以下是我现有代码的简化版本:
#look to concatenate the dataframes together all at once
#dataFrameList is the given list of dataFrames
concatenatedDataframes = pd.concat(dataFrameList, axis = 1)

#grouping the dataframes by the index, which is the same across all of the dataframes
groupedByIndex = concatenatedDataframes.groupby(level = 0)

#take the mean 
meanDataFrame = groupedByIndex.mean()

# Create a Pandas Excel writer using openpyxl as the engine.
writer = pd.ExcelWriter(filepath, engine='openpyxl')
meanDataFrame.to_excel(writer)

然而,当我打开Excel文件时,我看到每个数据帧好像都被复制到了工作表中,并且平均 / 均值数值没有显示。下面是一个简化的示例(减少了大部分行和数据框)。
              Dataframe 1                   Dataframe 2                   Dataframe 3
Index  Col2   Col3   Col4   Col5     Col2   Col3   Col4   Col5     Col2   Col3   Col4   Col5
0      Data   Data   Data   Data     Data   Data   Data   Data     Data   Data   Data   Data
1      Data   Data   Data   Data     Data   Data   Data   Data     Data   Data   Data   Data
2      Data   Data   Data   Data     Data   Data   Data   Data     Data   Data   Data   Data
....

我正在寻找更像这样的东西:
           Averaged DF
Index  Col2                                   Col3                                   Col4
0      Mean Index0,Col2 across DFs    Mean Index0,Col3 across DFs    Mean Index0,Col4 across DFs
1      Mean Index1,Col2 across DFs    Mean Index1,Col3 across DFs    Mean Index1,Col4 across DFs
2      Mean Index2,Col2 across DFs    Mean Index2,Col3 across DFs    Mean Index3,Col4 across DFs
...

我已经看到了这个答案: 获取多个Pandas数据框的平均值 如果可能的话,我正在寻找一个简洁的解决方案,而不是仅仅通过循环遍历每个数据框的值来实现的解决方案。有什么建议吗?
2个回答

2
也许我误解了你的问题。
解决方案很简单。你只需要沿着正确的轴连接即可。

虚拟数据

df1 = pd.DataFrame(index=range(rows), columns=range(columns), data=[[10 + i * j for j in range(columns)] for i in range(rows) ])
df2 = df1 = pd.DataFrame(index=range(rows), columns=range(columns), data=[[i + j for j in range(columns)] for i in range(rows) ])

ps. this should be your job as OP

pd.concat

df_concat0 = pd.concat((df1, df2), axis=1)

将所有数据框放在一起。

    0   1   0   1
0   10  10  0   1
1   10  11  1   2
2   10  12  2   3

如果我们现在想要进行分组,首先需要堆叠、分组再次堆叠。

df_concat0.stack().groupby(level=[0,1]).mean().unstack()

    0   1
0   5.0     5.5
1   5.5     6.5
2   6.0     7.5

如果我们执行

df_concat = pd.concat((df1, df2))

这将把所有的数据框叠放在一起。
    0   1
0   10  10
1   10  11
2   10  12
0   0   1
1   1   2
2   2   3

现在我们只需要像你做的那样,按索引进行分组:

df_concat.groupby(level=0).mean()

    0   1
0   5.0     5.5
1   5.5     6.5
2   6.0     7.5

然后使用ExcelWriter作为上下文管理器

with pd.ExcelWriter(filepath, engine='openpyxl') as writer:
    result.to_excel(writer)

或者只是简单的。
result.to_excel(filepath, engine='openpyxl') 

如果您可以覆盖filepath,那么:


这似乎会生成一个Series,但这不是我在寻找的。 - Keith Pham
我调整了我的回答,现在你已经澄清了你需要什么。 - Maarten Fabré
完美,正是我正在寻找的! - Keith Pham

2
我想你需要计算每列所有行的平均值。
将具有相同索引的数据帧列表连接起来会将其他数据帧的列添加到第一个数据帧的右侧。如下所示:
      col1  col2  col3  col1  col2  col3
    0     1     2     3     2     3     4
    1     2     3     4     3     4     5
    2     3     4     5     4     5     6
    3     4     5     6     5     6     7

尝试将数据框附加在一起,然后按组分组并取平均值以获得所需结果。
    ##creating data frames
    df1= pd.DataFrame({'col1':[1,2,3,4],
        'col2':[2,3,4,5],
        'col3':[3,4,5,6]})

    df2= pd.DataFrame({'col1':[2,3,4,5],
        'col2':[3,4,5,6],
        'col3':[4,5,6,7]})

    ## list of data frames
    dflist = [df1,df2]

    ## empty data frame to use for appending
    df=pd.DataFrame()

    #looping through each item in list and appending to empty data frame
    for i in dflist:
        df = df.append(i)

    # group by and calculating mean on index
    data_mean=df.groupby(level=0).mean()

当你写入文件时,可以像写入文本一样进行操作。

另外: 除了使用for循环添加之外,您还可以指定要连接数据框的轴向。在您的情况下,您希望沿着索引(axis=0)进行连接,将数据框置于彼此之上。如下所示:

       col1  col2  col3
    0     1     2     3
    1     2     3     4
    2     3     4     5
    3     4     5     6
    0     2     3     4
    1     3     4     5
    2     4     5     6
    3     5     6     7

    ##creating data frames
    df1= pd.DataFrame({'col1':[1,2,3,4],
                       'col2':[2,3,4,5],
                       'col3':[3,4,5,6]})

    df2= pd.DataFrame({'col1':[2,3,4,5],
                       'col2':[3,4,5,6],
                       'col3':[4,5,6,7]})

    ## list of data frames
    dflist = [df1,df2]

    #concat the dflist along axis 0 to put the data frames on top of each other
    df_concat=pd.concat(dflist,axis=0)

    # group by and calculating mean on index
    data_mean=df_concat.groupby(level=0).mean()

在编写代码的同时将内容写入文件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接