How to sort pandas dataframe based on a column and put missing values first?

Python provides various modules and function to sort Dataframe. Sort_values in Pandas helps in sorting Pandas Dataframe. One key challenge with sorting is presence of missing or NA values. Na values are grouped into one category and placed in the bottom of the Dataframe. In case the size of Dataframe is huge, one cannot know if the variable has NA values present while printing top rows of the file. We will discuss step by step guide on How to sort pandas dataframe based on a column and put missing values first?

Amy has employee data available with her for her company. She is looking to sort the dataset by Gender column. During sorting she wants to keep all the missing Gender rows at the top.

Sort data with missing value first

Below are the key steps Amy has to follow:

  • Step 1: Import all the necessary modules in Python.
import pandas as pd
  • Step 2: Use sort_values function to sort Dataframe with changed na_position. na_position is by default set to ‘last’. Therefore by default NA values comes in the last of the Dataframe. To change this default behaviour, we will update the syntax as below.
Employee_Data2=Employee_Data.sort_values(['gender'],na_position='first')
  • Step 3: Check the quality of output data. Use Dataframe.head to look top rows in the Dataframe.
Employee_Data2.head(20)
Sort Dataframe with Missing first

Thus, Amy is able to create single Dataframe as per her requirement in Python. How to sort pandas dataframe based on a column and put missing values first is no more a challenge for her.

To get top certifications in Python and build your resume visit here. Also, you can read books listed here to build strong knowledge around Python.

Visit us below for video tutorial:

 Looking to practice more with this example? Drop us a note, we will email you the Code file: 

    📬 Stay Ahead in Data Science & AI – Subscribe to Newsletter!

    • 🎯 Interview Series: Curated questions and answers for freshers and experienced candidates.
    • 📊 Data Science for All: Simplified articles on key concepts, accessible to all levels.
    • 🤖 Generative AI for All: Easy explanations on Generative AI trends transforming industries.

    💡 Why Subscribe? Gain expert insights, stay ahead of trends, and prepare with confidence for your next interview.

    👉 Subscribe here:

    Related Posts