You can sort a pandas DataFrame by a specific column using the sort_values method. Here’s an example:
import pandas as pd # create a DataFrame df = pd.DataFrame({'col1': [3, 2, 1], 'col2': ['A', 'B', 'C']}) # sort the DataFrame by column 'col1' in ascending order df.sort_values(by='col1', ascending=True, inplace=True)
After running this code, the DataFrame will be sorted in ascending order by the values in column ‘col1’. If you want to sort in descending order, set ascending=False.
You can also sort by multiple columns. To sort by multiple columns, pass a list of column names to the by parameter. The sorting order for each column can be specified using the ascending parameter, which can be a list of booleans with the same length as the number of columns to sort by.
Here’s an example:
# sort the DataFrame by columns 'col1' and 'col2' in ascending and descending order, respectively df.sort_values(by=['col1', 'col2'], ascending=[True, False], inplace=True)
In this example, the DataFrame is sorted first by the values in column ‘col1’ in ascending order and then by the values in column ‘col2’ in descending order.
1 thought on “How to sort by column in Pandas”