NaN entries can be replaced in a pandas Series
with a specified value using the fillna
method:
In [x]: ser1 = pd.Series({'b': 2, 'c': -5, 'd': 6.5}, index=list('abcd'))
In [x]: ser1
Out[x]:
a NaN
b 2.0
c -5.0
d 6.5
dtype: float64
In [x]: ser1.fillna(1, inplace=True)
In [x]: ser1
Out[x]:
a 1.0
b 2.0
c -5.0
d 6.5
dtype: float64
Infinities (represented by the floating-point inf
value) can be replaced with the replace
method, which takes a scalar or sequence of values and substitutes them with another, single value:
In [x]: ser2 = pd.Series([-3.4, 0, 0, 1], index=ser1.index)
In [x]: ser2
Out[x]:
a -3.4
b 0.0
c 0.0
d 1.0
dtype: float64
In [x]: ser3 = ser1 / ser2
In [x]: ser3
Out[x]:
a -0.294118
b inf
c -inf
d 6.500000
dtype: float64
In [x]: ser3.replace([np.inf, -np.inf], 0)
Out[x]:
a -0.294118
b 0.000000
c 0.000000
d 6.500000
dtype: float64
(Assuming NumPy has been imported with import numpy as np
.)