我发现Hadley 对R 的plyr包非常有帮助,它是一个用于转换数据的优秀DSL.解决的问题是如此常见,以至于在不操作R中的数据时,我会面对其他用例,但在其他编程语言中.
有谁知道是否存在一个为python做类似事情的模块?就像是:
def ddply(rows, *cols, op=lambda group_rows: group_rows):
"""group rows by cols, then apply the function op to each group
and return the results aggregating all groups
rows is a dict or list of values read by csv.reader or csv.DictReader"""
pass
Run Code Online (Sandbox Code Playgroud)
实施起来应该不会太难,但如果已经存在则会很好.我实现它,我用itertools.groupby它分组cols,然后应用op函数,然后使用itertools.chain将它全部链接起来.有更好的解决方案吗?
这是我起草的实施:
def ddply(rows, cols, op=lambda group_rows: group_rows):
"""group rows by cols, then apply the function op to each group
rows is list of values or dict with col names (like read from
csv.reader or csv.DictReader)"""
def group_key(row):
return (row[col] for col in cols)
rows = sorted(rows, key=group_key)
return itertools.chain.from_iterable(
op(group_rows) for k,group_rows in itertools.groupby(rows, key=group_key))
Run Code Online (Sandbox Code Playgroud)
另一步骤是将有一组可以被应用为预定义的功能op,像sum和其他实用功能.
| 归档时间: |
|
| 查看次数: |
1025 次 |
| 最近记录: |