I’m trying to unstack a dataframe perform operations on it (over time only) and then stack it back together like this:
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()
The problem is that multiindex is getting reversed after the operation, is there any easy way to make this work? Perhaps I’m misusing the stack from the start?
stackandunstackadd level(s) to the end of the MultiIndex, this is not controllable. You can change the order of the levels in a MultiIndex withreorder_levels():stacked.reorder_levels([2, 1, 0])will give you the same MultiIndex levels order as indf