How to sort a Pandas DataFrame by column?
Published on Aug. 22, 2023, 12:18 p.m.
To sort a Pandas DataFrame by column, you can use the sort_values()
method. This method returns a new sorted DataFrame and does not modify the original DataFrame. Here is an example:
import pandas as pd
df = pd.DataFrame({'col1': [3, 2, 1], 'col2': ['c', 'b', 'a'], 'col3': [9, 8, 7]})
sorted_df = df.sort_values(by=['col1']) # Sort by column 1 in ascending order
print(sorted_df)
Output:
col1 col2 col3
2 1 a 7
1 2 b 8
0 3 c 9
In the sort_values()
method, the by
parameter specifies the name(s) of the column(s) to sort by, and the ascending
parameter specifies whether to sort in ascending or descending order. By default, ascending
is set to True
, so the DataFrame is sorted in ascending order in the example above.
You can also sort by multiple columns by passing a list of column names to the by
parameter:
sorted_df = df.sort_values(by=['col1', 'col2']) # Sort by column 1 in ascending order and then by column 2 in ascending order
Both of these examples show how to sort a Pandas DataFrame by column.