pandas groupby,并设置项目集 [英] Pandas groupby and make set of items

查看:88
本文介绍了 pandas groupby,并设置项目集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pandas groupby,并希望应用该功能来根据组中的项目进行设置.

I am using pandas groupby and want to apply the function to make a set from the items in the group.

以下内容无效:

df = df.groupby('col1')['col2'].agg({'size': len, 'set': set})

但是以下方法可行:

def to_set(x):
    return set(x)

df = df.groupby('col1')['col2'].agg({'size': len, 'set': to_set})

在我的理解中,两个表达式相似,请问第一个不起作用的原因是什么?

In my understanding the two expression are similar, what is the reason why the first does not work?

推荐答案

这是因为settype type,而to_settype function:

It's because set is of type type whereas to_set is of type function:

type(set)
<class 'type'>

def to_set(x):
    return set(x)

type(to_set)

<class 'function'>

根据文档.agg()预期:

arg:functiondict

用于汇总组的功能.

  • 如果为function,则必须在传递DataFrame或传递给时必须起作用 DataFrame.apply.

  • If a function, must either work when passed a DataFrame or when passed to DataFrame.apply.

如果传递了dict,则键必须为DataFrame列 名称.

If passed a dict, the keys must be DataFrame column names.

可接受的组合是:

  • string cythonized函数名称
  • function

  • string cythonized function name
  • function

list函数

dict列->函数

嵌套的dict名称->函数字典

nested dict of names -> dicts of functions

这篇关于 pandas groupby,并设置项目集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