Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas df.fillna() function

Pandas df.fillna() function

Pandas Common Functions Common Pandas functions


df.fillna() is a function in Pandas used to fill in missing values.

The difference between dropna() Unlike removing missing values,fillna() allows us to fill missing data with specified values, the mean, the median, forward fill, or backward fill. This is very useful for maintaining data integrity and analytical accuracy.


Basic syntax and parameters

fillna() is a member function of DataFrame, called via the dot operator . to call it.

Syntax format



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

Parameter Description

Parameters Type Required Description Default value
value scalar, dict, Series, DataFrame Optional The value used to fill missing values. It can be a constant, a dictionary (specifying different values for different columns), a Series, or a DataFrame. None
method str Optional The fill method.'ffill' or 'pad' indicates filling with the previous value (forward fill);'bfill' or 'backfill' indicates filling with the next value (backward fill). None
axis int or str Optional Specifies the fill direction.0 or 'index' indicates filling by row;1 or 'columns' indicates filling by column. Only valid when method is not None is set. 0
inplace bool Optional If it is True, modify the original DataFrame directly without returning a new object; if False, a new DataFrame is returned and the original data is unchanged. False
limit int Optional Specifies the maximum number of consecutive fills. For example, setting limit=1 means filling only 1 missing value at a time. None
downcast dict or str Optional Specifies rules for downcasting data types, such as converting float64 to int64. None

Return value description


Example

Let us thoroughly master fillna() through a series of examples from simple to complex.

Example 1: Filling all missing values with a constant

The simplest usage is to fill all missing values with a constant.

Example

import

pandas

as

pd

import

numpy

as

np

Create a DataFrame with missing values

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

]

,

   

'Age'

:

[

25

,

np.

nan

,

35

,

np.

nan

]

,

 

Missing Values

   

'Salary'

:

[

5000

,

6000

,

np.

nan

,

8000

]

,

 

Missing Values

   

'Department'

:

[

'Ji shu' (a Chinese phrase)

,

'Marketing'

,

'Ji shu' (a Chinese phrase)

,

np.

nan

]

 

Missing Values

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Fill all missing values with the constant 0

df_filled

=

df.

fillna

(

0

)

print

(

"Data after filling with 0:"

)

print

(

df_filled

)

Expected output:

原始数据:

    姓名   年龄    薪资  部门

0  张三  25.0  5000.0  技术

1  李四   NaN  6000.0  市场

2  王五  35.0     NaN  技术

3  赵六   NaN  8000.0  NaN

==================================================

Data padded with 0s:

    名称   年龄    薪资  部门

0  张三  25.0  5000.0  技术

1  李四   0.0  6000.0  市场

2  王五  35.0     0.0  技术

3  赵六   0.0  8000.0  0

Code analysis:

  1. We created a DataFrame with multiple missing values.
  2. Use df.fillna(0) Replace all missing values with 0.
  3. This method is simple and direct, but it may not suit all scenarios; for example, filling age and salary with 0 may not be reasonable.

Example 2: Using a dictionary to specify different fill values for different columns

You can specify different fill values for different columns to make the data more reasonable.

Example

import

pandas

as

pd

import

numpy

as

np

Create a DataFrame with missing values

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

]

,

   

'Age'

:

[

25

,

np.

nan

,

35

,

np.

nan

]

,

   

'Salary'

:

[

5000

,

6000

,

np.

nan

,

8000

]

,

   

'Department'

:

[

'Ji shu' (a Chinese phrase)

,

'Marketing'

,

'Ji shu' (a Chinese phrase)

,

np.

nan

]

,

   

'Performance'

:

[

85

,

90

,

np.

nan

,

95

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Use a dictionary to specify different fill values for different columns

fill_values

=

{

   

'Age'

:

30

,

 

Fill missing age with 30

   

'Salary'

:

6500

,

 

Fill missing salary with 6500

   

'Department'

:

'Unassigned'

,

 

Fill missing department with "Unassigned"

   

'Performance'

:

80

 

Fill missing performance with 80

}

df_filled

=

df.

fillna

(

fill_values

)

print

(

"Data after filling different columns with different values:"

)

print

(

df_filled

)

Expected output:

原始数据:

    姓名   年龄    薪资  部门  绩效

0  张三  25.0  5000.0  技术   85

1  李四   NaN  6000.0  市场   90

2  王五  35.0     NaN  技术  NaN

3  赵六   NaN  8000.0  NaN   95

==================================================

Data after filling different columns with different values:

    姓名   年龄    薪资   部门  绩效

0  张三  25.0  5000.0   技术   85

1  李四  30.0  6000.0   市场   90

2  王五  35.0  6500.0   技术   80

3  赵六  30.0  8000.0  未分配   95

Code analysis:

Example 3: Filling numeric columns with the mean or median

For numeric data, filling with the mean or median is a common and reasonable approach.

Example

import

pandas

as

pd

import

numpy

as

np

Create a DataFrame with missing values

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

,

'Qian Qi'

]

,

   

'Math'

:

[

85

,

90

,

np.

nan

,

78

,

92

]

,

   

'English'

:

[

88

,

np.

nan

,

82

,

85

,

90

]

,

   

'Physics'

:

[

np.

nan

,

85

,

90

,

88

,

95

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Compute the mean of each column

math_mean

=

df

[

'Math'

]

.

mean

(

)

english_mean

=

df

[

'English'

]

.

mean

(

)

physics_mean

=

df

[

'Physics'

]

.

mean

(

)

print

(

f

"Math mean: {math_mean:.2f}"

)

print

(

f

"English mean: {english_mean:.2f}"

)

print

(

f

"Physics mean: {physics_mean:.2f}"

)

print

(

"="

50

)

Fill with the mean

df_filled

=

df.

fillna

(

{

   

'Math'

: math_mean

,

   

'English'

: english_mean

,

   

'Physics'

: physics_mean

}

)

print

(

"Data after filling with the mean:"

)

print

(

df_filled

)

Expected output:

原始数据:

    姓名  数学  英语  物理

0  张三  85.0  88.0  NaN

1  李四  90.0  NaN  85.0

2  王五  NaN  82.0  90.0

3  赵六  78.0  85.0  88.0

4  钱七  92.0  90.0  95.0

==================================================

数学均值: 86.25

英语均值: 86.25

物理均值: 89.50

==================================================

Data filled with the mean:

    姓名   数学   英语   物理

0  张三  85.0  88.0  89.5

1  李四  90.0  86.25  85.0

2  王五  86.25  82.0  90.0

3  赵六  78.0  85.0  88.0

4  钱七  92.0  90.0  95.0

Code analysis:

Example 4: Using forward fill (ffill) and backward fill (bfill)

Forward fill uses the previous valid value to fill missing values, while backward fill uses the next valid value.

Example

import

pandas

as

pd

import

numpy

as

np

Create a DataFrame with missing values

data

=

{

   

'Date'

:

[

'2024-01-01'

,

'2024-01-02'

,

'2024-01-03'

,

'2024-01-04'

,

'2024-01-05'

]

,

   

'Temperature'

:

[

20

,

np.

nan

,

22

,

np.

nan

,

25

]

,

   

'Humidity'

:

[

60

,

65

,

np.

nan

,

70

,

75

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Forward fill: fill missing values with the previous value

df_ffill

=

df.

fillna

(

method

=

'ffill'

)

print

(

"Data after forward fill (ffill):"

)

print

(

df_ffill

)

print

(

"="

50

)

Backward fill: fill missing values with the next value

df_bfill

=

df.

fillna

(

method

=

'bfill'

)

print

(

"Data after backward fill (bfill):"

)

print

(

df_bfill

)

Expected output:

原始数据:

        日期   温度   湿度

0  2024-01-01  20.0  60.0

1  2024-01-02  NaN  65.0

2  2024-01-03  22.0  NaN

3  2024-01-04  NaN  70.0

4  2024-01-05  25.0  75.0

==================================================

Data after forward fill (ffill):

        日期   温度   湿度

0  2024-01-01  20.0  60.0

1  2024-01-02  20.0  65.0  # 用前一个值20填充

2  2024-01-03  22.0  65.0  # 用前一个值65填充

3  2024-01-04  22.0  70.0  # 用前一个值22填充

4  2024-01-05  25.0  75.0

==================================================

Data after backfilling (bfill):

        日期   温度   湿度

0  2024-01-01  20.0  60.0

1  2024-01-02  22.0  65.0  # 用后一个值22填充

2  2024-01-03  22.0  70.0  # 用后一个值70填充

填充

3  2024-01-04  25.0  70.0  # 用后一个值25填充

4  2024-01-05  25.0  75.0

Code analysis:

Example 5: Using the limit parameter to restrict the number of fills

limit The parameter can restrict the maximum number of consecutive fills.

Example

import

pandas

as

pd

import

numpy

as

np

Create a DataFrame with multiple consecutive missing values

data

=

{

   

'A'

:

[

1

,

np.

nan

,

np.

nan

,

np.

nan

,

5

]

,

   

'B'

:

[

1

,

2

,

np.

nan

,

np.

nan

,

5

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Forward fill, but limit to filling only 1 consecutive missing value at a time

df_filled

=

df.

fillna

(

method

=

'ffill'

,

limit

=

1

)

print

(

"Data after limiting consecutive fills to 1:"

)

print

(

df_filled

)

Expected output:

原始数据:

     A    B

0  1.0  1.0

1  NaN  2.0

2  NaN  NaN

3  NaN  NaN

4  5.0  5.0

==================================================

Data after limiting continuous fill count to 1:

     A    B

0  1.0  1.0

1  1.0  2.0  # 填充1个

2  NaN  2.0  # 达到limit,不再填充

3  NaN  NaN  # 继续不填充

4  5.0  5.0

Code analysis:

Example 6: Filling missing values with interpolation

Pandas also provides the interpolate() method for interpolation, which suits numeric data.

Example

import

pandas

as

pd

import

numpy

as

np

Create a DataFrame with missing values

data

=

{

   

'x'

:

[

1

,

2

,

3

,

4

,

5

]

,

   

'y'

:

[

10

,

np.

nan

,

30

,

np.

nan

,

50

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"="

50

)

Fill using linear interpolation

df_interpolated

=

df.

copy

(

)

df_interpolated

[

'y'

]

=

df_interpolated

[

'y'

]

.

interpolate

(

method

=

'linear'

)

print

(

"Data after linear interpolation:"

)

print

(

df_interpolated

)

Expected output:

原始数据:

   x   y

0  1  10.0

1  2  NaN

2  3  30.0

3  4  NaN

4  5  50.0

==================================================

Data after linear interpolation filling:

   x   y

0  1  10.0

1  2  20.0  # 插值:10 + (30-10)/(3-1)*(2-1) = 20

2  3  30.0

3  4  40.0  # 插值:30 + (50-30)/(5-3)*(4-3) = 40

4  5  50.0

Code analysis:


Notes


Pandas Common Functions Common Pandas functions