Python pandas.melt如何将行值转换为列名?[duplicate]

x33g5p2x  于 2022-11-26  发布在  Python
关注(0)|答案(1)|浏览(155)
    • 此问题在此处已有答案**:

Transpose pandas dataframe(2个答案)
How do I transpose dataframe in pandas without index?(3个答案)
2天前关闭。
我正在尝试使用pandas.melt()pandas.pivot()将行从列食物类型转换为列标题,将日期转换为行。

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

最终的结果应该是这样的。

Banana  cereals   Rice
 2021    104      105.7    105.5
 Oct-21  104.4    105.8    106.5
 Nov-21  105.5    97.5     98.2
t3irkdon

t3irkdon1#

Food-Type设置为索引后,使用transposition

out = df.set_index('Food-Type').T

输出量:

Food-Type  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

备选方案:

out = df.set_index('Food-Type').T.rename_axis(columns=None)

输出量:

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

相关问题