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

如何调整DataFrame格式 实现行数据转为对应列结构

操作步骤

1. 先构造测试数据并修正拼写问题

你给出的可复现数据里Category列的Buildings存在拼写错误,先做修正避免结果不匹配:

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'Category': {0: 'Group', 1: 'Country', 2: 'People', 3: 'Buidings'},
    'Amount': {0: 5, 1: 10, 2: 100, 3: 50}
})
# 修正拼写错误
df['Category'] = df['Category'].replace('Buidings', 'Buildings')

2. 执行格式转换

有两种常用方法可以实现你要的宽表转换效果,任选其一即可:

方法1:索引转置法(最简便)
df_res = df.set_index('Category').T.reset_index(drop=True)
方法2:透视表法
df_res = df.pivot(columns='Category', values='Amount').reset_index(drop=True)

3. 输出验证

如果需要完全匹配你给出的无索引显示效果,打印时关闭行索引展示即可:

print(df_res.to_string(index=False))

输出结果:

Group  Country  People  Buildings
     5       10     100         50

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:39:03