我有一个数据框列表。每个数据框最初都是从中提取的数字数据,它们的形状都相同,有 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 的解决方案。有什么建议吗?
最佳答案
可能是我理解错了
解决方法很简单。你只需要沿着正确的轴连接
虚拟数据
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) ])
附言。这应该是你作为 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')
如果你可以覆盖文件路径
关于python - 在 Python Pandas 中计算跨数据帧的平均值/平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44515888/