DataFrame.sort() - ( Pandas DataFrame Basics )
Heading h2
Syntax
DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)
Example
import pandas as pd
# creating a sample dataframe
data = {'name': ['John', 'Alice', 'Bob', 'Mary'], 'age': [25, 20, 30, 27], 'salary': [50000, 30000, 70000, 45000]}
df = pd.DataFrame(data)
# sorting the dataframe by age
sorted_df = df.sort_values(by='age')
print(sorted_df)
Output
name age salary
1 Alice 20 30000
0 John 25 50000
3 Mary 27 45000
2 Bob 30 70000
Explanation
DataFrame.sort_values()
is a function in pandas that can be used to sort a dataframe by one or more column(s). It takes in various parameters, such as the column to sort by, the sort order, the sorting algorithm to use, whether to perform the sort operation in place or not, etc.
In the above example, we create a sample dataframe df
and then sort it by the 'age'
column using the sort_values()
function. The resulting dataframe sorted_df
is printed to the console.
Use
DataFrame.sort_values()
is useful in sorting a dataframe by one or more columns. It is an essential tool in data analysis and manipulation, especially when dealing with large datasets.
Important Points
DataFrame.sort_values()
is used to sort a dataframe by one or more columns- It takes in various parameters, such as the column to sort by, the sort order, the sorting algorithm to use, whether to perform the sort operation in place or not, etc.
- By default, it sorts the dataframe in ascending order
- It returns a new sorted dataframe and does not modify the original dataframe (unless specified with the
inplace
parameter)
Summary
In conclusion, DataFrame.sort_values()
is a powerful function in pandas that can be used to sort a dataframe by one or more columns. It is essential in data analysis and manipulation tasks, especially when dealing with large datasets. It takes in various parameters and returns a new sorted dataframe while leaving the original dataframe intact (unless specified with the inplace
parameter).