计算 Python Pandas 中数据帧的平均值

问题描述 投票:0回答:3

我有一个数据框列表。每个数据帧最初都是数字数据,其形状均相同,有 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 DataFrame 的平均值

如果可能的话,我正在寻找一种干净的解决方案,而不是简单地涉及按值循环每个数据帧的解决方案。有什么建议吗?

python pandas pandas-groupby
3个回答
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。这应该是你作为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

如果我们现在想做一个groupby,我们首先需要堆叠,groupby,再次堆叠

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


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 循环进行附加之外,您还可以提及要沿其连接数据帧的轴,在您的情况下,您希望沿索引(轴 = 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()

在写入时写入文件


0
投票
#First convert all your data frames to a numpy array, then use numpy  
#vector    based mean function. 
# import the two libraries 
import numpy as np
import pandas as pd
# convert to record arrays
ar_frame = [df.to_numpy(), for df in [df1, df2]]
# calculate the mean across the axis 1 for data frame
data_mean = np.mean(ar_frame, axis =1)
# convert back to pandas if required. use any of the data fram columns, 
#ofcourse this assumes that the columns names are the same across data 
#frames
df_mean = pd.DataFrame(data_mean, columns = df.columns)
© www.soinside.com 2019 - 2024. All rights reserved.