JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Pandas DataFrame DataFrame.sort_values() function

Author:JIYIK Last Updated:2025/05/01 Views:

Pandas DataFrame.sort_values() method sorts DataFramethe values ​​in the specified column of the caller along any index in ascending or descending order.


pandas.DataFrame.sort_values()grammar

DataFrame.sort_values(
    by,
    axis=0,
    ascending=True,
    inplace=False,
    kind="quicksort",
    na_position="last",
    ignore_index=False,
)

parameter

by The name or list of names to sort
axis Sort along rows ( axis=0) or columns ( )axis=1
ascending Sort in ascending order ( ascending=True) or descending order ( ascending=False)
inplace Boolean. If true True, modify the caller in placeDataFrame
kind The sorting algorithm. Defaults toquicksort
na_position Put NaNthe value at the beginning ( na_position= first) or end ( na_position= last)
ignore_index Boolean. If yes True, ignore DataFramethe index in the original . The default value is yes False, which means use the index. The default value is yes False, which means use the index. New in version 1.0.0

Return Value

If inplaceis True, return the sorted DataFrame; otherwise is None.


Example Code: Sorting a DataFrame Using Pandas pandas.DataFrame.sort_values()Sorting Based on a Single Column

import pandas as pd

dates=['April-10', 
       'April-11', 
       'April-12', 
       'April-13',
       'April-14',
       'April-16']
sales=[200,300,400,200,300,300]
prices=[3, 1, 2, 4,3,2]

df = pd.DataFrame({'Date':dates ,
                   'Sales':sales ,
                   'Price': prices})
print("Before Sorting:")
print(df)
sorted_df=df.sort_values(by=['Price'])
print("After Sorting:")
print(sorted_df)

Output:

Before Sorting:
       Date  Sales  Price
0  April-10    200      3
1  April-11    300      1
2  April-12    400      2
3  April-13    200      4
4  April-14    300      3
5  April-16    300      2
After Sorting:
       Date  Sales  Price
       Date  Sales  Price
1  April-11    300      1
2  April-12    400      2
5  April-16    300      2
0  April-10    200      3
4  April-14    300      3
3  April-13    200      4

It sorts Pricethe DataFrame in ascending order (default) based on the values ​​in the column .df

The index in the sorted DataFrame remains the same as the index in the original DataFrame.

DataFrameIf you prefer to use the new index column in the sorted , you can set it ignore_index(introduced in version 1.0.0) to True.

import pandas as pd

dates = ["April-10", "April-11", "April-12", "April-13", "April-14", "April-16"]
sales = [200, 300, 400, 200, 300, 300]
prices = [3, 1, 2, 4, 3, 2]

df = pd.DataFrame({"Date": dates, "Sales": sales, "Price": prices})
print("Before Sorting:")
print(df)
sorted_df = df.sort_values(by=["Price"], ignore_index=True)
print("After Sorting:")

Output:

Before Sorting:
       Date  Sales  Price
0  April-10    200      3
1  April-11    300      1
2  April-12    400      2
3  April-13    200      4
4  April-14    300      3
5  April-16    300      2
After Sorting:
       Date  Sales  Price
0  April-11    300      1
1  April-12    400      2
2  April-16    300      2
3  April-10    200      3
4  April-14    300      3
5  April-13    200      4

Here, we use ignore_index=Trueto assign new indices to the rows and ignore DataFramethe original indices.


Example Code: DataFrame.sort_values()Sort DataFrame Based on Multiple Columns Using Pandas

import pandas as pd

dates=['April-10', 
       'April-11', 
       'April-12', 
       'April-13',
       'April-14',
       'April-16']
sales=[200,300,400,200,300,300]
prices=[3, 1, 2, 4,3,2]

df = pd.DataFrame({'Date':dates ,
                   'Sales':sales ,
                   'Price': prices})
print("Before Sorting:")
print(df)
df.sort_values(by=['Sales','Price'],
               ignore_index=True,
               inplace=True)
print("After Sorting:")
print(df)

Output:

Before Sorting:
       Date  Sales  Price
0  April-10    200      3
1  April-11    300      1
2  April-12    400      2
3  April-13    200      4
4  April-14    300      3
5  April-16    300      2
After Sorting:
       Date  Sales  Price
0  April-10    200      3
1  April-13    200      4
2  April-11    300      1
3  April-16    300      2
4  April-14    300      3
5  April-12    400      2

Here, first Salessort is in ascending order, and then for each Sales, Pricethe is also sorted in ascending order.

In df, 200is Salesthe minimum value of the column, and 3is the minimum value of the column whose Salesvalue is .200Price

So, the rows Saleswith in columns 200and Pricein columns are at the front.3

Because inplace=True, after calling sort_values()the function, the original DataFrameis modified in place.


Example Code: DataFrame.sort_values()Sort DataFrame in Descending Order using Pandas

import pandas as pd

dates=['April-10', 
       'April-11', 
       'April-12', 
       'April-13',
       'April-14',
       'April-16']
