Python Pandas,DF.groupby().agg(),agg()中的列引用 (注:这是一个提问标题,无需回答)

48

针对一个具体的问题,假设我有一个名为 DF 的 DataFrame。

     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() 和 .aggregate() 是一样的吗?
非常感谢。
2个回答

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 中的所有行。因此,请确保如果您要使用 df.loc 进行选择,则 df.index.is_uniqueTrue


或者,您可以使用 apply。可调用的 apply 将传递一个子 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()]))

产出(yields)
word
a       T
an      T
the     S

使用idxmaxloc通常比apply更快,特别是对于大型数据框。使用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'}

@bananafish:语法变得更简单了:现在可以使用 df.groupby('word')['count'].idxmax() - unutbu

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

1
这个函数应该返回什么? - Ciprian Tomoiagă

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接