【问题标题】:python pandas, DF.groupby().agg(), column reference in agg()python pandas, DF.groupby().agg(), agg() 中的列引用
【发布时间】:2013-02-25 16:30:31
【问题描述】:

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

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

非常感谢。

【问题讨论】:

    标签: python pandas group-by split-apply-combine


    【解决方案1】:

    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 的可调用对象传递了一个子数据帧,它使您可以访问所有列:

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

    【讨论】:

    • @bananafish:语法变得更简单了:您现在可以使用df.groupby('word')['count'].idxmax()
    【解决方案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
    

    【讨论】:

    • 这个函数应该返回什么?
    猜你喜欢
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多