JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Pandas DataFrame DataFrame.fillna() function

Author:JIYIK Last Updated:2025/04/30 Views:

The pandas.DataFrame.fillna() function replaces the values DataFrame​​in NaNwith a certain value.


pandas.DataFrame.fillna()grammar

DataFrame.fillna(
    value=None, method=None, axis=None, inplace=False, limit=None, downcast=None
)

parameter

value scalar, dict, Seriesor DataFrame. NaNThe value used to replace
method backfill, bfill, pad, ffillor None. NaNMethods used to fill the value
axis Fill in missing values ​​along rows ( axis=0) or columns ( )axis=1
inplace Boolean. If true True, modify the caller in placeDataFrame
limit Integer. If specified , the maximum number of consecutive values method​​to fill forward/backward . If not specified, the maximum number of values ​​to fill along the axis.NaNmethodNaN
downcast Dictionary. Specifies the data type to be converted

Return Value

If inplaceis , replaces all values ​​of Truewith the given ; otherwise is .valueNaNDataFrameNone


Example code: Use DataFrame.fillna()the method to fill all the values DataFrame​​inNaN

import pandas as pd
import numpy as np

df = pd.DataFrame({'X': [1, 2, 3, np.nan, 3],
                   'Y': [4, np.nan, 8, np.nan, 3]})
print("DataFrame:")
print(df)

filled_df = df.fillna(5)

print("Filled DataFrame:")
print(filled_df)

Output:

DataFrame:
     X    Y
0  1.0  4.0
1  2.0  NaN
2  3.0  8.0
3  NaN  NaN
4  3.0  3.0
Filled DataFrame:
     X    Y
0  1.0  4.0
1  2.0  5.0
2  3.0  8.0
3  5.0  5.0
4  3.0  3.0

It fills all the values ​​in pandas.DataFrame.fillna()with the provided as parameter in the method .5DataFrameNaN

DataFrame.fillna()The average of

We can replace the values ​​in a column with the average of that column NaN.

import pandas as pd
import numpy as np

df = pd.DataFrame({'X': [1, 2, 3, np.nan, 3],
                   'Y': [4, np.nan, 8, np.nan, 3]})
print("DataFrame:")
print(df)

df.fillna(df.mean(),inplace=True)

print("Filled DataFrame:")
print(df)

Output:

DataFrame:
     X    Y
0  1.0  4.0
1  2.0  NaN
2  3.0  8.0
3  NaN  NaN
4  3.0  3.0
Filled DataFrame:
      X    Y
0  1.00  4.0
1  2.00  5.0
2  3.00  8.0
3  2.25  5.0
4  3.00  3.0

It fills the values X​​of column with the average of column, and fills the values ​​of column with the average of column.NaNXYNaNY

Because inplace=True, fillna()after calling the function, the original DataFrameis modified.

DataFrame.fillna()Fill with 0

import pandas as pd
import numpy as np

df = pd.DataFrame({'X': [1, 2, 3, np.nan, 3],
                   'Y': [4, np.nan, 8, np.nan, 3]})
print("DataFrame:")
print(df)

df.fillna(0,inplace=True)

print("Filled DataFrame:")
print(df)

Output:

DataFrame:
     X    Y
0  1.0  4.0
1  2.0  NaN
2  3.0  8.0
3  NaN  NaN
4  3.0  3.0
Filled DataFrame:
     X    Y
0  1.0  4.0
1  2.0  0.0
2  3.0  8.0
3  0.0  0.0
4  3.0  3.0

It 0fills all with NaN.


Example code: DataFrame.fillna()method with parametersmethod

We can also use different "method" parameters DataFrameto fill in NaNthe value.

import pandas as pd
import numpy as np

df = pd.DataFrame({'X': [1, 2, 3, np.nan, 3],
                   'Y': [4, np.nan, 8, np.nan, 3]})
print("DataFrame:")
print(df)

filled_df = df.fillna(method="backfill")

print("Filled DataFrame:")
print(filled_df)

Output:

DataFrame:
     X    Y
0  1.0  4.0
1  2.0  NaN
2  3.0  8.0
3  NaN  NaN
4  3.0  3.0
Filled DataFrame:
     X    Y
