We wish to sort the rows of a data frame by the values of one column.
We wish to sort a data frame in increasing order of the values of one column.
In this example, we wish to sort a data frame df
in ascending order of the values of a column col_1
.
df.sort_values(by='col_1')
Here is how this works:
sort_values()
to the data frame df
.sort_values()
the name of the column we want to sort by which here is col_1
.sort_values()
sorts in ascending order.We wish to sort a data frame in descending order of the values of one column.
In this example, we wish to sort a data frame df
in descending order of the values of a column col_1
.
df = df.sort_values(by="col_1", ascending=False)
Here is how this works:
sort_values()
to the data frame df
.sort_values()
the name of the column we want to sort by which here is col_1
.ascending=False
. The default, as we saw above, is to sort in ascending order; i.e.ascending=True
.Upon sorting a data frame, the rows keep their original row index. In some situations, we want to reset the row index so the rows of the sorted data frame would have an ordered index starting at 0 with the first row and ending at n-1 for the last row (where n is the number of rows in the data frame).
In this example, we wish to sort a data frame df
in ascending order of the values of a column col_1
and wish to have the row index of the resulting sorted data frame be ordered.
df = df.sort_values(by='col_1', ignore_index=True)
Here is how this works:
sort_values()
as described above to sort the data frame df in ascending order of the values of the column col_1
.ignore_index
parameter to True
. The default is ignore_index=False
.