Transform vs. aggregate in Pandas

故事扮演 提交于 2019-11-28 20:35:27

问题


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?


回答1:


consider the dataframe df

df = pd.DataFrame(dict(A=list('aabb'), B=[1, 2, 3, 4], C=[0, 9, 0, 9]))


groupby is the standard use aggregater

df.groupby('A').mean()


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 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']))



来源:https://stackoverflow.com/questions/40957932/transform-vs-aggregate-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!