The Wayback Machine - https://web.archive.org/web/20241006183155/https://www.geeksforgeeks.org/how-to-fill-nan-values-with-mean-in-pandas/
Open In App

How to fill NAN values with mean in Pandas?

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

It is a quite compulsory process to modify the data we have as the computer will show you an error of invalid input as it is quite impossible to process the data having ‘NaN’ with it and it is not quite practically possible to manually change the ‘NaN’ to its mean. Therefore, to resolve this problem we process the data and use various functions by which the ‘NaN’ is removed from our data and is replaced with the particular mean and ready to be processed by the system.

Python Fill NAN Values With Mean in Pandas

Below are the ways by which we can fill NAN values with mean in Pandas in Python:

  • Using Dataframe.fillna() Function
  • Using SimpleImputer from sklearn.impute

Fill NAN Values With Mean in Pandas Using Dataframe.fillna()

With the help of Dataframe.fillna()  from the pandas’ library, we can easily replace the ‘NaN’ in the data frame.

Example 1: Handling Missing Values Using Mean Imputation

In this example, a Pandas DataFrame, ‘gfg,’ is created from a dictionary (‘GFG_dict’) with NaN values in the ‘G2’ column. The code computes the mean of the ‘G2’ column and replaces the NaN values in that column with the calculated mean, resulting in an updated DataFrame.

Python3




import numpy as np
import pandas as pd
  
# A dictionary with list as values
GFG_dict = {'G1': [10, 20, 30, 40],
            'G2': [25, np.NaN, np.NaN, 29],
            'G3': [15, 14, 17, 11],
            'G4': [21, 22, 23, 25]}
  
# Create a DataFrame from dictionary
gfg = pd.DataFrame(GFG_dict)
  
# Finding the mean of the column having NaN
mean_value = gfg['G2'].mean()
  
# Replace NaNs in column S2 with the
# mean of values in the same column
gfg['G2'].fillna(value=mean_value, inplace=True)
print('Updated Dataframe:')
print(gfg)


Output:

Example 2: Filling Mean in NAN Values using Dataframe.fillna()

In this example, a Pandas DataFrame, ‘df,’ is created with missing values in the ‘Sale’ column. The code replaces the NaN values in the ‘Sale’ column with the integer mean of available values, producing an updated DataFrame with filled missing values.

Python3




import pandas as pd
import numpy as np
  
df = pd.DataFrame({
    'ID': [10, np.nan, 20, 30, np.nan, 50, np.nan,
           150, 200, 102, np.nan, 130],
  
    'Sale': [10, 20, np.nan, 11, 90, np.nan,
             55, 14, np.nan, 25, 75, 35],
  
    'Date': ['2020-10-05', '2020-09-10', np.nan,
             '2020-08-17', '2020-09-10', '2020-07-27',
             '2020-09-10', '2020-10-10', '2020-10-10',
             '2020-06-27', '2020-08-17', '2020-04-25'],
})
  
df['Sale'].fillna(int(df['Sale'].mean()), inplace=True)
print(df)


Output:

 

Filling NAN Values With Mean Using SimpleImputer() from sklearn.impute 

This function Imputation transformer for completing missing values which provide basic strategies for imputing missing values. These values can be imputed with a provided constant value or using the statistics (mean, median, or most frequent) of each column in which the missing values are located. This class also allows for different missing value encoding.

Syntax: class sklearn.impute.SimpleImputer(*, missing_values=nan, strategy=’mean’, fill_value=None, verbose=0, copy=True, add_indicator=False)

Parameters:

  • missing_values: int float, str, np.nan or None, default=np.nan
  • strategy string: default=’mean’
  • fill_valuestring or numerical value: default=None
  • verbose: integer, default=0
  • copy: boolean, default=True
  • add_indicator: boolean, default=False

Example 1: Computation on PID column

In this example, a property dataset is loaded from a CSV file using Pandas. The code focuses on a specific column (presumably the first column based on iloc[:, 0]) denoted as ‘X.’ The SimpleImputer from scikit-learn is employed to replace missing values (NaN) in ‘X’ with the mean of the available values, and the updated ‘X’ is printed.

Python3




from sklearn.impute import SimpleImputer
import pandas as pd
import numpy as np
  
Dataset = pd.read_csv("property data.csv")
X = Dataset.iloc[:, 0].values
  
# To calculate mean use imputer class
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(X)
  
X = imputer.transform(X)
print(X)


Output:

Example 2: Computation on ST_NUM Column

In this example, a property dataset is loaded from a CSV file using Pandas. The code focuses on the second column (index 1) denoted as ‘X.’ The SimpleImputer from scikit-learn is employed to replace missing values (NaN) in ‘X’ with the mean of the available values.

Python3




