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

jf3*_*328 42 python group-by pandas split-apply-combine

在一个具体问题上,假设我有一个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 
Run Code Online (Sandbox Code Playgroud)

对于每个"单词",我想找到具有最多"计数"的"标签".所以回报就像是

     word  tag count
1    the   S    20
2    a     T    60
3    an    T    5
Run Code Online (Sandbox Code Playgroud)

我不关心计数列,或者订单/索引是原始的还是搞砸了.返回字典{ 'the':'S',...}就好了.

我希望我能做到

DF.groupby(['word']).agg(lambda x: x['tag'][ x['count'].argmax() ] )
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我无法访问列信息.

更抽象地说,agg(函数)中的函数看作什么?

顺便说一下,.agg()与.aggregate()相同吗?

非常感谢.

unu*_*tbu 69

agg是一样的aggregate.它的可调用性是一次一个地传递给它的列(Series对象)DataFrame.


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

idx = df.groupby('word')['count'].idxmax()
print(idx)
Run Code Online (Sandbox Code Playgroud)

产量

word
a       2
an      3
the     1
Name: count
Run Code Online (Sandbox Code Playgroud)

然后使用loc选择wordtag列中的那些行:

print(df.loc[idx, ['word', 'tag']])
Run Code Online (Sandbox Code Playgroud)

产量

  word tag
2    a   T
3   an   T
1  the   S
Run Code Online (Sandbox Code Playgroud)

请注意,idxmax返回索引标签.df.loc可用于按标签选择行.但是,如果索引不是唯一的 - 也就是说,如果存在具有重复索引标签的行 - 那么df.loc将选择具有列出的标签的所有行idx.所以,要小心,df.index.is_uniqueTrue如果你使用idxmaxdf.loc


另外,你可以使用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()]))
Run Code Online (Sandbox Code Playgroud)

产量

word
a       T
an      T
the     S
Run Code Online (Sandbox Code Playgroud)

使用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
Run Code Online (Sandbox Code Playgroud)

如果你想要一个字典映射单词到标签,那么你可以使用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'}
Run Code Online (Sandbox Code Playgroud)


Jef*_*eff 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
Run Code Online (Sandbox Code Playgroud)

你的函数只是在帧的子部分运行(在这种情况下),分组变量都具有相同的值(在这个cas'sword'中),如果你传递一个函数,那么你必须处理聚合潜在的非字符串列; 标准函数,如'sum'为您执行此操作

自动不在字符串列上聚合

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

您正在聚合所有列

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
Run Code Online (Sandbox Code Playgroud)

你可以在函数中做任何事情

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