【问题标题】:Compute Average/Mean across Dataframes in Python Pandas在 Python Pandas 中跨数据帧计算平均值/平均值
【发布时间】:2017-06-13 08:16:14
【问题描述】:

我有一个数据框列表。每个数据框最初都是取自其形状相同的数字数据,共有 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
...

我也已经看到了这个答案: Get the mean across multiple Pandas DataFrames

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

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    也许我误解了你的意思

    解决方案很简单。你只需要沿着正确的轴连接

    虚拟数据

    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,首先需要stack,groupby,再stack

    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()
    

    边写边写文件

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 2018-05-08
      • 2013-01-14
      • 2022-01-06
      • 2021-06-23
      • 1970-01-01
      相关资源
      最近更新 更多