如何在熊猫中将长数据转换为宽数据?

时间:2021-03-12 20:08:13

标签: python pandas

类似问题:

(使用该链接中给出的方法时出现重复索引错误)

MWE

df_long = pd.DataFrame({'name': ['A', 'B', 'A', 'B'],
          'variable': ['height', 'height', 'width', 'width'],
          'value': [10, 20, 1, 2]})
print(df_long)
  name variable  value
0    A   height     10
1    B   height     20
2    A    width      1
3    B    width      2



============================

Requires answer

  name  height  width
0    A      10      1
1    B      20      2

我的尝试

(df_long.set_index(['name'])
        .stack()
        .unstack(0)
        .reset_index()
        .rename_axis(None, axis=1)
)

ValueError: Index contains duplicate entries, cannot reshape

1 个答案:

答案 0 :(得分:1)

df_long.pivot_table("value",["name"], "variable")

variable  height  width
name                   
A             10      1
B             20      2