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

如何将Anscombe数据集从长格式转换为宽格式

将Anscombe长格式数据集转换为宽格式

要把seaborn加载的长格式Anscombe数据集转换成你需要的宽格式,可以用pandas的pivot方法配合列名调整来实现,具体步骤如下:

完整代码实现

import seaborn as sns
import pandas as pd

# 加载长格式数据集
anscombe_long = sns.load_dataset("anscombe")

# 把dataset列的罗马数字转为阿拉伯数字,方便后续命名列
anscombe_long['dataset_num'] = anscombe_long['dataset'].map({
    'I': 1, 'II': 2, 'III': 3, 'IV': 4
})

# 生成每个数据集内的行序号(每个数据集有11条数据,序号从0到10)
anscombe_long['row_id'] = anscombe_long.groupby('dataset').cumcount()

# 转换为宽格式
anscombe_wide = anscombe_long.pivot(
    index='row_id',
    columns='dataset_num',
    values=['x', 'y']
)

# 调整列名:把多层列名合并成x1、y1这样的格式
anscombe_wide.columns = [f'{col[0]}{col[1]}' for col in anscombe_wide.columns]

# 重置索引,去掉row_id列
anscombe_wide = anscombe_wide.reset_index(drop=True)

# 查看结果
print(anscombe_wide)

输出结果

x1  x2  x3  x4     y1    y2     y3     y4
0   10  10  10   8   8.04  9.14   7.46   6.58
1    8   8   8   8   6.95  8.14   6.77   5.76
2   13  13  13   8   7.58  8.74  12.74   7.71
3    9   9   9   8   8.81  8.77   7.11   8.84
4   11  11  11   8   8.33  9.26   7.81   8.47
5   14  14  14   8   9.96  8.10   8.84   7.04
6    6   6   6   8   7.24  6.13   6.08   5.25
7    4   4   4  19   4.26  3.10   5.39  12.50
8   12  12  12   8  10.84  9.13   8.15   5.56
9    7   7   7   8   4.82  7.26   6.42   7.91
10   5   5   5   8   5.68  4.74   5.73   6.89

关键步骤说明

  • 罗马数字转阿拉伯数字:将dataset列的I/II/III/IV映射为1/2/3/4,确保最终列名符合x1/y1的格式要求。
  • 生成行序号:通过groupby.cumcount()为每个数据集内的行生成唯一序号,作为pivot的索引,保证每条数据能精准对应到宽格式的对应行。
  • 合并列名:pivot操作后会生成多层列名,通过列表推导式将两层列名合并为单一的xN/yN格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:43:21