Python Pandas,DF.groupby().agg(),agg()中的列引用

48 投票
2 回答
90590 浏览
提问于 2025-04-17 18:35

在一个具体的问题上,比如我有一个数据框叫DF

     word  tag count
0    a     S    30
1    the   S    20
2    a     T    60
3    an    T    5
4    the   T    10 

我想要找出每个“单词”对应的“标签”,并且这个标签的“计数”是最多的。所以返回的结果应该像这样

     word  tag count
1    the   S    20
2    a     T    60
3    an    T    5

我不在乎计数这一列,也不在乎顺序或索引是原来的还是乱的。返回一个字典,比如‘the’ : ‘S’,这样就可以了。

我希望可以这样做

DF.groupby(['word']).agg(lambda x: x['tag'][ x['count'].argmax() ] )

但是它不管用。我无法访问列的信息。

更抽象地说,在agg(函数)中,函数看到的参数是什么?

顺便问一下,.agg()和.aggregate()是一样的吗?

非常感谢。

2 个回答

18

这里有个简单的方法来理解传入的内容(即 unutbu)解决方案是如何“应用”的!

In [33]: def f(x):
....:     print type(x)
....:     print x
....:     

In [34]: df.groupby('word').apply(f)
<class 'pandas.core.frame.DataFrame'>
  word tag  count
0    a   S     30
2    a   T     60
<class 'pandas.core.frame.DataFrame'>
  word tag  count
0    a   S     30
2    a   T     60
<class 'pandas.core.frame.DataFrame'>
  word tag  count
3   an   T      5
<class 'pandas.core.frame.DataFrame'>
  word tag  count
1  the   S     20
4  the   T     10

你的函数实际上是在处理一个框架的子部分,这部分的变量都是相同的值(在这个例子中是“word”)。如果你传入的是一个函数,那么你需要处理可能包含非字符串类型的列的聚合;像“sum”这样的标准函数会为你处理这些情况。

注意,它不会自动对字符串类型的列进行聚合。

In [41]: df.groupby('word').sum()
Out[41]: 
      count
word       
a        90
an        5
the      30

你实际上是在对所有列进行聚合。

In [42]: df.groupby('word').apply(lambda x: x.sum())
Out[42]: 
        word tag count
word                  
a         aa  ST    90
an        an   T     5
the   thethe  ST    30

在这个函数里,你几乎可以做任何事情。

In [43]: df.groupby('word').apply(lambda x: x['count'].sum())
Out[43]: 
word
a       90
an       5
the     30
71

aggaggregate 是一样的。它的调用方式是逐个传入 DataFrame 的列(也就是 Series 对象)。


你可以使用 idxmax 来获取行中最大计数的索引标签:

idx = df.groupby('word')['count'].idxmax()
print(idx)

这样会得到

word
a       2
an      3
the     1
Name: count

然后可以用 loc 来选择 wordtag 列中的那些行:

print(df.loc[idx, ['word', 'tag']])

这样会得到

  word tag
2    a   T
3   an   T
1  the   S

注意,idxmax 返回的是索引的 标签df.loc 可以用来根据标签选择行。但是如果索引不是唯一的,也就是说有重复的索引标签,那么 df.loc 会选择 所有 具有 idx 中列出的标签的行。所以如果你使用 idxmaxdf.loc,要确保 df.index.is_uniqueTrue


另外,你也可以使用 applyapply 的调用方式是传入一个子 DataFrame,这样你就可以访问所有的列:

import pandas as pd
df = pd.DataFrame({'word':'a the a an the'.split(),
                   'tag': list('SSTTT'),
                   'count': [30, 20, 60, 5, 10]})

print(df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()]))

这样会得到

word
a       T
an      T
the     S

通常情况下,使用 idxmaxloc 比使用 apply 更快,尤其是在处理大型 DataFrame 时。你可以使用 IPython 的 %timeit 来测试:

N = 10000
df = pd.DataFrame({'word':'a the a an the'.split()*N,
                   'tag': list('SSTTT')*N,
                   'count': [30, 20, 60, 5, 10]*N})
def using_apply(df):
    return (df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()]))

def using_idxmax_loc(df):
    idx = df.groupby('word')['count'].idxmax()
    return df.loc[idx, ['word', 'tag']]

In [22]: %timeit using_apply(df)
100 loops, best of 3: 7.68 ms per loop

In [23]: %timeit using_idxmax_loc(df)
100 loops, best of 3: 5.43 ms per loop

如果你想要一个将单词映射到标签的字典,可以这样使用 set_indexto_dict

In [36]: df2 = df.loc[idx, ['word', 'tag']].set_index('word')

In [37]: df2
Out[37]: 
     tag
word    
a      T
an     T
the    S

In [38]: df2.to_dict()['tag']
Out[38]: {'a': 'T', 'an': 'T', 'the': 'S'}

撰写回答