Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to realize grouping in Pandas

Shulou Source: shulou.com Published: 2022-06-01 14:21:33 09月22日 Update

This article mainly explains "how Pandas realize grouping". The explanation content in this article is simple and clear, easy to learn and understand. Please follow the idea of Xiaobian and go deep into it slowly to study and learn "how Pandas realize grouping" together.

Create a test data frame

import pandas as pddf = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7,8],'c': ['x', 'y', 'x','y'],'d':["one","two","three","two"]})print(df) a b c d0 1 5 x one1 2 6 y two2 3 7 x three3 4 8 y two

Compute the average of groups grouped by c columns. Non-numerical columns are automatically ignored

print(df.groupby(df["c"]).mean()) a bc x 2 6y 3 7

multicolumn grouping

gb=df.groupby ([df["c"],df["d"])print(gb)#groupby stores grouping information, not grouped data for i,j in gb: print(i) print ('-----------') print(j)('x', 'one') ----------- a b c d0 1 5 x one ('x', 'three') ----------- a b c d2 3 7 x three('y', 'two') ----------- a b c d1 2 6 y two3 4 8 y two

aggregate function agg()

print(df.groupby(df["c"]).agg(['min','max']))a b d min max min max min maxc x 1 3 5 7 one threey 2 4 6 8 two two

Return results to data frame transform

print(df.groupby('c').transform('mean')) a b0 2 61 3 72 2 63 3 7

the PivotTable

table =pd.pivot_table(df, values='a', index=['c'],columns=['d'], aggfunc=np.sum)d one three twoc x 1.0 3.0 NaNy NaN NaN 6.0 Thank you for reading, the above is the content of "Pandas how to achieve grouping", after the study of this article, I believe everyone has a deeper understanding of Pandas how to achieve grouping, the specific use of the situation still needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Grouping data learning content information functions that is averages ideas situations numerical values articles more knowledge points articles results follow questions storage Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Huawei Shulou Tech Info Linux Shulou Technology