如何使用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] })
转换步骤
只需要两步就能得到你要的结果:
- 将
Food-Type列设置为数据框的索引 - 对数据框进行转置操作(
.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
相关产品推荐
相关产品推荐

