在Pandas中转换与聚合 [英] Transform vs. aggregate in Pandas
本文介绍了在Pandas中转换与聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在对Pandas DataFrame进行分组时,什么时候应该使用transform
,什么时候应该使用aggregate
?怎么做
它们在实际应用方面有所不同,您选择哪一个
认为更重要?
When grouping a Pandas DataFrame, when should I use transform
and when should I use aggregate
? How do
they differ with respect to their application in practice and which one do you
consider more important?
推荐答案
考虑数据框df
df = pd.DataFrame(dict(A=list('aabb'), B=[1, 2, 3, 4], C=[0, 9, 0, 9]))
groupby
是标准用途聚合器
df.groupby('A').mean()
也许您希望这些值在整个组中传播,并返回与开始时具有相同索引的内容.
使用transform
maybe you want these values broadcast across the whole group and return something with the same index as what you started with.
use transform
df.groupby('A').transform('mean')
df.set_index('A').groupby(level='A').transform('mean')
agg
用于当您有要针对不同列运行的特定内容或在同一列上运行多个内容的情况.
agg
is used when you have specific things you want to run for different columns or more than one thing run on the same column.
df.groupby('A').agg(['mean', 'std'])
df.groupby('A').agg(dict(B='sum', C=['mean', 'prod']))
这篇关于在Pandas中转换与聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文