Pandas GroupBy两个文本列并返回基于计数的最大行

时间:2016-06-09 21:47:55

标签: python pandas max

我试图找出最大(First_Word, Group)

import pandas as pd

df = pd.DataFrame({'First_Word': ['apple', 'apple', 'orange', 'apple', 'pear'],
           'Group': ['apple bins', 'apple trees', 'orange juice', 'apple trees', 'pear tree'],
           'Text': ['where to buy apple bins', 'i see an apple tree', 'i like orange juice',
                'apple fell out of the tree', 'partrige in a pear tree']},
          columns=['First_Word', 'Group', 'Text'])

  First_Word         Group                        Text
0      apple    apple bins     where to buy apple bins
1      apple   apple trees         i see an apple tree
2     orange  orange juice         i like orange juice
3      apple   apple trees  apple fell out of the tree
4       pear     pear tree     partrige in a pear tree

然后我做groupby

grouped = df.groupby(['First_Word', 'Group']).count()
                         Text
First_Word Group             
apple      apple bins       1
           apple trees      2
orange     orange juice     1
pear       pear tree        1

我现在想要将其过滤到只有最大Text计数的唯一索引行。您已经删除了apple bins,因为apple trees具有最大值。

                         Text
First_Word Group             
apple      apple trees      2
orange     orange juice     1
pear       pear tree        1

这个max value of group问题类似,但是当我尝试这样的事情时:

df.groupby(["First_Word", "Group"]).count().apply(lambda t: t[t['Text']==t['Text'].max()])

我收到错误:KeyError: ('Text', 'occurred at index Text')。如果我将axis=1添加到apply,我会IndexError: ('index out of bounds', 'occurred at index (apple, apple bins)')

1 个答案:

答案 0 :(得分:2)

鉴于grouped,您现在希望按First Word索引级别进行分组,并找到每个组的最大行的索引标签(使用idxmax):

In [39]: grouped.groupby(level='First_Word')['Text'].idxmax()
Out[39]: 
First_Word
apple       (apple, apple trees)
orange    (orange, orange juice)
pear           (pear, pear tree)
Name: Text, dtype: object

然后,您可以使用grouped.loc按索引标签从grouped中选择行:

import pandas as pd
df = pd.DataFrame(
    {'First_Word': ['apple', 'apple', 'orange', 'apple', 'pear'],
     'Group': ['apple bins', 'apple trees', 'orange juice', 'apple trees', 'pear tree'],
     'Text': ['where to buy apple bins', 'i see an apple tree', 'i like orange juice',
              'apple fell out of the tree', 'partrige in a pear tree']},
    columns=['First_Word', 'Group', 'Text'])

grouped = df.groupby(['First_Word', 'Group']).count()
result = grouped.loc[grouped.groupby(level='First_Word')['Text'].idxmax()]
print(result)

产量

                         Text
First_Word Group             
apple      apple trees      2
orange     orange juice     1
pear       pear tree        1