例如,如何在 Pandas 中执行以下R data.table操作:

PATHS[,.( completed=sum(exists), missing=sum(not(exists)), total=.N, 'size (G)'=sum(sizeMB)/1024), by=.(projectPath, pipelineId)]

IE。按projectPathpipelineId分组,汇总一些列
使用可能的自定义函数,然后重命名结果列。

输出应该是没有分层索引的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

最佳答案

您可以使用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}
    })

sample 运行:
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()

python - 在 Pandas 中执行聚合和重命名操作的惯用方式是什么-LMLPHP

更新:如果您确实要自定义聚合而不使用不建议使用的嵌套字典语法,则可以始终使用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()

python - 在 Pandas 中执行聚合和重命名操作的惯用方式是什么-LMLPHP

关于python - 在 Pandas 中执行聚合和重命名操作的惯用方式是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45382114/

10-12 17:23
查看更多