How to sort pandas dataframe by one column?
Sorting your DataFrame is straightforward with df.sort_values()
. Below is a concise guide on sorting by a single column.
import pandas as pd df = pd.DataFrame({ "Name": ["Alice", "Bob", "Charlie", "David"], "Age": [25, 30, 35, 40], "City": ["New York", "Chicago", "San Francisco", "Seattle"] }) # Sort DataFrame by the 'Age' column in ascending order df_sorted_asc = df.sort_values(by="Age") print(df_sorted_asc) # Sort DataFrame by the 'Age' column in descending order df_sorted_desc = df.sort_values(by="Age", ascending=False) print(df_sorted_desc)
sort_values(by="Age")
sorts the DataFrame in ascending order based on the values in the"Age"
column.ascending=False
reverses the sort order, returning the largest values first.- The default behavior is to return a new DataFrame with the rows re-ordered. If you want to sort in-place, use
df.sort_values(..., inplace=True)
.
Additional Tips
- Sorting by index: If you need to sort by the DataFrame’s index (row labels), use
df.sort_index()
. - Sorting by multiple columns: Pass a list to
by
, for exampledf.sort_values(by=["Age", "Name"])
. - Handling missing values: By default, NaN values are placed at the end of the sorted list, but you can change this with the
na_position
parameter (e.g.,na_position="first"
).
Level Up Your Python & Data Skills
If you want to master more than just sorting—like efficient data manipulation, best coding practices, and advanced features—check out Grokking Python Fundamentals by DesignGurus.io. A strong Python foundation will make any data-processing task in Pandas more intuitive and performant.
With sort_values()
, you can confidently rearrange your DataFrame by any column or set of columns, ensuring your data is properly ordered for analysis, visualization, or exporting.
CONTRIBUTOR
TechGrind