python - Pandas:如何创建多索引枢轴

标签 python pandas dataframe pivot multi-index

我有一组由两个变量定义的实验:scenarioheight。对于每个实验,我进行 3 次测量:结果 1、2 和 3。 收集所有结果的数据框如下所示:

import numpy as np
import pandas as pd

df = pd.DataFrame()
df['Scenario']= np.repeat(['Scenario a','Scenario b','Scenario c'],3)
df['height'] = np.tile([0,1,2],3)
df['Result 1'] = np.arange(1,10)
df['Result 2'] = np.arange(20,29)
df['Result 3'] = np.arange(30,39)

如果我运行以下命令:

mypiv = df.pivot('Scenario','height').transpose()
writer = pd.ExcelWriter('test_df_pivot.xlsx')
mypiv.to_excel(writer,'test df pivot')
writer.save()

我获得了一个数据框,其中列是场景,行有一个由resultheight定义的多索引:

+----------+--------+------------+------------+------------+
|          | height | Scenario a | Scenario b | Scenario c |
+----------+--------+------------+------------+------------+
| Result 1 |      0 |          1 |          4 |          7 |
|          |      1 |          2 |          5 |          8 |
|          |      2 |          3 |          6 |          9 |
| Result 2 |      0 |         20 |         23 |         26 |
|          |      1 |         21 |         24 |         27 |
|          |      2 |         22 |         25 |         28 |
| Result 3 |      0 |         30 |         33 |         36 |
|          |      1 |         31 |         34 |         37 |
|          |      2 |         32 |         35 |         38 |
+----------+--------+------------+------------+------------+

如何创建交换索引的枢轴,即首先是 height,然后是 result

我找不到直接创建它的方法。我设法得到我想要的交换级别并对结果重新排序:

mypiv2 = mypiv.swaplevel(0,1 , axis=0).sortlevel(level=0,axis=0,sort_remaining=True)

但我想知道是否有更直接的方法。

最佳答案

可以先set_index然后 stackunstack :

print (df.set_index(['height','Scenario']).stack().unstack(level=1))
Scenario         Scenario a  Scenario b  Scenario c
height                                             
0      Result 1           1           4           7
       Result 2          20          23          26
       Result 3          30          33          36
1      Result 1           2           5           8
       Result 2          21          24          27
       Result 3          31          34          37
2      Result 1           3           6           9
       Result 2          22          25          28
       Result 3          32          35          38

关于python - Pandas:如何创建多索引枢轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38205540/

相关文章:

python - 将从一个函数返回的多个一维数组组合成一个二维数组python

python - 如何将列表转换为所需的字典格式

Python 'end' 参数无效语法错误

python - 用 Python 制作实时图表的好框架?

python - 如何获取 Pandas 列的频率计数?

python - Pandas Hdf 获取表信息

Python:for循环迭代通过对象,而不是字符串

pandas - 替换 Pandas MultiIndex 的所有级别中的 NaN 值

loops - Julia 迭代数据帧的行

python - Pandas 根据另一列的子字符串中的数字从子字符串切片中创建新列