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

如何使用pandas.melt或pivot将Food-Type行值转为列名、日期转为行?

解决方法

原始数据构造

先把你提供的原始数据用pandas构造出来:

import pandas as pd

df = pd.DataFrame({
    'Food-Type': ['Banana', 'cereals', 'Rice'],
    '2021': [104, 105.7, 97.6],
    'Oct-21': [104.4, 105.8, 97.5],
    'Nov-21': [105.5, 106.5, 98.2]
})

转换步骤

只需要两步就能得到你要的结果:

  1. 将Food-Type列设置为数据框的索引
  2. 对数据框进行转置操作(.T)

代码如下:

# 设置Food-Type为索引
df.set_index('Food-Type', inplace=True)
# 转置得到目标结果
result = df.T

最终结果

运行上述代码后,result的输出就是你期望的格式:

Banana  cereals  Rice
2021      104.0    105.7  97.6
Oct-21    104.4    105.8  97.5
Nov-21    105.5    106.5  98.2

备注:如果不想修改原始数据框,可以去掉inplace=True,写成df.set_index('Food-Type').T一步完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:01:16