pandas groupby,并设置项目集 [英] Pandas groupby and make set of items
问题描述
我正在使用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?
推荐答案
这是因为set
是type
type
,而to_set
是type
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:
function
或dict
用于汇总组的功能.
-
如果为
function
,则必须在传递DataFrame
或传递给时必须起作用DataFrame.apply
.
If a
function
, must either work when passed aDataFrame
or when passed toDataFrame.apply
.
如果传递了dict
,则键必须为DataFrame
列
名称.
If passed a dict
, the keys must be DataFrame
column
names.
可接受的组合是:
-
string
cythonized函数名称 -
function
string
cythonized function namefunction
list
函数
dict
列->函数
嵌套的dict
名称->函数字典
nested dict
of names -> dicts of functions
这篇关于 pandas groupby,并设置项目集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!