The Wayback Machine - https://web.archive.org/web/20241123040633/https://www.geeksforgeeks.org/working-with-missing-data-in-pandas/
Open In App

Working with Missing Data in Pandas

Last Updated : 11 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Missing Data can occur when no information is provided for one or more items or for a whole unit. Missing Data is a very big problem in a real-life scenarios. Missing Data can also refer to as NA(Not Available) values in pandas. In DataFrame sometimes many datasets simply arrive with missing data, either because it exists and was not collected or it never existed. For Example, Suppose different users being surveyed may choose not to share their income, some users may choose not to share the address in this way many datasets went missing.

Pandas - Missing Data

In Pandas missing data is represented by two value:

  • None: None is a Python singleton object that is often used for missing data in Python code.
  • NaN : NaN (an acronym for Not a Number), is a special floating-point value recognized by all systems that use the standard IEEE floating-point representation

Pandas treat None and NaN as essentially interchangeable for indicating missing or null values. To facilitate this convention, there are several useful functions for detecting, removing, and replacing null values in Pandas DataFrame :

In this article we are using CSV file, to download the CSV file used, Click Here.

Checking for missing values using isnull() and notnull()

In order to check missing values in Pandas DataFrame, we use a function isnull() and notnull(). Both function help in checking whether a value is NaN or not. These function can also be used in Pandas Series in order to find null values in a series.

Checking for missing values using isnull()

In order to check null values in Pandas DataFrame, we use isnull() function this function return dataframe of Boolean values which are True for NaN values.

Code #1: 

Python
# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
        'Second Score': [30, 45, 56, np.nan],
        'Third Score':[np.nan, 40, 80, 98]}

# creating a dataframe from list
df = pd.DataFrame(dict)

# using isnull() function  
df.isnull()

Output:

Code #2: 

Python
# importing pandas package 
import pandas as pd 
  
# making data frame from csv file 
data = pd.read_csv("employees.csv") 
  
# creating bool series True for NaN values 
bool_series = pd.isnull(data["Gender"]) 
  
# filtering data 
# displaying data only with Gender = NaN 
data[bool_series] 

Output: As shown in the output image, only the rows having Gender = NULL are displayed.

Checking for missing values using notnull()

In order to check null values in Pandas Dataframe, we use notnull() function this function return dataframe of Boolean values which are False for NaN values.

Code #3: 

Python
# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
        'Second Score': [30, 45, 56, np.nan],
        'Third Score':[np.nan, 40, 80, 98]}

# creating a dataframe using dictionary
df = pd.DataFrame(dict)

# using notnull() function 
df.notnull()

Output:

Code #4:

Python
# importing pandas package 
import pandas as pd 
  
# making data frame from csv file 
data = pd.read_csv("employees.csv") 
  
# creating bool series True for NaN values 
bool_series = pd.notnull(data["Gender"]) 
  
# filtering data 
# displaying data only with Gender = Not NaN 
data[bool_series] 

Output: As shown in the output image, only the rows having Gender = NOT NULL are displayed.

Filling missing values using fillna(), replace() and interpolate()

In order to fill null values in a datasets, we use fillna(), replace() and interpolate() function these function replace NaN values with some value of their own. All these function help in filling a null values in datasets of a DataFrame. Interpolate() function is basically used to fill NA values in the dataframe but it uses various interpolation technique to fill the missing values rather than hard-coding the value.

Code #1: Filling null values with a single value 

Python
# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
        'Second Score': [30, 45, 56, np.nan],
        'Third Score':[np.nan, 40, 80, 98]}

# creating a dataframe from dictionary
df = pd.DataFrame(dict)

# filling missing value using fillna()  
df.fillna(0)

Output:

Code #2: Filling null values with the previous ones 

Python
# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
        'Second Score': [30, 45, 56, np.nan],
        'Third Score':[np.nan, 40, 80, 98]}

# creating a dataframe from dictionary
df = pd.DataFrame(dict)

# filling a missing value with
# previous ones  
df.fillna(method ='pad')

Output:


