【发布时间】:2019-03-07 16:03:53
【问题描述】:
我创建了以下名为df的数据框
col1 col2 col3
0 4 5 2
1 5 2 4
2 3 10 3
3 6 2 2
4 3 2 4
我现在想要的是翻转行,使 df 看起来像这样:
column_name value
0 col1 4
1 col2 5
2 col3 2
3 col1 5
4 col2 2
5 col3 4
... ... ...
我想我需要使用stack(),但我不确定如何使用。我已经尝试了以下
df = df.stack().rename_axis(['column_name']).reset_index(name = 'value')
但返回以下错误
raise ValueError('Length of names must match number of levels in '
ValueError: Length of names must match number of levels in MultiIndex.
问题:如何堆叠这些值以获得所需的数据帧?
【问题讨论】:
标签: python python-3.x pandas dataframe