我正在使用pandas groupby并希望应用该功能从组中的项目创建一个集合.
以下不起作用:
df = df.groupby('col1')['col2'].agg({'size': len, 'set': set})
Run Code Online (Sandbox Code Playgroud)
但以下工作:
def to_set(x):
return set(x)
df = df.groupby('col1')['col2'].agg({'size': len, 'set': to_set})
Run Code Online (Sandbox Code Playgroud)
在我的理解中,这两个表达式是相似的,第一个不起作用的原因是什么?
这是因为set是的type type,而to_set是type function:
type(set)
<class 'type'>
def to_set(x):
return set(x)
type(to_set)
<class 'function'>
Run Code Online (Sandbox Code Playgroud)
根据文档,.agg()预计:
arg:
function或dict用于聚合组的功能.
如果a
function,必须在传递aDataFrame或传递时工作DataFrame.apply.如果传递a
dict,则键必须是DataFrame列名.接受的组合是:
stringcythonized函数名称
function
list功能
dict列 - >函数嵌套
dict名称 - >功能的dicts
小智 5
尝试使用:
df = df.groupby('col1')['col2'].agg({'size': len, 'set': lambda x: set(x)})
Run Code Online (Sandbox Code Playgroud)
为我工作。
如果出现以下错误,请更新 Pandas 的新版本
SpecificationError: nested renamer is not supported
Run Code Online (Sandbox Code Playgroud)
SpecificationError: nested renamer is not supported
Run Code Online (Sandbox Code Playgroud)