Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize grouping in Pandas

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report