2016-09-28 56 views
2

考虑的一个水平pd.Seriesspd.MultiIndexidx便捷的方式,以重新编制一个多指标

idx = pd.MultiIndex.from_product([list('AB'), [1, 3], list('XY')], 
           names=['one', 'two', 'three']) 
s = pd.Series(np.arange(8), idx) 
s 

one two three 
A 1 X  0 
      Y  1 
    3 X  2 
      Y  3 
B 1 X  4 
      Y  5 
    3 X  6 
      Y  7 
dtype: int32 

我想reindexlevel='two'np.arange(4)
我可以做到这一点:

s.unstack([0, 2]).reindex(np.arange(4), fill_value=0).stack().unstack([0, 1]) 

one two three 
A 0 X  0 
      Y  0 
    1 X  0 
      Y  1 
    2 X  0 
      Y  0 
    3 X  2 
      Y  3 
B 0 X  0 
      Y  0 
    1 X  4 
      Y  5 
    2 X  0 
      Y  0 
    3 X  6 
      Y  7 
dtype: int32 

但如果存在,我正在寻找更直接的东西。有任何想法吗?

回答

2

不幸的是如果需要reindexMultiIndex,需要各个层面:

mux = pd.MultiIndex.from_product([list('AB'), np.arange(4), list('XY')], 
           names=['one', 'two', 'three']) 

print (s.reindex(mux, fill_value=0)) 
one two three 
A 0 X  0 
      Y  0 
    1 X  0 
      Y  1 
    2 X  0 
      Y  0 
    3 X  2 
      Y  3 
B 0 X  0 
      Y  0 
    1 X  4 
      Y  5 
    2 X  0 
      Y  0 
    3 X  6 
      Y  7 
dtype: int32 

编辑的评论:

idx = pd.MultiIndex.from_tuples([('A', 1, 'X'), ('B', 3, 'Y')], 
           names=['one', 'two', 'three']) 
s = pd.Series([5,6], idx) 
print (s) 
one two three 
A 1 X  5 
B 3 Y  6 
dtype: int64 

mux = pd.MultiIndex.from_tuples([('A', 0, 'X'), ('A', 1, 'X'), 
           ('A', 2, 'X'), ('A', 3, 'X'), 
           ('B', 0, 'Y'), ('B', 1, 'Y'), 
           ('B', 2, 'Y'), ('B', 3, 'Y')], 
           names=['one', 'two', 'three']) 

print (s.reindex(mux, fill_value=0)) 
one two three 
A 0 X  0 
    1 X  5 
    2 X  0 
    3 X  0 
B 0 Y  0 
    1 Y  0 
    2 Y  0 
    3 Y  6 
dtype: int64 

直接解决

new_lvl = np.arange(4) 
mux = [(a, b, c) for b in new_lvl for a, c in s.reset_index('two').index.unique()] 
s.reindex(mux, fill_value=0).sort_index() 

one two three 
A 0 X  0 
      Y  0 
    1 X  0 
      Y  1 
    2 X  0 
      Y  0 
    3 X  2 
      Y  3 
B 0 X  0 
      Y  0 
    1 X  4 
      Y  5 
    2 X  0 
      Y  0 
    3 X  6 
      Y  7 
dtype: int64 
+0

这正是我在想的事情。但是,我无法在任何'MultiIndex'上一般使用'from_product'。例如,如果原始索引是'[('A',1,'X'),('B',3,'Y')]',我希望'level ='两个'reindex' ''将会返回'[''A',0,'X'),('A',1,'X'),('A',2,'X'),('A',3'' ('B',0,'Y'),('B',1,'Y'),('B',2,'Y'), )]' – piRSquared

+0

你是对的,你一般可以使用'from_product'。您只需要以某种方式创建新索引,然后重新索引。也许'from_tuples'。 – jezrael

+1

然后更复杂的是创建元组 - 也许列表理解可能会有帮助。 – jezrael

相关问题