sales=[200,300,400,200,300,300]
prices=[3, 1, 2, 4,3,2]

df = pd.DataFrame({'Date':dates ,
                   'Sales':sales ,
                   'Price': prices})
print("Before Sorting:")
print(df)
sorted_df=df.sort_values(by=['Sales'],
                         ignore_index=True,
                         ascending=False)
print("After Sorting:")
print(sorted_df)

Output:


Before Sorting:
       Date  Sales  Price
0  April-10    200      3
1  April-11    300      1
2  April-12    400      2
3  April-13    200      4
4  April-14    300      3
5  April-16    300      2
After Sorting:
       Date  Sales  Price
0  April-12    400      2
1  April-11    300      1
2  April-14    300      3
3  April-16    300      2
4  April-10    200      3
5  April-13    200      4

It sorts Salesthe DataFrame in descending order based on the numerical value of the column .df

400is Salesthe maximum value in the column, so that entry will be placed at the top and the other rows will be sorted accordingly.


Example Code: DataFrame.sort_values()Sort DataFrame using Pandas, NaNputting

import pandas as pd

dates=['April-10', 
       'April-11', 
       'April-12', 
       'April-13',
       'April-14',
       'April-16']
sales=[200,300,400,200,300,300]
prices=[3, 1, 2, 4,3,2]

df = pd.DataFrame({'Date':dates ,
                   'Sales':sales ,
                   'Price': prices})
print("Before Sorting:")
print(df)
sorted_df=df.sort_values(by=['Price'],ignore_index=True,na_position='first')
print("After Sorting:")
print(sorted_df)

Output:

Before Sorting:
       Date  Sales  Price
0  April-10    200    NaN
1  April-11    300    1.0
2  April-12    400    2.0
3  April-13    200    4.0
4  April-14    300    3.0
5  April-16    300    NaN
After Sorting:
       Date  Sales  Price
0  April-10    200    NaN
1  April-16    300    NaN
2  April-11    300    1.0
3  April-12    400    2.0
4  April-14    300    3.0
5  April-13    200    4.0

By default, values ​​are placed last NaNafter sorting .DataFrame

But by setting na_position=first, we can NaNput the value DataFrameat the beginning of .

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Convert Pandas to CSV without index

Publish Date:2025/05/01 Views:159 Category:Python

As you know, an index can be thought of as a reference point used to store and access records in a DataFrame. They are unique for each row and usually range from 0 to the last row of the DataFrame, but we can also have serial numbers, dates

Convert Pandas DataFrame to Dictionary

Publish Date:2025/05/01 Views:197 Category:Python

This tutorial will show you how to convert a Pandas DataFrame into a dictionary with the index column elements as keys and the corresponding elements of other columns as values. We will use the following DataFrame in the article. import pan

Convert Pandas DataFrame columns to lists

Publish Date:2025/05/01 Views:191 Category:Python

When working with Pandas DataFrames in Python, you often need to convert the columns of the DataFrame into Python lists. This process is very important for various data manipulation and analysis tasks. Fortunately, Pandas provides several m

Subtracting Two Columns in Pandas DataFrame

Publish Date:2025/05/01 Views:120 Category:Python

Pandas can handle very large data sets and has a variety of functions and operations that can be applied to the data. One of the simple operations is to subtract two columns and store the result in a new column, which we will discuss in thi

Dropping columns by index in Pandas DataFrame

Publish Date:2025/05/01 Views:99 Category:Python

DataFrames can be very large and can contain hundreds of rows and columns. It is necessary to master the basic maintenance operations of DataFrames, such as deleting multiple columns. We can use dataframe.drop() the method to delete columns

Pandas Copy DataFrame

Publish Date:2025/05/01 Views:53 Category:Python

This tutorial will show you how to DataFrame.copy() copy a DataFrame object using the copy method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 ], "Cost" : [ "300" , "400" , "350" ], } ) print (items_df) Output:

Pandas DataFrame.ix[] Function

Publish Date:2025/05/01 Views:168 Category:Python

Python Pandas DataFrame.ix[] function slices rows or columns based on the value of the argument. pandas.DataFrame.ix[] grammar DataFrame . ix[index = None , label = None ] parameter index Integer or list of integers used to slice row indice

Pandas DataFrame.describe() Function

Publish Date:2025/05/01 Views:120 Category:Python

Python Pandas DataFrame.describe() function returns the statistics of a DataFrame. pandas.DataFrame.describe() grammar DataFrame . describe( percentiles = None , include = None , exclude = None , datetime_is_numeric = False ) parameter perc

Pandas DataFrame.astype() Function

Publish Date:2025/05/01 Views:160 Category:Python

Python Pandas DataFrame.astype() function changes the data type of an object to the specified data type. pandas.DataFrame.astype() grammar DataFrame . astype(dtype, copy = True , errors = "raise" ) parameter dtype The data type we want to a

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial