我正在使用Dask处理数据集(考虑到它不适合内存),我希望根据列和它的类型,使用不同的聚合函数对实例进行分组。
对于数值数据类型,Dask有一组默认的聚合函数,但对于字符串/对象则没有。是否有一种方法可以为字符串实现用户定义的聚合函数,类似于下面的示例?
atts_to_group = {'A', 'B'}
agg_fn = {
'C': 'mean' #int
'D': 'concatenate_fn1' #string - No default fn for strings - Doesn't work
'E': 'concatenate_fn2' #string
}
ddf = ddf.groupby(atts_to_group).agg(agg_fn).compute().reset_index()此时,我可以在删除不相关的列/行时读取内存中的整个数据集,但考虑到执行所需的操作更快,我更希望继续在Dask中进行处理。
编辑:尝试将自定义函数直接添加到字典中:
def custom_concat(df):
...
return df_concatd
agg_fn = {
'C': 'mean' #int
'D': custom_concat(df)
}
-------------------------------------------------------
ValueError: unknown aggregate Dask DataFrame Structure:发布于 2018-09-03 16:35:41
已实现的达斯克提供了聚合数据结构。可以按以下方式进行自定义聚合:
# Concatenates the strings and separates them using ","
custom_concat = dd.Aggregation('custom_sum', lambda x: ",".join(str(x)), lambda x0: ",".join(str(x0)))
custom_concat_E = ...
atts_to_group = {'A', 'B'}
agg_fn = {
'C': 'mean' #int
'D': custom_concat_D
'E': custom_concat_E
}
ddf = ddf.groupby(atts_to_group).agg(agg_fn).compute().reset_index()这也可以用Dataframe.apply来完成,这样的解决方案不那么冗长。
def agg_fn(x):
return pd.Series(
dict(
C = x['C'].mean(), # int
D = "{%s}" % ', '.join(x['D']), # string (concat strings)
E = ...
)
)
ddf = ddf.groupby(atts_to_group).apply(agg_fn).compute().reset_indexhttps://stackoverflow.com/questions/52149746
复制相似问题