How to remove NaN from a Pandas Series?

PandasServer Side ProgrammingProgramming

In the pandas series constructor, the method called dropna() is used to remove missing values from a series object. And it does not update the original series object with removed NaN values instead of updating the original series object, it will return another series object with updated values.

The parameters of the dropna() method are axis, inplace, and how.

Example 1

# importing packages
import pandas as pd
import numpy as np

# Creating Series objects
sr = pd.Series([42, np.nan, 55, 42, np.nan, 73, np.nan, 55, 76, 87], index=list("ABCDEFGHIJ"))

print('Series object:',sr)

# Remove missing elements
result = sr.dropna()

# display output
print(result)

Explanation

Initially, we have created a pandas Series with labeled index values and there are some Nan values present in the series object. After creating a pandas series object we have applied the dropna() method to remove missing values.

Output

Series object:
A 42.0
B  NaN
C 55.0
D 42.0
E  NaN
F 73.0
G  NaN
H 55.0
I 76.0
J 87.0
dtype: float64

A 42.0
C 55.0
D 42.0
F 73.0
H 55.0
I 76.0
J 87.0
dtype: float64

In the above output block, we can see both initial and resultant series objects. The second series object is the output object with removed missing values.

Example 2

# importing packages
import pandas as pd
import numpy as np

dates = pd.date_range('2021-06-01', periods=10, freq='D')

#creating pandas Series with date index
sr = pd.Series([np.nan, 61, 72, 11, np.nan, 24, 56, 30, np.nan, 55], index=dates)

print('Series object:',sr)

# Remove missing elements
result = sr.dropna()

# display output
print(result)

Explanation

In the following example, we have created a pandas Series with date range index values and there are some Nan values present in the series object “sr”. After creating a pandas series object we applied the dropna() method to remove those Nan values.

Output

Series object:
2021-06-01  NaN
2021-06-02 61.0
2021-06-03 72.0
2021-06-04 11.0
2021-06-05  NaN
2021-06-06 24.0
2021-06-07 56.0
2021-06-08 30.0
2021-06-09  NaN
2021-06-10 55.0
Freq: D, dtype: float64

2021-06-02 61.0
2021-06-03 72.0
2021-06-04 11.0
2021-06-06 24.0
2021-06-07 56.0
2021-06-08 30.0
2021-06-10 55.0
dtype: float64

Here we got a new series object with removed Nan values. In the above output block, we can see both initial and resultant series objects. The first object is the initial series, and the second one is the output of the dropna() method.

raja
Updated on 09-Mar-2022 09:46:51

Advertisements