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

如何计算指定格式下Pandas DataFrame中x、y列的分组方差

解决方案

你可以直接按列名分组后按行计算方差,核心实现代码如下:

import pandas as pd
import numpy as np

# 构造示例DataFrame
row = (1, 2)
columns = ["x", "y", "x", "y", "x", "y", "x", "y"]
data = ([10, 2, 8, 1.5, 9, 2, 11, 1.6], [8, 3, 7.5, 2.2, 9, 2, 8.6, 2.3])
df = pd.DataFrame(data, index = row, columns = columns)

# 核心计算逻辑:按列名分组,逐行计算方差
result = df.groupby(df.columns, axis=1).var(axis=1)
# 如果需要计算总体方差(除以样本数n而非n-1),可以改用以下代码:
# result = df.groupby(df.columns, axis=1).var(axis=1, ddof=0)

print(result)

运行后输出结果和要求的理想格式完全一致:

x         y
1  1.666667  0.082500
2  0.509167  0.022500

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:57:03