如何进行“多索引”分组

2024-04-25 08:53:09 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我想说我是python的初学者,但这里有一个数据帧:

df = pd.DataFrame({'countingVariable': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'], 'color': ['red', 'red', 'orange', 'yellow', 'yellow', 'orange', 'red', 'yellow', 'orange'], 'foods': ['apple', 'pepper', 'apple', 'apple', 'apple', 'pepper', 'pepper', 'apple', 'apple']})
b = df.groupby(['color', 'foods']).count().sort_values(['countingVariable', 'foods', 'color'], ascending = [False, False, False])

其中b如下所示:

               countingVariable
color  foods                   
yellow apple                  3
red    pepper                 2
orange apple                  2
       pepper                 1
red    apple                  1

但我希望它看起来像这样:

               countingVariable
color  foods                   
yellow apple                  3
red    pepper                 2
       apple                  1
orange apple                  2
       pepper                 1

因此程序将找到最高的计数,然后将其与所属组的其他成员一起放在顶部


Tags: 数据falseappledataframedfredcolorpd
3条回答

真奇怪。将初始输出显示为

print(b)
               countingVariable
color  foods                   
yellow apple                  3
red    pepper                 2
orange apple                  2
       pepper                 1
red    apple                  1

然而,当我使用你的精确代码时,我得到了不同的输出

df = pd.DataFrame({
  'countingVariable': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'],
  'color': ['red', 'red', 'orange', 'yellow', 'yellow', 'orange', 'orange', 'yellow', 'orange'],
  'foods': ['apple', 'pepper', 'apple', 'apple', 'apple', 'pepper', 'pepper', 'apple', 'apple']
    })
b = df.groupby(['color', 'foods']).count().sort_values(['countingVariable', 'foods', 'color'],
               ascending = [False, False, False])

print(b)
               countingVariable
color  foods                   
yellow apple                  3
orange pepper                 2
       apple                  2
red    pepper                 1
       apple                  1

这似乎是你真正想要的输出。你知道吗

编辑

也许你发布的数据与你实际使用的数据有些不同?你知道吗

需要在第0级.reindex获得你的分类(食物按最高计数,然后在食物中下降)。这是因为pd.unique保存器是有序的。你知道吗

import pandas as pd

b = b.reindex(b.index.unique(level=0), level=0)

输出:

               countingVariable
color  foods                   
yellow apple                  3
red    pepper                 2
       apple                  1
orange apple                  2
       pepper                 1

这应该可以做到:

df.groupby(['color', 'foods']).count().sort_values('countingVariable', ascending=False)

输出:

               countingVariable
color  foods                   
yellow apple                  3
orange apple                  2
       pepper                 2
red    apple                  1
       pepper                 1

相关问题 更多 >