How do I replace inf with 100?… here is a solution to the problem.
How do I replace inf with 100?
In my dataset, I have a column that contains inf
. I tried replacing it with 100, but I got the error TypeError: Cannot compare types 'ndarray(dtype=float64)' and 'str'
. All other values in this column are numeric.
How do I replace inf
with 100?
fresult.col1.replace(to_replace=dict(inf='100'), inplace=True)
Solution
You can use >replace Via np.inf
:
fresult = pd. DataFrame({'col1': [1, np.inf]})
print (fresult)
col1
0 1.000000
1 inf
fresult.col1 = fresult.col1.replace(np.inf, 100)
print (fresult)
col1
0 1.0
1 100.0
If some values cannot be converted< a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="noreferrer noopener nofollow"> to_numeric
add parameters errors='coerce'
– replace it with NaN
.
fresult = pd. DataFrame({'col1': [1, np.inf, 'a', 'inf']})
print (fresult)
col1
0 1
1 inf <- numpy.inf
2 a
3 inf <-text inf
fresult.col1 = pd.to_numeric(fresult.col1, errors='coerce').replace(np.inf, 100)
print (fresult)
col1
0 1.0
1 100.0
2 NaN
3 100.0
If there is only text inf
:
fresult = pd. DataFrame({'col1': [1, np.inf, 'inf']})
print (fresult)
col1
0 1
1 inf
2 inf
print (type(fresult.col1.iat[1]))
<class 'float'>
print (type(fresult.col1.iat[2]))
<class 'str'>
fresult.col1 = pd.to_numeric(fresult.col1).replace(np.inf, 100)
print (fresult)
col1
0 1.0
1 100.0
2 100.0