将新索引添加到MultiIndex数据框熊猫的特定级别

时间:2018-09-24 22:37:01

标签: python pandas dataframe multi-index

以下是我要执行的操作的示例:

import io
import pandas as pd
data = io.StringIO('''Fruit,Color,Count,Price
Apple,Red,3,$1.29
Apple,Green,9,$0.99
Pear,Red,25,$2.59
Pear,Green,26,$2.79
Lime,Green,99,$0.39
''')
df_unindexed = pd.read_csv(data)
df = df_unindexed.set_index(['Fruit', 'Color'])

输出:

Out[5]: 
             Count  Price
Fruit Color              
Apple Red        3  $1.29
      Green      9  $0.99
Pear  Red       25  $2.59
      Green     26  $2.79
Lime  Green     99  $0.39

现在让我说我想计算“颜色”级别的键数:

L = []
for i in pd.unique(df.index.get_level_values(0)):
    L.append(range(df.xs(i).shape[0]))

list(np.concatenate(L))

然后,将结果列表[0,1,0,1,0]添加为新列:

df['Bob'] = list(np.concatenate(L))

如此:

             Count  Price  Bob
Fruit Color                   
Apple Red        3  $1.29    0
      Green      9  $0.99    1
Pear  Red       25  $2.59    0
      Green     26  $2.79    1
Lime  Green     99  $0.39    0

我的问题:

如何将Bob列作为与Color 相同级别的索引?这就是我想要的:

                 Count  Price
Fruit Color Bob                   
Apple Red    0    3     $1.29
      Green  1    9     $0.99
Pear  Red    0   25     $2.59
      Green  1   26     $2.79
Lime  Green  0   99     $0.39

2 个答案:

答案 0 :(得分:5)

您要寻找cumcount吗?如果是这样,您可以放弃循环并向量化您的解决方案。

df = df.set_index(df.groupby(level=0).cumcount(), append=True)
print(df)
               Count  Price
Fruit Color                
Apple Red   0      3  $1.29
      Green 1      9  $0.99
Pear  Red   0     25  $2.59
      Green 1     26  $2.79
Lime  Green 0     99  $0.39

或者,如果您希望一口气做到这一点,

df_unindexed = pd.read_csv(data)
df = df_unindexed.set_index(['Fruit', 'Color', df.groupby('Fruit').cumcount()])
print(df)
               Count  Price
Fruit Color                
Apple Green 0      9  $0.99
      Red   1      3  $1.29
Lime  Green 0     99  $0.39
Pear  Green 1     26  $2.79
      Red   0     25  $2.59

要重命名索引,请使用rename_axis

df = df.rename_axis(['Fruit', 'Color', 'Bob'])
print(df)
                 Count  Price
Fruit Color Bob              
Apple Red   0        3  $1.29
      Green 1        9  $0.99
Pear  Red   0       25  $2.59
      Green 1       26  $2.79
Lime  Green 0       99  $0.39

答案 1 :(得分:2)

IIUC,使用append的{​​{1}}参数:

set_index