向pandas Series / DataFrame附加一个级别(具有固定值)

时间:2016-11-16 15:38:55

标签: python pandas dataframe multi-index

我有一个带有多索引的熊猫系列如下:

category_1  number
A           0         1.764052
            1         0.400157
            2         0.978738
            3         2.240893
            4         1.867558
C           0        -0.977278
            1         0.950088
            2        -0.151357
            3        -0.103219
            4         0.410599

它是从以下代码生成的:

import pandas as pd
import numpy as np
idx = pd.MultiIndex.from_product([['A','C'],range(5)], names=['category_1','number'])
np.random.seed(0)
s = pd.Series(index=idx, data = np.random.randn(len(idx)))

我想在索引中添加另一个名为category_2的级别,并使用固定值(即D)来获得以下结果:

category_1  category_2  number
A           D           0         1.764052
                        1         0.400157
                        2         0.978738
                        3         2.240893
                        4         1.867558
C           D           0        -0.977278
                        1         0.950088
                        2        -0.151357
                        3        -0.103219
                        4         0.410599

我一直用这种hacky方式来做到这一点:

df =s.to_frame('dummy')
df['category_2'] = 'D'
df.set_index('category_2', append = True, inplace = True)
df = df.reorder_levels([0,2,1])
res = df['dummy']

是否有更好的(更简洁/ pythonic)方式将具有固定值的级别添加到pandas Series / DataFrame上的现有级别?

1 个答案:

答案 0 :(得分:2)

您需要创建新的MultiIndex,然后替换旧版本:

#change multiindex
new_index = list(zip(s.index.get_level_values('category_1'), 
                     ['D'] * len(s.index), 
                     s.index.get_level_values('number')))
print (new_index)
[('A', 'D', 0), ('A', 'D', 1),
 ('A', 'D', 2), ('A', 'D', 3), 
 ('A', 'D', 4), ('C', 'D', 0), 
 ('C', 'D', 1), ('C', 'D', 2), 
 ('C', 'D', 3), ('C', 'D', 4)]
s.index = pd.MultiIndex.from_tuples(new_index, 
                                    names=['category_1','category_2','number'])
print (s)
category_1  category_2  number
A           D           0         1.764052
                        1         0.400157
                        2         0.978738
                        3         2.240893
                        4         1.867558
C           D           0        -0.977278
                        1         0.950088
                        2        -0.151357
                        3        -0.103219
                        4         0.410599
dtype: float64

MultiIndex.from_product的另一个不错的解决方案 - 有点改变comment

s.index = pd.MultiIndex.from_product([s.index.levels[0], 
                                      ['D'], 
                                      s.index.levels[1]], names= ['c1','c2','number']) 
print (s)
c1  c2  number
A   D   0         1.764052
        1         0.400157
        2         0.978738
        3         2.240893
        4         1.867558
C   D   0        -0.977278
        1         0.950088
        2        -0.151357
        3        -0.103219
        4         0.410599
dtype: float64

或者:

s.index = pd.MultiIndex.from_product([s.index.get_level_values('category_1').unique(), 
                                      ['D'],  
                                      s.index.get_level_values('number').unique()], 
                                     names= ['c1','c2','number']) 
print (s)
c1  c2  number
A   D   0         1.764052
        1         0.400157
        2         0.978738
        3         2.240893
        4         1.867558
C   D   0        -0.977278
        1         0.950088
        2        -0.151357
        3        -0.103219
        4         0.410599
dtype: float64