无法在 python 中旋转 pandas 数据框

Cant pivot pandas dataframe in python

我有一个需要重塑的数据框:

sampl = pd.DataFrame({'ID': '5 6 6 6 6 7 7 7'.split(),
                   'VarName': 'one one two three two two one three'.split(),
                   'Value': '345 242 345 three two two 335 356'.split(),
                   'Week': '1 1 1 2 2 2 3 3'.split()
                   })

我需要那个形状:

但是我的编码器 return 错误:

pd.pivot(sampl, index='ID', values='Value', columns='VarName')

pd.pivot_table(sampl, index='ID', values='Value', columns='VarName')

感谢您的帮助。

print(
    sampl.pivot(index=["ID", "Week"], columns="VarName", values="Value")
    .reset_index()
    .fillna("")
    .rename_axis("", axis=1)
)

打印:

  ID Week  one  three  two
0  5    1  345            
1  6    1  242         345
2  6    2       three  two
3  7    2              two
4  7    3  335    356