In Python, we can use the DataFrame.sort_values() function to sort a DataFrame. In this article, we will discuss how to sort a DataFrame by a column using Python pandas.
We can use the following Python code to sort a DataFrame by a column.
import pandas list1 = [[10, 21, 13, 14], [50, 60, 75, 82], [19, 10, 11, 126], [13, 140, 125, 16]] df1 = pandas.DataFrame(list1, index=["Row 1", "Row 2", "Row 3", "Row 4"], columns=["Column 1", "Column 2", "Column 3", "Column 4"]) print("df1 before sorting: \n", df1) df1.sort_values(by=["Column 2"], ascending=True, inplace=True) print("df1 after sorting by Column 2: \n", df1)
The output of the above program will be:
df1 before sorting: Column 1 Column 2 Column 3 Column 4 Row 1 10 21 13 14 Row 2 50 60 75 82 Row 3 19 10 11 126 Row 4 13 140 125 16 df1 after sorting by Column 2: Column 1 Column 2 Column 3 Column 4 Row 3 19 10 11 126 Row 1 10 21 13 14 Row 2 50 60 75 82 Row 4 13 140 125 16
Here, the “by” parameter in the DataFrame.sort_values() function indicates the label of the column by which the DataFrame should be sorted.
df1.sort_values(by=["Column 2"], ascending=True, inplace=True)
The ascending=True parameter indicates that the soring should be done in ascending order. If we are sorting in descending order, then the ascending parameter should be False.
And the inplace=True parameter indicates that no new DataFrame is created after the sorting. Instead, the existing DataFrame is updated.






0 Comments