例如,如何在pandas中执行以下R data.table操作:
PATHS[,.( completed=sum(exists), missing=sum(not(exists)), total=.N, 'size (G)'=sum(sizeMB)/1024), by=.(projectPath, pipelineId)]
Run Code Online (Sandbox Code Playgroud)
即group by projectPath和pipelineId,使用可能的自定义函数聚合一些列,然后重命名结果列.
输出应该是没有分层索引的DataFrame,例如:
projectPath pipelineId completed missing size (G)
/data/pnl/projects/TRACTS/pnlpipe 0 2568 0 45.30824
/data/pnl/projects/TRACTS/pnlpipe 1 1299 0 62.69934
Run Code Online (Sandbox Code Playgroud)
Psi*_*dom 15
你可以使用groupby.agg:
df.groupby(['projectPath', 'pipelineId']).agg({
'exists': {'completed': 'sum', 'missing': lambda x: (~x).sum(), 'total': 'size'},
'sizeMB': {'size (G)': lambda x: x.sum()/1024}
})
Run Code Online (Sandbox Code Playgroud)
样品运行:
df = pd.DataFrame({
'projectPath': [1,1,1,1,2,2,2,2],
'pipelineId': [1,1,2,2,1,1,2,2],
'exists': [True, False,True,True,False,False,True,False],
'sizeMB': [120032,12234,223311,3223,11223,33445,3444,23321]
})
df1 = df.groupby(['projectPath', 'pipelineId']).agg({
'exists': {'completed': 'sum', 'missing': lambda x: (~x).sum(), 'total': 'size'},
'sizeMB': {'size (G)': lambda x: x.sum()/1024}
})
?
df1.columns = df1.columns.droplevel(0)
?
df1.reset_index()
Run Code Online (Sandbox Code Playgroud)
更新:如果您确实要在不使用已弃用的嵌套字典语法的情况下自定义聚合,则始终可以使用groupby.apply并返回每个组中的Series对象:
df.groupby(['projectPath', 'pipelineId']).apply(
lambda g: pd.Series({
'completed': g.exists.sum(),
'missing': (~g.exists).sum(),
'total': g.exists.size,
'size (G)': g.sizeMB.sum()/1024
})
).reset_index()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
666 次 |
| 最近记录: |