Pandas Data Sorting and Aggregation
Data sorting and aggregation are very common and important operations in data analysis, especially when analyzing large datasets.
Sorting helps us arrange data by specific criteria, while aggregation lets us summarize data and compute various statistics.
Pandas provides powerful sorting and aggregation features that help analysts process data efficiently.
| Operation | Method | Description | Common functions/methods |
|---|---|---|---|
| Sorting | sort_values(by, ascending) |
Sort by the values of a column,ascending Control ascending or descending order |
df.sort_values(by='column') |
| Sorting | sort_index(axis) |
Sort by the index of rows or columns | df.sort_index(axis=0) |
| Group aggregation | groupby(by) |
After grouping by a column, apply aggregation functions | df.groupby('column') |
| Aggregation function | agg() |
Aggregation functions, such as sum()、mean()、count() etc. |
df.groupby('column').agg({'value': 'sum'}) |
| Multiple aggregations | agg([func1, func2]) |
Apply multiple aggregation functions to the same column | df.groupby('column').agg({'value': ['mean', 'sum']}) |
| Sorting after grouping | apply(lambda x: x.sort_values(...)) |
Sort after grouping | df.groupby('column').apply(lambda x: x.sort_values(...)) |
| Pivot tables | pivot_table() |
Create a pivot table to summarize data by rows and columns |
1. Data Sorting (Sorting)
SortingIt refers to arranging data in ascending or descending order by the values of a column. Pandas provides two main methods for sorting:sort_values() and sort_index()。
Sorting methods
sort_values(): sort by the values of columns.sort_index(): sort by the index of rows or columns.
Example
| Operation | Method | Description | Example |
|---|---|---|---|
| Sort by value | df.sort_values(by, ascending) |
According to the specified column (by) sort,ascending Control ascending or descending order, default is ascending |
df.sort_values(by='Age', ascending=False) |
| Sort by index | df.sort_index(axis) |
Sort by the index of rows or columns,axis Control sorting by row or column |
df.sort_index(axis=0) |
sort_values() Example:
Example
import
pandas
as
pd
Sample data
data
=
{
'Name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
]
,
'Age'
:
[
25
,
30
,
35
,
40
]
,
'Salary'
:
[
50000
,
60000
,
70000
,
80000
]
}
df
=
pd.
DataFrame
(
data
)
Sort by the values of the "Age" column in descending order
df_sorted
=
df.
sort_values
(
by
=
'Age'
,
ascending
=
False
)
(
df_sorted
)
Output:
Name Age Salary
3 David 40 80000
2 Charlie 35 70000
1 Bob 30 60000
0 Alice 25 50000
sort_index() Example:
Example
Sort by row index
df_sorted_by_index
=
df.
sort_index
(
axis
=
0
)
(
df_sorted_by_index
)
Output:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 35 70000
3 David 40 80000
2. Data Aggregation (Aggregation)
AggregationIt refers to summarizing data according to certain rules, usually performing operations such as sum, mean, maximum, and minimum on the data of certain columns. Pandas providesgroupby()methods to group the data and then apply different aggregation functions.
Aggregation methods
groupby(): group by certain columns.- Aggregation functions: such as
sum(),mean(),count(),min(),max(),std(), etc.
Example
| Operation | Method | Description | Example |
|---|---|---|---|
| Group by column and aggregate | df.groupby(by).agg() |
By the specified column (by) group,agg() You can pass different aggregation functions to perform various operations |
df.groupby('Department').agg({'Salary': 'mean'}) |
| Application of multiple aggregation functions | df.groupby(by).agg([func1, func2]) |
You can apply multiple aggregation functions to the same column and return multiple aggregation results | df.groupby('Department').agg({'Salary': ['mean', 'sum']}) |
groupby() Example:
Example
import
pandas
as
pd
Sample data
data
=
{
'Department'
:
[
'HR'
,
'Finance'
,
'HR'
,
'IT'
,
'IT'
]
,
'Employee'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
]
,
'Salary'
:
[
50000
,
60000
,
55000
,
70000
,
75000
]
}
df
=
pd.
DataFrame
(
data
)
Group by department and compute the average salary of each department
grouped
=
df.
groupby
(
'Department'
)
[
'Salary'
]
.
mean
(
)
(
grouped
)
Output:
Department
Finance 60000.0
HR 52500.0
IT 72500.0
Name: Salary, dtype: float64
Application of multiple aggregation functions:
Example
Group by department and compute the mean and sum of salaries for each department
grouped_multiple
=
df.
groupby
(
'Department'
)
.
agg
(
{
'Salary'
:
[
'mean'
,
'sum'
]
}
)
(
grouped_multiple
)
Output:
Salary
mean sum
Department
Finance 60000.0 60000
HR 52500.0 105000
IT 72500.0 145000
3. Sorting After Grouping
Aggregated data can be further sorted by the values of a column, so that the most important values in a specific group can be found.
Sorting after grouping
| Operation | Method | Description | Example |
|---|---|---|---|
| Sorting after grouping | df.groupby(by).apply(lambda x: x.sort_values(by='col')) |
Sort by the values of a column within each group. | df.groupby('Department').apply(lambda x: x.sort_values(by='Salary', ascending=False)) |
Example of sorting after grouping:
Example
After grouping by department, sort by salary in descending order
grouped_sorted
=
df.
groupby
(
'Department'
)
.
apply
(
lambda
x: x.
sort_values
(
by
=
'Salary'
,
ascending
=
False
)
)
(
grouped_sorted
)
Output:
Department Employee Salary
Department
Finance Bob 60000
HR Charlie 55000
HR Alice 50000
IT Eve 75000
IT David 70000
4. Pivot Tables
A pivot table is a special aggregation method that lets us quickly summarize data by rows, columns, and aggregation functions, similar to pivot tables in Excel.
Example
| Operation | Method | Description | Example |
|---|---|---|---|
| Create a pivot table | df.pivot_table(values, index, columns, aggfunc) |
Use the specified columns for row and column classification and summarization,values is the value to be aggregated,aggfunc is the aggregation function |
df.pivot_table(values='Salary', index='Department', aggfunc='mean') |
Pivot table example:
Example
Use pivot_table to compute the average salary of each department
pivot_table
=
df.
pivot_table
(
values
=
'Salary'
,
index
=
'Department'
,
aggfunc
=
'mean'
)
(
pivot_table
)
Output:
Department
Finance 60000.0
HR 52500.0
IT 72500.0
Name: Salary, dtype: float64