我创建了以下名为 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.
问题: 如何堆叠值以便获得所需的数据帧?
最佳答案
这里有必要使用 reset_index
和 drop=True
删除 MultiIndex 的第一级:
df = (df.stack()
.reset_index(level=0, drop=True)
.rename_axis(['column_name'])
.reset_index(name = 'value'))
print (df)
column_name value
0 col1 4
1 col2 5
2 col3 2
3 col1 5
4 col2 2
5 col3 4
6 col1 3
7 col2 10
8 col3 3
9 col1 6
10 col2 2
11 col3 2
12 col1 3
13 col2 2
14 col3 4
另一个解决方案是
melt
,改变了值的顺序:df = df.melt(var_name='column_name')
print (df)
column_name value
0 col1 4
1 col1 5
2 col1 3
3 col1 6
4 col1 3
5 col2 5
6 col2 2
7 col2 10
8 col2 2
9 col2 2
10 col3 2
11 col3 4
12 col3 3
13 col3 2
14 col3 4
关于python - 创建保存另一个数据框的列名和相应值的 df,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52609848/