how to sort pandas dataframe from one column
To sort a Pandas DataFrame based on the values in a column, you can use the sort_values()
method of the DataFrame. This method takes a column name as an argument, and sorts the DataFrame based on the values in that column. By default, the sort_values()
method will sort the values in ascending order.
Here's an example of how to use sort_values()
to sort a DataFrame by the values in the 'Price' column:
import pandas as pd
# Load the data
df = pd.read_csv('data.csv')
# Sort the DataFrame by the 'Price' column
df.sort_values(by='Price')
This will sort the DataFrame in ascending order based on the values in the 'Price' column.
You can also specify the ascending
parameter to control the direction of the sort. Setting ascending=False
will sort the DataFrame in descending order.
For example:
# Sort the DataFrame by the 'Price' column in descending order
df.sort_values(by='Price', ascending=False)
You can also sort the DataFrame by multiple columns by passing a list of column names to the by
parameter.
For example:
# Sort the DataFrame by the 'Price' and 'Quantity' columns
df.sort_values(by=['Price', 'Quantity'])
This will first sort the DataFrame by the 'Price' column in ascending order, and then sort the rows with the same 'Price' value by the 'Quantity' column in ascending order.