![](/img/trans.png)
[英]How to perform a groupby and transform count with a condition in pandas
[英]Compute and broadcast a count in pandas (with groupby transform)
如何在 Pandas 中計算和廣播計數?
要計算計數:
df.groupby('field').size()
要將聚合廣播到原始數據幀:
df.groupby('field')['field_to_aggregate'].transform(aggregation)
如果我指定要聚合的字段和sum
、 mean
等聚合,后者會起作用。但是當我想要對分組字段進行簡單計數時,我沒有找到使其工作的方法。
(注意:我可以只使用第一個並重新加入原始表上的分組表,但我想避免加入,我正在尋找使用熊貓transform
的有效解決方案)
你可以試試:
result = df.groupby('field')['field_to_aggregate'].transform('size')
請注意, 'field_to_aggregate'
可以與'field'
相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.