Pyhon uses .groupby () as the example code of grouping operation.
This article mainly explains "pyhon uses .groupby () as grouping operation example code". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "pyhon uses .groupby () as grouping operation example code".
1. Construct the data source and give it a try.
Import pandas as pd df = pd.DataFrame ({"category": ["vegetables", "vegetables", "fruits", "fruits", "vegetables", "vegetables", "fruits", "aquatic products"], "quantity": [10, 20, 30, 40, 50, 60, 70, 80, 90100] df
two。 Practice, confirm whether the method is feasible or not
Df.sort_values (["category", "quantity"], ascending= [1d0], inplace=True) df_grouped = df.groupby (["category"]) .head (2) df_grouped
It's obviously feasible.
2.1 | 0Jing True or False, "true" or "false"
Import pandas as pd df1 = pd.DataFrame ({"category": ["vegetables", "vegetables", "fruits", "fruits", "vegetables", "vegetables", "fruits", "aquatic products"], "quantity": [10, 20, 30, 40, 50, 60, 70, 80, 90100] df1
Df.sort_values ([category "," quantity "], ascending= [True, False], inplace=True) df1_grouped = df.groupby ([" category "]) .head (3) df1_grouped
3. Add a little more hierarchical index
Import pandas as pd df2 = pd.read_excel (r "D:\ my documents\ jupyter.xlsx", sheet_name = 1) df2
Df2.sort_values ([True, False], inplace=True) df2_grouped = df2.groupby (["category"]) .head (3) df2_groupeddf2.sort_values (["city", "category", "sales quantity"], ascending= [True,True, False], inplace=True) df2_grouped = df2.groupby (["category"]) .head (3) df2_grouped
Df2.sort_values (["city", "category", "sales quantity"], ascending= [True,False, False], inplace=True) df2_grouped = df2.groupby (["category", "city"]) .head (3) df2_grouped
Thank you for your reading. The above is the content of "pyhon uses .groupby () as grouping operation instance code". After the study of this article, I believe you have a deeper understanding of the problem that pyhon uses .groupby () as grouping operation instance code, and the specific usage still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!