I want to replace the -inf values in a pandas.series feature (column of my dataframe) to np.nan, but I could not make it.
I have tried:
df[feature] = df[feature].replace(-np.infty, np.nan)
df[feature] = df[feature].replace(-np.inf, np.nan)
df[feature] = df[feature].replace('-inf', np.nan)
df[feature] = df[feature].replace(float('-inf'), np.nan)
But it does not work. Any ideas how to replace these values?
Edit:
df[feature] = df[feature].replace(-np.inf, np.nan)
works
BUT:
df = df.replace(-np.inf, np.nan)
does not work.
How to replace NaN values in a pandas dataframe ? To replace all NaN values in a dataframe, a solution is to use the function fillna (), illustration Example of how to replace NaN values for a given column ('Gender here')
In the context of our example, here is the complete Python code to replace the NaN values with 0’s: Run the code, and you’ll see that the previous two NaN values became 0’s: You can accomplish the same task, of replacing the NaN values with zeros, by using NumPy:
Pandas Series.replace () function is used to replace values given in to_replace with value. The values of the Series are replaced with other values dynamically. Syntax: Series.replace (to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’) to_replace : How to find the values that will be replaced.
Feature scaling is an important preprocessing step in machine learning that can help increase accuracy and training speed. Naive Bayes is a simple but powerful machine learning model that is often used for classification tasks. To replace values with NaN, use the DataFrame's replace (~) method.
it should work:
df.replace([np.inf, -np.inf], np.nan,inplace=True)
The problem may be that you are not assigning back to the original series.
Note that pd.Series.replace
is not an in-place operation by default. The below code is a minimal example.
df = pd.DataFrame({'feature': [1, 2, -np.inf, 3, 4]})
df['feature'] = df['feature'].replace(-np.inf, np.nan)
print(df)
# feature
# 0 1.0
# 1 2.0
# 2 NaN
# 3 3.0
# 4 4.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With