python pandas,DF.groupby().agg(),agg() 中的列引用

python pandas, DF.groupby().agg(), column reference in agg()

提问人:jf328 提问时间:3/10/2013 最后编辑:Brad Solomonjf328 更新时间:9/22/2017 访问量:90078

问:

在一个具体问题上,假设我有一个 DataFrame 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(function) 中的函数将什么视为其参数

顺便说一句,.agg() 和 .aggregate() 一样吗?

非常感谢。

熊猫 分组依据 拆分-应用-合并

评论


答:

71赞 unutbu 3/10/2013 #1

agg与 相同。它是可调用的,一次传递一个 的列(对象)。aggregateSeriesDataFrame


您可以使用来收集具有最大值的行的索引标签 计数:idxmax

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

收益 率

word
a       2
an      3
the     1
Name: count

,然后用于选择 AND 列中的那些行:locwordtag

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

收益 率

  word tag
2    a   T
3   an   T
1  the   S

请注意,这返回索引标签。 可用于选择行 按标签。但是,如果索引不是唯一的,也就是说,如果存在具有重复索引标签的行,则将选择具有 中列出的标签的所有行。所以要小心,如果你使用idxmaxdf.locdf.locidxdf.index.is_uniqueTrueidxmaxdf.loc


或者,您可以使用 .的可调用对象被传递一个子 DataFrame,它允许您访问所有列:applyapply

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

使用 和 通常比 快,尤其是对于大型 DataFrame。使用 IPython 的 %timeit:idxmaxlocapply

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'}

评论

0赞 unutbu 8/24/2015
@bananafish:语法变得更简单了:您现在可以使用了。df.groupby('word')['count'].idxmax()
18赞 Jeff 3/10/2013 #2

这里有一个简单的方法可以弄清楚正在传递什么(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

你的函数只是在帧的一个子部分上操作(在这种情况下),分组变量都具有相同的值(在这个 CAS '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ă 11/17/2016
这个函数应该返回什么?