我在使用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发布于 2016-08-18 20:18:59
您可以使用unstack和stack
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: int64https://stackoverflow.com/questions/39026671
复制相似问题