使用`reindex`

时间:2016-08-18 20:07:29

标签: pandas dataframe multi-index reindex

使用reindex()计算我的DataFrame中的各种组合时,我遇到了一些困难。

以下代码重现了我的问题:

a = [
    ['Brand A' if i==0 else 'Brand B' for i in np.random.randint(0,2,size=(100,))],
    ['Type 1' if i==0 else 'Type 2' for i in np.random.randint(0,2,size=(100,))],
    ['Red' if i==0 else 'Blue' for i in np.random.randint(0,2,size=(100,))]
]
b = pd.DataFrame(a, index=['Brand', 'Type', 'Color']).T
b.loc[(b.Brand=='Brand A')&(b.Type=='Type 1'), 'Color'] = 'Red'   # no Blue, Type 1, Brand A
b.loc[(b.Brand=='Brand B')&(b.Type=='Type 2'), 'Color'] = 'Blue'  # no Red, Type 2, Brand B

c = b.groupby(['Brand','Type','Color'])
c.size()\
 .reindex(['Blue','Red'], level=2, fill_value=0)

输出:

Brand    Type    Color
Brand A  Type 1  Red      17
         Type 2  Blue     17
                 Red      19 
Brand B  Type 1  Blue     13
                 Red       9
         Type 2  Blue     25
dtype: int64

无论如何都要获得此输出:

Brand    Type    Color
Brand A  Type 1  Blue      0
                 Red      17
         Type 2  Blue     17
                 Red      19 
Brand B  Type 1  Blue     13
                 Red       9
         Type 2  Blue     25
                 Red       0
dtype: int64

1 个答案:

答案 0 :(得分:1)

您可以使用unstackstack

print (b.groupby(['Brand','Type','Color']).size().unstack(2, fill_value=0).stack())
Brand    Type    Color
Brand A  Type 1  Blue      0
                 Red      21
         Type 2  Blue     20
                 Red      14
Brand B  Type 1  Blue     15
                 Red      11
         Type 2  Blue     19
                 Red       0
dtype: int64

reindex MultiIndex.from_product的解决方案:

iterables = [['Brand A', 'Brand B'], ['Type 1', 'Type 2'], ['Blue','Red']]
idx = pd.MultiIndex.from_product(iterables, names=['Brand', 'Type', 'Color'])
print (b.groupby(['Brand','Type','Color']).size().reindex(idx, fill_value=0))
Brand    Type    Color
Brand A  Type 1  Blue      0
                 Red      21
         Type 2  Blue     20
                 Red      14
Brand B  Type 1  Blue     15
                 Red      11
         Type 2  Blue     19
                 Red       0
dtype: int64