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

如何用Python转置DataFrame行列并实现指定格式列对齐输出?

解决DataFrame转置为目标样式的方法

你可以用pandas的pivot方法将原始长格式DataFrame转换为目标宽格式,具体代码如下:

import pandas as pd

# 原始DataFrame
df = pd.DataFrame({
    "platform":['test3','test3','test3','test4','test4','test5','test5','test5','test6','test6'],
    "ripenes type":['OverRipes', 'Ripes','UnRipes','Ripes','UnRipes','OverRipes', 'Ripes','UnRipes', 'Ripes', 'UnRipes'],
    "total":[1,5,5,5,4,5,4,1,11,1]
})

# 转换为目标样式:platform作为行,成熟度类型作为列,total为对应值
target_df = df.pivot(
    index='platform',
    columns='ripenes type',
    values='total'
).fillna(0).astype(int)

# 可选:将platform从索引转为普通列
target_df = target_df.reset_index()

# 查看结果
print(target_df)

代码说明

  • pivot方法直接实现长表转宽表,指定index为行标识(platform),columns为列标识(ripenes type),values为填充的数值(total)。
  • fillna(0)用于填充缺失的类别组合(比如test4没有OverRipes记录,填充0)。
  • astype(int)确保数值为整数类型,匹配原始数据格式。

输出结果

ripenes type platform  OverRipes  Ripes  UnRipes
0                test3          1      5        5
1                test4          0      5        4
2                test5          5      4        1
3                test6          0     11        1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:15:43