如何在pandas中恢复未堆叠的数据帧

时间:2012-08-20 08:53:06

标签: pandas

我正在尝试将数据帧执行操作卸载(仅限时间),然后将其重新堆叠在一起,如下所示:

import pandas as pd
import numpy as np
from itertools import *

time = pd.date_range(pd.datetime(2007,1,1),pd.datetime(2007,1,2))
slot = map(lambda n:"s-"+str(n),reversed(range(2)))
obj  = map(lambda n:"o-"+str(n),reversed(range(2)))
idx  = pd.MultiIndex.from_tuples(list(product(slot, obj, time)), names=['Ananas','Bananas','time']) #list(.) needed to get a length, should this really be needed?
data = np.random.rand(len(idx),4)

df = pd.DataFrame(data=data,index=idx, columns=['a','b','c','d']) #why is idx.size==0?

print df.to_string()
print "====="
unstacked = df.unstack(level=[0,1])
print unstacked.to_string()
print "====="
stacked = unstacked.stack(level=[2,1])
print stacked.to_string()

问题是多指数在手术后反转,是否有任何简单的方法可以使这项工作?也许我从一开始就误用了堆栈?

1 个答案:

答案 0 :(得分:3)

stackunstack将级别添加到MultiIndex的 end ,这是不可控制的。您可以使用reorder_levels()更改MultiIndex中级别的顺序:stacked.reorder_levels([2, 1, 0])将为您提供与df

中相同的MultiIndex级别顺序