0  1.0  4.0
1  2.0  8.0
2  3.0  8.0
3  3.0  3.0
4  3.0  3.0

Set method="backfill"to fill all the values DataFrame​​in NaNto after the value in the same column NaN.

We can also use the bfill, , padand ffillmethods to fill in the value DataFramein NaN.

methodmethod illustrate
backfill/bfill Fill all the values ​​in with NaNthe value after the value in the same columnDataFrameNaN
ffill/pad Fill all values ​​in with NaNthe value preceding the value in the same columnDataFrameNaN

Example code: DataFrame.fillna()Method limitparameters

DataFrame.fillna()The parameter in the method limitlimits NaNthe maximum number of consecutive values ​​that the method will fill.

import pandas as pd
import numpy as np

df = pd.DataFrame({'X': [1, 2,np.nan, 3,3],
                   'Y': [4, np.nan, 8, np.nan, 3]})
print("DataFrame:")
print(df)

filled_df = df.fillna(3,limit=1)

print("Filled DataFrame:")
print(filled_df)

Output:

DataFrame:
     X    Y
0  1.0  4.0
1  2.0  NaN
2  NaN  8.0
3  3.0  NaN
4  3.0  3.0
Filled DataFrame:
     X    Y
0  1.0  4.0
1  2.0  3.0
2  3.0  8.0
3  3.0  NaN
4  3.0  3.0

Here, once NaNthe values ​​in a column are filled, the other values ​​in the same column NaNremain as they are.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Pandas DataFrame DataFrame.query() function

Publish Date:2025/04/30 Views:107 Category:Python

The pandas.DataFrame.query() method filters the rows of the caller DataFrame using the given query expression. pandas.DataFrame.query() grammar DataFrame . query(expr, inplace = False , ** kwargs) parameter expr Filter rows based on query e

Pandas DataFrame DataFrame.min() function

Publish Date:2025/04/30 Views:162 Category:Python

Python Pandas DataFrame.min() function gets the minimum value of the DataFrame object along the specified axis. pandas.DataFrame.min() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = None , ** kwargs) pa

Pandas DataFrame DataFrame.mean() function

Publish Date:2025/04/30 Views:85 Category:Python

Python Pandas DataFrame.mean() function calculates the mean of the values ​​of the DataFrame object over the specified axis. pandas.DataFrame.mean() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = No

Pandas DataFrame DataFrame.isin() function

Publish Date:2025/04/30 Views:133 Category:Python

The pandas.DataFrame.isin(values) function checks whether each element in the caller DataFrame contains values the value specified in the input . pandas.DataFrame.isin(values) grammar DataFrame . isin(values) parameter values iterable - lis

Pandas DataFrame DataFrame.groupby() function

Publish Date:2025/04/30 Views:161 Category:Python

pandas.DataFrame.groupby() takes a DataFrame as input and divides the DataFrame into groups based on a given criterion. We can use groupby() the method to easily process large datasets. pandas.DataFrame.groupby() grammar DataFrame . groupby

How to Apply a Function to a Column in a Pandas Dataframe

Publish Date:2025/04/30 Views:50 Category:Python

In Pandas, you can transform and manipulate columns and DataFrames using methods apply() such as transform() and . The desired transformation is passed to these methods as a function argument. Each method has its own subtle differences and

Finding the installed version of Pandas

Publish Date:2025/04/12 Views:190 Category:Python

Pandas is one of the commonly used Python libraries for data analysis, and Pandas versions need to be updated regularly. Therefore, other Pandas requirements are incompatible. Let's look at ways to determine the Pandas version and dependenc

KeyError in Pandas

Publish Date:2025/04/12 Views:81 Category:Python

This tutorial explores the concept of KeyError in Pandas. What is Pandas KeyError? While working with Pandas, analysts may encounter multiple errors thrown by the code interpreter. These errors are wide ranging and can help us better invest

Grouping and Sorting in Pandas

Publish Date:2025/04/12 Views:90 Category:Python

This tutorial explored the concept of grouping data in a DataFrame and sorting it in Pandas. Grouping and Sorting DataFrame in Pandas As we know, Pandas is an advanced data analysis tool or package extension in Python. Most of the companies

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial