重新索引多索引更改结构并删除索引名称

时间:2015-08-20 18:15:39

标签: python pandas indexing scipy

我正在尝试使用元组列表来重新索引多索引Pandas.Series。该系列的结构如下

(Pdb) object

respondent  brand    
0           Asda     6
1           Tesco    7
2           Asda     9
3           Aldi     2
4           Asda     4
Name: rating, dtype: int64

和多索引结构如下

(Pdb) obj.index
MultiIndex(levels=[[0, 1, 2, 3, 4], [u'Aldi', u'Asda', u'Tesco']],
           labels=[[0, 1, 2, 3, 4], [1, 2, 1, 0, 1]],
           names=[u'respondent', u'brand'])

按照以下步骤进行重新索引

indexes = [(0, u'Asda'), (0, u'Tesco'), (0, u'Aldi'), (0, u'pick'), (1, u'Asda'), (1, u'Tesco'), (1, u'Aldi'), (1, u'pick'), (2, u'Asda'), (2, u'Tesco'), (2, u'Aldi'), (2, u'pick'), (3, u'Asda'), (3, u'Tesco'), (3, u'Aldi'), (3, u'pick'), (4, u'Asda'), (4, u'Tesco'), (4, u'Aldi'), (4, u'pick')]

obj.reindex(index=indexes, fill_value=default)

结果是

0  Asda     6
   Tesco    0
   Aldi     0
   pick     0
1  Asda     0
   Tesco    7
   Aldi     0
   pick     0
2  Asda     9
   Tesco    0
   Aldi     0
   pick     0
3  Asda     0
   Tesco    0
   Aldi     2
   pick     0
4  Asda     4
   Tesco    0
   Aldi     0
   pick     0

,多索引现在是

MultiIndex(levels=[[0, 1, 2, 3, 4], [u'Aldi', u'Asda', u'Tesco', u'pick']],
           labels=[[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4], [1, 2, 0, 3, 1, 2, 0, 3, 1, 2, 0, 3, 1, 2, 0, 3, 1, 2, 0, 3]])

这是一个问题,因为索引名称已被删除。有什么方法可以防止这种情况吗?如何解决?

2 个答案:

答案 0 :(得分:1)

我想我们可以制作新的DataFrame并将值添加到原始DataFrame中的新值:

In [134]:

print df
                  v
respondent brand   
0          Asda   6
1          Tesco  7
2          Asda   9
3          Aldi   2
4          Asda   4
In [135]:

Index = pd.MultiIndex.from_product((df.index.get_level_values(0).unique(), 
                                    df.index.get_level_values(1).unique()),
                                   names = df.index.names)
df2 = pd.DataFrame({'v': np.zeros(len(Index))},
                   index = Index)
In [136]:

print (df2+df).fillna(0)
                  v
respondent brand   
0          Aldi   0
           Asda   6
           Tesco  0
1          Aldi   0
           Asda   0
           Tesco  7
2          Aldi   0
           Asda   9
           Tesco  0
3          Aldi   2
           Asda   0
           Tesco  0
4          Aldi   0
           Asda   4
           Tesco  0

答案 1 :(得分:0)

我最终采取了一种稍微不同的方法,这对我来说效果更好。我最终构建了一个新的Index / MultiIndex,正确命名然后对此进行重新索引。

def re_index(obj, default, indexes):
    if isinstance(indexes[0], list):
        complete_index = pd.MultiIndex.from_product(indexes)
        complete_index.names = obj.index.names
    else:
        complete_index = pd.Index(data=indexes, name=obj.index.name)
        complete_index.name = obj.index.name

    new_obj = copy.copy(obj)
    return new_obj.reindex(index=complete_index, fill_value=default)