You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas DataFrame的列均值存储为列格式?

问题解决方法

现有如下Pandas DataFrame:

A   B   C
0   5   3   8
1   5   3   9
2   8   4   9

使用df.mean()计算列均值后得到的是Series格式:

A    6.000000
B    3.333333
C    8.666667
dtype: float64

若要将其转换为如下指定格式的DataFrame(保留一位小数):

A     B     C
0   6.0   3.3   8.6

可以通过以下两种简洁方式实现:

方法一:转置+精度处理

import pandas as pd

# 构造原数据
df = pd.DataFrame({'A': [5,5,8], 'B': [3,3,4], 'C': [8,9,9]})

# 计算均值并转换格式
mean_df = df.mean().to_frame().T.round(1)
print(mean_df)

方法二:直接构造目标DataFrame

import pandas as pd

df = pd.DataFrame({'A': [5,5,8], 'B': [3,3,4], 'C': [8,9,9]})

mean_df = pd.DataFrame([df.mean().round(1)])
print(mean_df)

关键逻辑说明:

  • df.mean():计算各列均值,返回Series对象
  • .round(1):将均值保留一位小数,匹配目标格式的精度要求
  • to_frame().T:先把Series转为列结构的DataFrame,再通过转置得到行结构结果;或者直接用pd.DataFrame([...])将处理后的均值作为列表元素传入,直接生成目标格式的DataFrame

内容的提问来源于stack exchange,提问作者mostafiz67

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:21:01