Code #3:

Filling null value with the next ones 


Python
# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
        'Second Score': [30, 45, 56, np.nan],
        'Third Score':[np.nan, 40, 80, 98]}

# creating a dataframe from dictionary
df = pd.DataFrame(dict)

# filling  null value using fillna() function  
df.fillna(method ='bfill')

Output:

Code #4: Filling null values in CSV File 

Python
# importing pandas package 
import pandas as pd 
  
# making data frame from csv file 
data = pd.read_csv("employees.csv")

# Printing the first 10 to 24 rows of
# the data frame for visualization   
data[10:25]

Output

Now we are going to fill all the null values in Gender column with “No Gender”

Python
# importing pandas package 
import pandas as pd 
  
# making data frame from csv file 
data = pd.read_csv("employees.csv") 

# filling a null values using fillna() 
data["Gender"].fillna("No Gender", inplace = True) 

data

Output:

Code #5: Filling a null values using replace() method 

Python
# importing pandas package 
import pandas as pd 
  
# making data frame from csv file 
data = pd.read_csv("employees.csv")

# Printing the first 10 to 24 rows of
# the data frame for visualization   
data[10:25]

Output:

Now we are going to replace the all Nan value in the data frame with -99 value. 

Python
# importing pandas package 
import pandas as pd 
  
# making data frame from csv file 
data = pd.read_csv("employees.csv") 
  
# will replace  Nan value in dataframe with value -99  
data.replace(to_replace = np.nan, value = -99) 

Output:

  Code #6: Using interpolate() function to fill the missing values using linear method. 

Python
# importing pandas as pd 
import pandas as pd 
  
# Creating the dataframe  
df = pd.DataFrame({"A":[12, 4, 5, None, 1], 
                   "B":[None, 2, 54, 3, None], 
                   "C":[20, 16, None, 3, 8], 
                   "D":[14, 3, None, None, 6]}) 
  
# Print the dataframe 
df 

Output:

Let’s interpolate the missing values using Linear method. Note that Linear method ignore the index and treat the values as equally spaced. 

Python
# to interpolate the missing values 
df.interpolate(method ='linear', limit_direction ='forward')

Output:

As we can see the output, values in the first row could not get filled as the direction of filling of values is forward and there is no previous value which could have been used in interpolation.  

Dropping missing values using dropna()

In order to drop a null values from a dataframe, we used dropna() function this function drop Rows/Columns of datasets with Null values in different ways.

Code #1: Dropping rows with at least 1 null value. 

Python
# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
        'Second Score': [30, np.nan, 45, 56],
        'Third Score':[52, 40, 80, 98],
        'Fourth Score':[np.nan, np.nan, np.nan, 65]}

# creating a dataframe from dictionary
df = pd.DataFrame(dict)
  
df

Output

Now we drop rows with at least one Nan value (Null value) 

Python
# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
        'Second Score': [30, np.nan, 45, 56],
        'Third Score':[52, 40, 80, 98],
        'Fourth Score':[np.nan, np.nan, np.nan, 65]}

# creating a dataframe from dictionary
df = pd.DataFrame(dict)

# using dropna() function  
df.dropna()

Output:

Code #2: Dropping rows if all values in that row are missing. 

Python
# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, np.nan, np.nan, 95],
        'Second Score': [30, np.nan, 45, 56],
        'Third Score':[52, np.nan, 80, 98],
        'Fourth Score':[np.nan, np.nan, np.nan, 65]}

# creating a dataframe from dictionary
df = pd.DataFrame(dict)
  
df

Output

Now we drop a rows whose all data is missing or contain null values(NaN) 

Python
# importing pandas as pd
import pandas as pd

# importing numpy as np
import numpy as np

# dictionary of lists
dict = {'First Score':[100, np.nan, np.nan, 95],
        'Second Score': [30, np.nan, 45, 56],
        'Third Score':[52, np.nan, 80, 98],
        'Fourth Score':[np.nan, np.nan, np.nan, 65]}

df = pd.DataFrame(dict)

