繁体   English   中英

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

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

在一个具体问题上,假设我有一个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( 函数 )中的函数看作什么?

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

非常感谢。

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_unique注意df.index.is_uniqueTrue


另外,你可以使用apply apply的callable传递给一个子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'}

这是一个简单的方法来确定传递什么(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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM