Coding Ref

How to sort by two columns in Pandas

How to sort by two columns in Pandas

To sort a Pandas DataFrame by two columns, you can use the sort_values method. This method takes a list of column names as an argument, and sorts the DataFrame by the values in those columns.

For example, consider the following DataFrame:

main.pys
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

This DataFrame has three columns A, B, and C, with five rows of data.

To sort the DataFrame by the values in columns B and C, you could do the following:

main.py
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

# Sort the DataFrame by columns B and C
sorted_df = df.sort_values(by=['B', 'C'])

# Print the resulting DataFrame
print(sorted_df)

In the code above, the sort_values method is applied to the DataFrame, and the by argument is used to specify the columns that should be used for sorting. This sorts the DataFrame by the values in columns B and C.

In this case, the resulting DataFrame has the following values:

output
   A   B    C
0  1  10  100
1  2  20  200
2  3  30  300
3  4  40  400
4  5  50  500
By default, `sort_values` will sort in ascending, small to large, order. To sort in descending order, from large to small, set `ascending=False`.

Sort in descending order

You can also use the sort_values method to sort the DataFrame in descending order. To do this, you can use the ascending argument and set it to False, as shown in the following example:

main.py
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

# Sort the DataFrame by columns B and C in descending order
sorted_df = df.sort_values(by=['B', 'C'], ascending=False)

# Print the resulting DataFrame
print(sorted_df)

In the code above, the sort_values method is applied to the DataFrame, and the by and ascending arguments are used to specify the columns and the order in which they should be sorted.

This sorts the DataFrame by the values in columns B and C, in descending order.

In this case, the resulting DataFrame has the following values:

output
   A   B    C
4  5  50  500
3  4  40  400
2  3  30  300
1  2  20  200
0  1  10  100

You'll also like

Related tutorials curated for you

    How to use intertuples() in Pandas

    How to use ffill() in Pandas

    How to use where() in Pandas

    How to print a specific row in a Pandas DataFrame?

    Pandas read SQL

    How to get the first row in Pandas

    How to make a crosstab in Pandas

    How to groupby, then sort within groups in Pandas

    How to use str.split() in Pandas

    How to GroupBy Index in Pandas

    How to split a Pandas DataFrame by a column value

    How to reset index in a Pandas DataFrame