# using dropna() function    
df.dropna(how = 'all')

Output:


Code #3:

Dropping columns with at least 1 null value. 


Python
# importing pandas as pd
import pandas as pd
 
# importing numpy as np
import numpy as np
 
# dictionary of lists
dict = {'First Score':[100, np.nan, np.nan, 95],
        'Second Score': [30, np.nan, 45, 56],
        'Third Score':[52, np.nan, 80, 98],
        'Fourth Score':[60, 67, 68, 65]}

# creating a dataframe from dictionary 
df = pd.DataFrame(dict)
   
df

Output

Now we drop a columns which have at least 1 missing values 

Python
# importing pandas as pd
import pandas as pd
 
# importing numpy as np
import numpy as np
 
# dictionary of lists
dict = {'First Score':[100, np.nan, np.nan, 95],
        'Second Score': [30, np.nan, 45, 56],
        'Third Score':[52, np.nan, 80, 98],
        'Fourth Score':[60, 67, 68, 65]}

# creating a dataframe from dictionary  
df = pd.DataFrame(dict)

# using dropna() function     
df.dropna(axis = 1)

Output :

  Code #4: Dropping Rows with at least 1 null value in CSV file 

Python
# importing pandas module 
import pandas as pd 
  
# making data frame from csv file 
data = pd.read_csv("employees.csv") 
  
# making new data frame with dropped NA values 
new_data = data.dropna(axis = 0, how ='any') 
  
new_data

Output:

Now we compare sizes of data frames so that we can come to know how many rows had at least 1 Null value 

Python
print("Old data frame length:", len(data))
print("New data frame length:", len(new_data)) 
print("Number of rows with at least 1 NA value: ", (len(data)-len(new_data)))

Output : 

Old data frame length: 1000
New data frame length: 764
Number of rows with at least 1 NA value: 236

Since the difference is 236, there were 236 rows which had at least 1 Null value in any column.

Working with Missing Data in Pandas – FAQs

How to get rows with missing data in pandas?

To find rows with missing data in any column within a DataFrame, use the isna() method combined with the any() function:

import pandas as pd

# Example DataFrame
df = pd.DataFrame({
'A': [1, 2, None, 4],
'B': ['a', 'b', 'c', None]
})

# Select rows where any column has missing data
rows_with_missing = df[df.isna().any(axis=1)]
print(rows_with_missing)

How to handle missing data in a dataset?

You can handle missing data by several methods depending on your data and the analysis requirements:

  • Remove missing data: Use dropna() to remove rows or columns with missing values.
  • Fill missing data: Use fillna() to fill missing values with a specific value or a calculated statistic like mean or median.
  • Interpolation: For numerical data, use interpolate() to estimate missing values.

How to fill missing values in pandas using mean?

To fill missing numerical values with the mean of the column in pandas, you can use the fillna() method with the mean() of the column:

# Assuming df is your DataFrame
df['A'] = df['A'].fillna(df['A'].mean())
print(df)

What are some methods to handle missing or corrupted data?

Here are some effective methods to handle missing or corrupted data:

  • Imputation: Replace missing values with the mean, median, mode, or another representative value.
  • Using algorithms that support missing values: Some machine learning algorithms can handle missing values natively.
  • Prediction of missing values: Use predictive modeling techniques to estimate missing values based on other data in the dataset.

How to count missing values in pandas?

To count the number of missing values in each column of a DataFrame, use the isna() method followed by the sum() method:

missing_value_count = df.isna().sum()
print(missing_value_count)


Previous Article
Next Article

Similar Reads

