tit*_*dam 4 python dataframe python-3.x pandas
我创建了以下数据帧 df
col1 col2 col3
0 4 5 2
1 5 2 4
2 3 10 3
3 6 2 2
4 3 2 4
Run Code Online (Sandbox Code Playgroud)
我现在想要的是翻转行,以便df看起来像这样:
column_name value
0 col1 4
1 col2 5
2 col3 2
3 col1 5
4 col2 2
5 col3 4
... ... ...
Run Code Online (Sandbox Code Playgroud)
我想我需要使用stack(),但我不确定如何.我尝试了以下内容
df = df.stack().rename_axis(['column_name']).reset_index(name = 'value')
Run Code Online (Sandbox Code Playgroud)
但是会返回以下错误
raise ValueError('Length of names must match number of levels in '
ValueError: Length of names must match number of levels in MultiIndex.
Run Code Online (Sandbox Code Playgroud)
问题:如何堆叠值以便获得所需的数据帧?
这里有必要采用去除多指标的第一级reset_index有drop=True:
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
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |