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

Pandas Missing Value Handling

Pandas Missing Value Handling

Real-world data often contains missing values (NaN), and Pandas provides a rich set of functions for handling missing data. This section explains in detail how to use methods such as fillna, dropna, and interpolate.


Representation of missing values

In Pandas, use NaN(Not a Number) represents missing values and comes from the NumPy library.

Example

import

pandas

as

pd

import

numpy

as

np

Create data containing missing values

s

=

pd.

Series

(

[

1

,

2

,

np.

nan

,

4

,

5

]

)

print

(

"Series containing NaN:"

)

print

(

s

)

print

(

f

"Has missing values: {s.isna().any()}"

)

print

(

)

Missing values in a DataFrame

df

=

pd.

DataFrame

(

{

   

"A"

:

[

1

,

2

,

np.

nan

,

4

]

,

   

"B"

:

[

np.

nan

,

2

,

3

,

4

]

,

   

"C"

:

[

1

,

2

,

3

,

np.

nan

]

}

)

print

(

"DataFrame with missing values:"

)

print

(

df

)

print

(

)

Detect missing values

print

(

"Missing value locations:"

)

print

(

df.

isna

(

)

)

print

(

)

Count missing values in each column

print

(

"Missing value count per column:"

)

print

(

df.

isna

(

)

.

sum

(

)

)

In Pandas,NaN、None、pandas.NA are all recognized as missing values. Use isna() or isnull() to detect all of these missing values consistently.


dropna: remove missing values

Drop rows

Example

import

pandas

as

pd

import

numpy

as

np

df

=

pd.

DataFrame

(

{

   

"A"

:

[

1

,

2

,

np.

nan

,

4

]

,

   

"B"

:

[

1

,

np.

nan

,

3

,

4

]

,

   

"C"

:

[

1

,

2

,

3

,

np.

nan

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Drop rows containing missing values (default)

print

(

"Rows with missing values dropped:"

)

print

(

df.

dropna

(

)

)

print

(

)

how='all': drop only when all values are missing

print

(

"Only rows with all values missing are dropped:"

)

print

(

df.

dropna

(

how

=

"all"

)

)

print

(

)

thresh: keep only rows with at least N non-missing values

print

(

"Keep only rows with at least 2 non-missing values:"

)

print

(

df.

dropna

(

thresh

=

2

)

)

Drop columns

Example

import

pandas

as

pd

import

numpy

as

np

df

=

pd.

DataFrame

(

{

   

"A"

:

[

1

,

2

,

np.

nan

,

4

]

,

   

"B"

:

[

np.

nan

,

np.

nan

,

np.

nan

,

np.

nan

]

,

 

All missing

   

"C"

:

[

1

,

2

,

3

,

4

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Drop columns containing missing values

print

(

"Columns with missing values dropped:"

)

print

(

df.

dropna

(

axis

=

1

)

)

print

(

)

how='all': drop columns where all values are missing

print

(

"Columns with all values missing dropped:"

)

print

(

df.

dropna

(

axis

=

1

,

how

=

"all"

)

)


fillna: fill missing values

Fill with a fixed value

Example

import

pandas

as

pd

import

numpy

as

np

df

=

pd.

DataFrame

(

{

   

"A"

:

[

1

,

2

,

np.

nan

,

4

,

5

]

,

   

"B"

:

[

np.

nan

,

2

,

3

,

np.

nan

,

5

]

,

   

"C"

:

[

1

,

2

,

3

,

4

,

np.

nan

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Fill with 0

print

(

"Filled with 0:"

)

print

(

df.

fillna

(

0

)

)

print

(

)

Fill different columns with specified values

print

(

"Different columns filled with different values:"

)

print

(

df.

fillna

(

{

"A"

:

0

,

"B"

:

99

,

"C"

: -

1

}

)

)

print

(

)

Fill with the previous value (forward fill)

print

(

"Forward fill:"

)

print

(

df.

fillna

(

method

=

"ffill"

)

)

print

(

)

Fill with the next value (backward fill)

print

(

"Backward fill:"

)

print

(

df.

fillna

(

method

=

"bfill"

)

)

Fill with statistical values

Example

import

pandas

as

pd

import

numpy

as

np

df

=

pd.

DataFrame

(

{

   

"A"

:

[

1

,

2

,

np.

nan

,

4

,

5

,

6

]

,

   

"B"

:

[

10

,

np.

nan

,

30

,

np.

nan

,

50

,

60

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Fill with the mean

print

(

"Filled with the mean:"

)

print

(

df.

fillna

(

df.

mean

(

)

)

)

print

(

)

Fill with the median

print

(

"Filled with the median:"

)

print

(

df.

fillna

(

df.

median

(

)

)

)

print

(

)

Fill each column separately

print

(

"Column A filled with the mean, column B with 0:"

)

print

(

df.

fillna

(

{

"A"

: df

[

"A"

]

.

mean

(

)

,

"B"

:

0

}

)

)

Forward and backward fills are especially useful for time-series data because they preserve continuity. Which one to choose depends on the business meaning of the data.


interpolate: fill by interpolation

Interpolation is a smarter way to fill, estimating missing values from neighboring data.

Linear interpolation

Example

import

pandas

as

pd

import

numpy

as

np

s

=

pd.

Series

(

[

1

,

2

,

np.

nan

,

4

,

5

,

np.

nan

,

7

]

)

print

(

"Original Series:"

)

print

(

s

)

print

(

)

Linear interpolation (default)

print

(

"Linear interpolation:"

)

print

(

s.

interpolate

(

)

)

print

(

)

Specify an interpolation method

print

(

"Time-weighted interpolation (time series):"

)

s2

=

pd.

Series

(

[

1

,

np.

nan

,

np.

nan

,

4

]

,

index

=

pd.

date_range

(

"2024-01-01"

,

periods

=

4

,

freq

=

"D"

)

)

print

(

s2.

interpolate

(

method

=

"time"

)

)

print

(

)

Fill with nearby values

print

(

"Filled with nearby values:"

)

print

(

s.

interpolate

(

method

=

"nearest"

)

)

DataFrame interpolation

Example

import

pandas

as

pd

import

numpy

as

np

df

=

pd.

DataFrame

(

{

   

"A"

:

[

1

,

2

,

np.

nan

,

4

,

5

]

,

   

"B"

:

[

10

,

np.

nan

,

30

,

40

,

np.

nan

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Interpolate on the original DataFrame

df_interpolated

=

df.

interpolate

(

method

=

"linear"

)

print

(

"After linear interpolation:"

)

print

(

df_interpolated

)

print

(

)

Limit the interpolation range

print

(

"Fill only the first and last of consecutive missing values (at most 1):"

)

print

(

df.

interpolate

(

limit

=

1

)

)


Practical example: handling real data

Example

import

pandas

as

pd

import

numpy

as

np

Simulate realistic business data

np.

random

.

seed

(

42

)

n

=

20

df

=

pd.

DataFrame

(

{

   

"date"

: pd.

date_range

(

"2024-01-01"

,

periods

=

n

)

,

   

"Sales"

: np.

random

.

choice

(

[

100

,

200

,

np.

nan

,

300

,

np.

nan

]

,

n

)

,

   

"customer_count"

: np.

random

.

choice

(

[

10

,

np.

nan

,

20

,

30

]

,

n

)

,

   

"Conversion Rate"

: np.

random

.

choice

(

[

0.05

,

0.1

,

np.

nan

,

0.15

]

,

n

)

}

)

print

(

"Missing values in the original data:"

)

print

(

df.

isna

(

)

.

sum

(

)

)

print

(

)

Handling strategy:

1. Fill sales with the average of neighboring values (business allows fluctuation)

df

[

"Sales"

]

=

df

[

"Sales"

]

.

interpolate

(

)

2. Fill customer count with the mean

df

[

"customer_count"

]

=

df

[

"customer_count"

]

.

fillna

(

df

[

"customer_count"

]

.

mean

(

)

)

3. Fill conversion rate with 0 (meaning no conversion)

df

[

"Conversion Rate"

]

=

df

[

"Conversion Rate"

]

.

fillna

(

0

)

print

(

"Processed data:"

)

print

(

df

)

print

(

)

print

(

"Missing values after processing:"

)

print

(

df.

isna

(

)

.

sum

(

)

)


Common questions

1. Does fillna create a new object or modify in place?

fillna By default it returns a new object; use inplace=True to modify in place.

2. Missing values remain after interpolation

If missing values are at the beginning or end of the series, interpolation cannot fill them and extra handling is needed.

3. Distinguish NaN from empty strings

Empty string "" is not a missing value; you need to use replace("", np.nan) to convert.

Consider the business meaning when choosing a fill method: forward fill suits time-series data, backward fill suits static data, the mean suits numeric data, and interpolation suits continuous data.