current position:Home>Pandas: how to group and calculate by index
Pandas: how to group and calculate by index
2022-01-30 11:52:26 【Stone sword】
You can use the following methods in pandas Group by one or more index columns and perform some calculations .
Method 1: Group by an index column
df.groupby('index1')['numeric_column'].max()
Copy code
Method 2: Group by multiple index columns
df.groupby(['index1', 'index2'])['numeric_column'].sum()
Copy code
Method 3: Group by index column and general column
df.groupby(['index1', 'numeric_column1'])['numeric_column2'].nunique()
Copy code
The following example shows how to use the following multi indicator pandas DataFrame To use each method .
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
'position': ['G', 'G', 'G', 'F', 'F', 'G', 'G', 'F', 'F', 'F'],
'points': [7, 7, 7, 19, 16, 9, 10, 10, 8, 8],
'rebounds': [8, 8, 8, 10, 11, 12, 13, 13, 15, 11]})
#set 'team' column to be index column
df.set_index(['team', 'position'], inplace=True)
#view DataFrame
df
points rebounds
team position
A G 7 8
G 7 8
G 7 8
F 19 10
F 16 11
B G 9 12
G 10 13
F 10 13
F 8 15
F 8 11
Copy code
Method 1: Group by an index column
The following code shows how to find 'points' The maximum value of the column , And pass 'position' Index columns are grouped .
#find max value of 'points' grouped by 'position index column
df.groupby('position')['points'].max()
position
F 19
G 10
Name: points, dtype: int64
Copy code
Method 2: Group by multiple index columns
The following code shows how to pass " The team " and " Location " Index columns to find " integral " The sum of the columns .
#find max value of 'points' grouped by 'position index column
df.groupby(['team', 'position'])['points'].sum()
team position
A F 35
G 21
B F 26
G 19
Name: points, dtype: int64
Copy code
Method 3: Group by index column and general column
The following code shows how to ' rebounds ' The number of unique values found in the column , And through the index column ' The team ' And normal columns ' integral ' grouping .
#find max value of 'points' grouped by 'position index column
df.groupby(['team', 'points'])['rebounds'].nunique()
team points
A 7 1
16 1
19 1
B 8 2
9 1
10 1
Name: rebounds, dtype: int64
Copy code
copyright notice
author[Stone sword],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301152237752.html
The sidebar is recommended
- Python Network Programming -- create a simple UPD socket to realize mutual communication between two processes
- leetcode 110. Balanced Binary Tree(python)
- Django uses Django celery beat to dynamically add scheduled tasks
- The bear child said "you haven't seen Altman" and hurriedly studied it in Python. Unexpectedly
- Optimization iteration of nearest neighbor interpolation and bilinear interpolation algorithm for Python OpenCV image
- Bilinear interpolation algorithm for Python OpenCV image, the most detailed algorithm description in the whole network
- Use of Python partial()
- Python game development, pyGame module, python implementation of angry birds
- leetcode 1104. Path In Zigzag Labelled Binary Tree(python)
- Save time and effort. 10 lines of Python code automatically clean up duplicate files in the computer
guess what you like
-
Learn python, know more meat, and be a "meat expert" in the technical circle. One article is enough
-
[Python data structure series] "stack (sequential stack and chain stack)" -- Explanation of knowledge points + code implementation
-
Datetime module of Python time series
-
Python encrypts and decrypts des to solve the problem of inconsistency with Java results
-
Chapter 1: introduction to Python programming-4 Hello World
-
Summary of Python technical points
-
11.5K Star! An open source Python static type checking Library
-
Chapter 2: Fundamentals of python-1 grammar
-
[Python daily homework] day4: write a function to count the number of occurrences of each number in the incoming list and return the corresponding dictionary.
-
Python uses turtle to express white
Random recommended
- Some people say Python does not support function overloading?
- "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system with Python
- Introduction to Python - CONDA common commands
- Python actual combat | just "4 steps" to get started with web crawler (with benefits)
- Don't know what to eat every day? Python to tell you! Generate recipes and don't worry about what to eat every day!
- Are people who like drinking tea successful? I use Python to make a tea guide! Do you like it?
- I took 100g pictures offline overnight with Python just to prevent the website from disappearing
- Binary operation of Python OpenCV image re learning and image smoothing (convolution processing)
- Analysis of Python event mechanism
- Iterator of Python basic language
- Base64 encryption and decryption in Python
- Chapter 2: Fundamentals of python-2 variable
- Python garbage collection summary
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
- Python draws a spinning windmill with turtle
- Deep understanding of Python features
- A website full of temptations for Python crawler writers, "lovely picture network", look at the name of this website
- Python opencv Canny edge detection knowledge supplement
- Complex learning of Python opencv Sobel operator, ScHARR operator and Laplacian operator
- Python: faker extension package
- Python code reading (Part 44): find the location of qualified elements
- Elegant implementation of Django model field encryption
- 40 Python entry applet
- Pandas comprehensive application
- Chapter 2: Fundamentals of python-3 character string
- Python pyplot draws a parallel histogram, and the x-axis value is displayed in the center of the two histograms
- [Python crawler] detailed explanation of selenium from introduction to actual combat [1]
- Curl to Python self use version
- Python visualization - 3D drawing solutions pyecharts, Matplotlib, openpyxl
- Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
- Using python, opencv obtains and changes pixels, modifies image channels, and trims ROI
- [Python data collection] university ranking data collection
- [Python data collection] stock information collection
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (2)
- Python solves the problem of suspending execution after clicking the mouse in CMD window (fast editing mode is prohibited)
- [Python from introduction to mastery] (II) how to run Python? What are the good development tools (pycharm)
- Python type hints from introduction to practice
- Python notes (IX): basic operation of dictionary
- Python notes (8): basic operations of collections
- Python notes (VII): definition and use of tuples