从宽到长转置熊猫数据帧

时间:2020-05-29 02:42:06

标签: python pandas dataframe

我已经检查了pandas.wide_to_longpandas.melt和各种SO帖子,但是在下面找不到针对该问题的解决方案。

我有这个数据框:

enter image description here

能否请您告诉我如何将其更改为这种格式?预先感谢。

enter image description here

1 个答案:

答案 0 :(得分:1)

让我们尝试以下操作:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Var1':[*'xyz'],
                  'Var2':['a']*3,
                  'Var1a':[1,5,9],
                  'Var2a':[2,6,10],
                  'Var3':[3,7,11],
                  'Var4':[4,8,12]})

df_out = df.set_index(['Var2', 'Var1']).stack().unstack(1).droplevel(1)
df_out = df_out.rename_axis(index=None, columns=None)
df_out 

输出:

   x  y   z
a  1  5   9
a  2  6  10
a  3  7  11
a  4  8  12