What Is the Difference Between Missing at Random and Missing Not at Random Data?
Answer: MAR data depends on observed data, whereas Missing Not at Random (MNAR) data depends on unobserved data, making its absence unrelated to the observed data.In the realm of statistics and data science, understanding the nature of missing data is crucial for accurate analysis and modeling. Missing data can be categorized into three types: Miss
2 min read
Python | Pandas Working With Text Data
Series and Indexes are equipped with a set of string processing methods that make it easy to operate on each element of the array. Perhaps most importantly, these methods exclude missing/NA values automatically. These are accessed via the str attribute and generally, have names matching the equivalent (scalar) built-in string methods. In order to l
8 min read
Challenges of Working with Unstructured Data in Data Engineering
Working with unstructured data in data engineering presents a myriad of challenges that require careful consideration and strategic planning to overcome. In today's data-driven world, unstructured data, which encompasses text, images, videos, and more, constitutes a significant portion of the data generated daily. Effectively managing, processing,
5 min read
Working with database using Pandas
Performing various operations on data saved in SQL might lead to performing very complex queries that are not easy to write. So to make this task easier it is often useful to do the job using pandas which are specially built for data preprocessing and is more simple and user-friendly than SQL. There might be cases when sometimes the data is stored
3 min read
ML | Handle Missing Data with Simple Imputer
SimpleImputer is a scikit-learn class which is helpful in handling the missing data in the predictive model dataset. It replaces the NaN values with a specified placeholder. It is implemented by the use of the SimpleImputer() method which takes the following arguments : missing_values : The missing_values placeholder which has to be imputed. By def
2 min read
Missing data imputation with fancyimpute
In a real world dataset, there will always be some data missing. This mainly associates with how the data was collected. Missing data plays an important role creating a predictive model, because there are algorithms which does not perform very well with missing dataset. Fancyimput fancyimpute is a library for missing data imputation algorithms. Fan
3 min read
Handling Missing Values in Time Series Data
Handling missing values in time series data in R is a crucial step in the data preprocessing phase. Time series data often contains gaps or missing observations due to various reasons such as sensor malfunctions, human errors, or other external factors. In R Programming Language dealing with missing values appropriately is essential to ensure the a
5 min read
Handling Missing Data in Decision Tree Models
Decision trees, a popular and powerful tool in data science and machine learning, are adept at handling both regression and classification tasks. However, their performance can suffer due to missing or incomplete data, which is a frequent challenge in real-world datasets. This article delves into the intricacies of handling missing data in decision
5 min read
How to Handle Missing Data in Logistic Regression?
Logistic regression is a robust statistical method employed to model the likelihood of binary results. Nevertheless, real-world datasets frequently have missing values, presenting obstacles while fitting logistic regression models. Dealing with missing data effectively is essential to prevent skewed estimates and maintain the model's accuracy. In t
9 min read
Full Information Maximum Likelihood for Missing Data in R
Missing data is a common issue in statistical analysis and can lead to biased results if not handled properly. Full Information Maximum Likelihood (FIML) is a robust method for dealing with missing data, particularly when the data is missing at random (MAR). FIML uses all available data to estimate parameters, providing unbiased and efficient estim
6 min read
Handling Missing Data with IterativeImputer in Scikit-learn
Handling missing data is a critical step in data preprocessing for machine learning projects. Missing values can significantly impact the performance of machine learning models if not addressed properly. One effective method for dealing with missing data is multivariate feature imputation using Scikit-learn's IterativeImputer. This article will del
7 min read
Managing Missing Data in Linear Regression
Managing missing data in linear regression or any machine learning model is crucial, to maintain the accuracy and reliability of machine learning models. This article will delve into the methods and techniques for managing missing data in linear regression, highlighting the importance of understanding the context and nature of missing data. In the
7 min read
Using KNNImputer in Scikit-Learn to Handle Missing Data in Python
KNNimputer is a scikit-learn class used to fill out or predict the missing values in a dataset. It is a more useful method that works on the basic approach of the KNN algorithm rather than the naive approach of filling all the values with the mean or the median. In this approach, we specify a distance from the missing values which is also known as
4 min read
Handling Missing Data with KNN Imputer
Missing data is a common issue in data analysis and machine learning, often leading to inaccurate models and biased results. One effective method for addressing this issue is the K-Nearest Neighbors (KNN) imputation technique. This article will delve into the technical aspects of KNN imputation, its implementation, advantages, and limitations. Tabl
6 min read
Pandas Series dt.day_name() Method | Get Day From Date in Pandas
Pandas dt.day_name() method returns the day names of the DateTime Series objects with specified locale. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) resu
2 min read
Pandas Series dt.weekday | Find Day of the Week in Pandas
The dt.weekday attribute returns the day of the week. It is assumed the week starts on Monday, which is denoted by 0, and ends on Sunday which is denoted by 6. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day
2 min read
Pandas Series dt.weekofyear Method | Get Week of Year in Pandas Series
The dt.weekofyear attribute returns a Series containing the week ordinal of the year in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index =
2 min read
Pandas Series dt.dayofyear | Get Day of Year in Pandas
Pandas dt.dayofyear attribute returns the ordinal day of the year in the underlying DateTime data in the given Series object. Example: C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr =
2 min read
Pandas Series dt.minute | Extract Minute from DateTime Series in Pandas
Pandas Series.dt.minute attribute returns a NumPy array containing the minutes of the DateTime in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Pandas Series dt.days_in_month | Get Total Number of Days in Month in Pandas
The Pandas dt.days_in_month attribute returns the total number of days in the month for the given Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) r
2 min read
Pandas Series dt.dayofweek | Get Day of Week from DateTime Series in Pandas
Pandas dt.dayofweek attribute returns the day of the week from the given DateTime Series Object. It is assumed the week starts on Monday, which is denoted by 0, and ends on Sunday which is denoted by 6. Example: C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:
2 min read
Pandas Series dt.freq | Retrieve Frequency of Pandas Time Series
Pandas dt.freq attribute returns the time series frequency applied on the given series object if any, else it returns None. Examples C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_da
2 min read
Pandas Series dt.daysinmonth | Get Number of Days in Month in Pandas Series
The dt.daysinmonth attribute returns the number of days in the month for the given DateTime series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) result
2 min read
Pandas Series dt.normalize() | Normalize Time in Pandas Series
The dt.normalize() method converts times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases when the time does not matter. Length is unaltered. The time zones are unaffected. Example: C/C++ Code import pandas as pd sr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'M',
2 min read
What is Big Data Analytics ? - Definition, Working, Benefits
Big Data Analytics uses advanced analytical methods that can extract important business insights from bulk datasets. Within these datasets lies both structured (organized) and unstructured (unorganized) data. Its applications cover different industries such as healthcare, education, insurance, AI, retail, and manufacturing. This guide will discuss
9 min read
Handling missing values using Sunbird
The Sunbird library is used for feature engineering purposes. In this library, you will get various techniques to handle missing values, outliers, categorical encoding, normalization and standardization, feature selection techniques, etc. Installation:pip install sunbirdHandling Missing Values: Datasets might have missing values, which can cause pr
4 min read
Handling Missing Values with CatBoost
Data is the cornerstone of any analytical or machine-learning endeavor. However, real-world datasets are not perfect yet and they often contain missing values which can lead to error in the training phase of any algorithm. Handling missing values is crucial because they can lead to biased or inaccurate results in data analyses and machine learning
8 min read
How to Find and Count Missing Values in R DataFrame
In this article, we will be discussing how to find and count missing values in the R programming language. Find and Count Missing Values in the R DataFrameGenerally, missing values in the given data are represented with NA. In R programming, the missing values can be determined by is.na() method. This method accepts the data variable as a parameter
4 min read
How to Predict NaN (Missing Values) of a Dataframe Using ARIMA in Python?
Answer: Use ARIMA to model the time series excluding NaNs, then predict the missing values based on the fitted model and insert these predictions back into the original series.Predicting missing values in a time series data using the ARIMA (AutoRegressive Integrated Moving Average) model involves several key steps. ARIMA is a popular method for tim
2 min read
Handling Missing Values with Random Forest
Data imputation is a critical challenge in machine learning, with missing values impacting statistical modelling. Random Forest, an ensemble learning method, is a robust solution for accurate predictions, particularly in healthcare. It can handle classification and regression problems, and it is more nuanced than traditional methods. It can handle
10 min read
three90RightbarBannerImg