from sklearn.impute import SimpleImputer
import pandas as pd
import numpy as np
  
Dataset = pd.read_csv("property data.csv")
X = Dataset.iloc[:, 1].values
  
# To calculate mean use imputer class
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(X)
X = imputer.transform(X)
print(X)


Output:



Previous Article
Next Article

Similar Reads

Replace infinity with large finite numbers and fill NaN for complex input values using NumPy in Python
In this article, we will cover how to fill Nan for complex input values and infinity values with large finite numbers in Python using NumPy. Example: Input: [complex(np.nan,np.inf)] Output: [1000.+1.79769313e+308j] Explanation: Replace Nan with complex values and infinity values with large finite. numpy.nan_to_num method The numpy.nan_to_num method
3 min read
Python NumPy - Replace NaN with zero and fill positive infinity for complex input values
In this article, we will see how to replace NaN with zero and fill positive infinity for complex input values in Python. Numpy package provides us with the numpy.nan_to_num() method to replace NaN with zero and fill positive infinity for complex input values in Python. This method substitutes a nan value with a number and replaces positive infinity
4 min read
Replace NaN with zero and fill negative infinity values in Python
In this article, we will cover how to replace NaN with zero and fill negative infinity values in Python using NumPy. Example Input: [ nan -inf 5.] Output: [0.00000e+00 9.99999e+05 5.00000e+00] Explanation: Replacing NaN with 0 and negative inf with any value. numpy.nan_to_num method The numpy.nan_to_num method is used to replace Nan values with zer
3 min read
Ways to Create NaN Values in Pandas DataFrame
Let's discuss ways of creating NaN values in the Pandas Dataframe. There are various ways to create NaN values in Pandas dataFrame. Those are: Using NumPy Importing csv file having blank values Applying to_numeric function Method 1: Using NumPy C/C++ Code import pandas as pd import numpy as np num = {'number': [1,2,np.nan,6,7,np.nan,np.nan]} df = p
1 min read
Drop rows from Pandas dataframe with missing values or NaN in columns
Pandas provides various data structures and operations for manipulating numerical data and time series. However, there can be cases where some data might be missing. 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),
4 min read
Count NaN or missing values in Pandas DataFrame
In this article, we will see how to Count NaN or missing values in Pandas DataFrame using isnull() and sum() method of the DataFrame. Dataframe.isnull() method Pandas isnull() function detect missing values in the given object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing
5 min read
How to count the number of NaN values in Pandas?
We might need to count the number of NaN values for each feature in the dataset so that we can decide how to deal with it. For example, if the number of missing values is quite low, then we may choose to drop those observations; or there might be a column where a lot of entries are missing, so we can decide whether to include that variable at all u
4 min read
Replace all the NaN values with Zero's in a column of a Pandas dataframe
Replacing the NaN or the null values in a dataframe can be easily performed using a single line DataFrame.fillna() and DataFrame.replace() method. We will discuss these methods along with an example demonstrating how to use it. DataFrame.fillna(): This method is used to fill null or null values with a specific value. Syntax: DataFrame.fillna(self,
3 min read
Count the NaN values in one or more columns in Pandas DataFrame
Let us see how to count the total number of NaN values in one or more columns in a Pandas DataFrame. In order to count the NaN values in the DataFrame, we are required to assign a dictionary to the DataFrame and that dictionary should contain numpy.nan values which is a NaN(null) value. Consider the following DataFrame. # importing the modules impo
2 min read
Highlight the nan values in Pandas Dataframe
In this article, we will discuss how to highlight the NaN (Not a number) values in Pandas Dataframe. NaN values used to represent NULL values and sometimes it is the result of the mathematical overflow.Lets first make a dataframe: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe d
2 min read
How to Drop Columns with NaN Values in Pandas DataFrame?
Nan(Not a number) is a floating-point value which can't be converted into other data type expect to float. In data analysis, Nan is the unnecessary value which must be removed in order to analyze the data set properly. In this article, we will discuss how to remove/drop columns having Nan values in the pandas Dataframe. We have a function known as
3 min read
How to Drop Rows with NaN Values in Pandas DataFrame?
NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results. In this article, we will
4 min read
Replace NaN Values with Zeros in Pandas DataFrame
NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results.  Methods to Replace NaN V
5 min read
Python | Visualize missing values (NaN) values using Missingno Library
In the case of a real-world dataset, it is very common that some values in the dataset are missing. We represent these missing values as NaN (Not a Number) values. But to build a good machine learning model our dataset should be complete. That's why we use some imputation techniques to replace the NaN values with some probable values. But before do
3 min read
Check for NaN in Pandas DataFrame
NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results. Check for NaN Value in Pa
3 min read
How to Count the NaN Occurrences in a Column in Pandas Dataframe?
The data frame is divided into cells, which can store a value belonging to some data structure as well as it may contain missing or NA values. The pandas package contains various in-built functions, to check if the value in the cell of a data frame is either NA or not, and also to perform aggregations over these NA values. Method #1: Using In-built
2 min read
Pandas – Filling NaN in Categorical data
Real-world data is full of missing values. In order to work on them, we need to impute these missing values and draw meaningful conclusions from them. In this article, we will discuss how to fill NaN values in Categorical Data. In the case of categorical features, we cannot use statistical imputation methods. Let's first create a sample dataset to
2 min read
Replace NaN with Blank or Empty String in Pandas?
In this article, we will discuss how to replace NaN with Blank or Empty string in Pandas. Example: Input: "name": ['suraj', 'NaN', 'harsha', 'NaN'] Output: "name": ['sravan', , 'harsha', ' '] Explanation: Here, we replaced NaN with empty string.Replace NaN with Empty String using replace() We can replace the NaN with an empty string using df.replac
2 min read
Replacing Pandas or Numpy Nan with a None to use with MysqlDB
The widely used relational database management system is known as MysqlDB. The MysqlDB doesn't understand and accept the value of 'Nan', thus there is a need to convert the 'Nan' value coming from Pandas or Numpy to 'None'. In this article, we will see how we can replace Pandas or Numpy 'Nan' with a 'None'. Replacing NaN with None in PandasExample
3 min read
How to remove NaN values from a given NumPy array?
In this article, we are going to learn how to remove Nan values from a given array. Nan values are those values that do not have a specific value associated with them or they are different from the type of values that are to be used in the declared array. There are basically three approaches with slight differences in syntax. Either we could use a
3 min read
NumPy | Replace NaN values with average of columns
Data visualization is one of the most important steps in machine learning and data analytics. Cleaning and arranging data is done by different algorithms. Sometimes in data sets, we get NaN (not a number) values that are unusable for data visualization. To solve this problem, one possible method is to replace NaN values with an average of columns.
5 min read
Check For NaN Values in Python
In data analysis and machine learning, missing or NaN (Not a Number) values can often lead to inaccurate results or errors. Identifying and handling these NaN values is crucial for data preprocessing. Here are five methods to check for NaN values in Python. What are Nan Values In In Python?In Python, NaN stands for "Not a Number". It is a special f
2 min read
Dealing with NaN Values in Boxplot
In data visualization, handling missing data (NaN values) is a common challenge. While boxplots are excellent for visualizing the distribution of a dataset, they are often affected by NaN (Not a Number) values that can distort the representation. Boxplots are invaluable for visualizing data distributions, especially when identifying outliers and un
3 min read
Pandas - GroupBy One Column and Get Mean, Min, and Max values
We can use Groupby function to split dataframe into groups and apply different operations on it. One of them is Aggregation. Aggregation i.e. computing statistical parameters for each group created example - mean, min, max, or sums. Let's have a look at how we can group a dataframe by one column and get their mean, min, and max values. Example 1: i
2 min read
Fill empty column - Pandas
Sometimes the dataframe contains an empty column and may pose a real problem in the real life scenario. 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. In this article, let's see how to fill
2 min read
Mapping external values to dataframe values in Pandas
Mapping external values to a dataframe means using different sets of values to add to that dataframe by keeping the keys of the external dictionary as same as the one column of that dataframe. To add external values to dataframe, we use a dictionary that has keys and values which we want to add to the dataframe. By adding external values in the dat
3 min read
Highlight the negative values red and positive values black in Pandas Dataframe
Let's see various methods to Highlight the positive values red and negative values black in Pandas Dataframe.First, Let's make a Dataframe: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], '
3 min read
Python | cmath.nan Constant
cMath module contains a number of functions which is used for mathematical operations for complex numbers. The cmath.nan Constant is used to get the floating-point nan (Not a Number). Syntax: cmath.nan Returns: Return the floating-point nan value. Below examples illustrate the use of above function: Example #1 : C/C++ Code # Python code to implemen
1 min read
How to randomly insert NaN in a matrix with NumPy in Python ?
Prerequisites: Numpy In this article, let's see how to generate a Python Script that randomly inserts Nan into a matrix using Numpy. Given below are 3 methods to do the same: Method 1: Using ravel() function ravel() function returns contiguous flattened array(1D array with all the input-array elements and with the same type as it). A copy is made o
3 min read
Check if the value is infinity or NaN in Python
In this article, we will check whether the given value is NaN or Infinity. This can be done using the math module. Let's see how to check each value in detail. Check for NaN values in Python NaN Stands for "Not a Number" and it is a numeric datatype used as a proxy for values that are either mathematically undefined or cannot be represented. There
4 min read
Practice Tags :