SoFunction
Updated on 2024-11-13

Python Data Analysis Pandas Dataframe Sorting Operations

Preface:

Data sorting is a common operation, DataFrame sorting is divided into two kinds, one is to sort the index, the other is to sort the values, the next are introduced.

1. Index sorting

DataFrame providessort_index()method to sort the index byaxisThe parameter specifies whether to sort by row index or by column index, the default is 0 for sorting by row index and 1 for sorting by column index;ascendingparameter specifies ascending or descending order, the default is True for ascending order and False for descending order.

The specific use is as follows:

Performs a descending sort on the row index:

sort_df = df.sort_index(ascending=False)
sort_df

Sorts column indexes in ascending order:

sort_df = df.sort_index(axis=1)
sort_df

2. Ordering of values

DataFrame providessort_values()method to sort values, compared to thesort_index()method, which has an extrabyparameter, receive a string or list, to specify the name of the row or column to be sorted, the rest is basically the same, the specific use of the following:

Sort by age in ascending order.

sort_df = df.sort_values(by="age")
sort_df

Sort by the value of age in ascending order, then by the value of gender in descending order:

sort_df = df.sort_values(by=["age", "gender"], ascending=[True, False])
sort_df

The resultant output is as follows:

After sorting, if you want to tweak the row indexes a bit, you can use the following to reset the row indexes.

frame.reset_index(drop=True)

Setting parametersdrop=Truemeans to delete the original index, if you don't want to delete the original index, just add another index column, you can not set.Below:

To this article on Python data analysis Pandas Dataframe sorting operation is introduced to this article, more related Pandas Dataframe sorting operation content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!