Replacing -inf values to np.nan in a feature pandas.series [duplicate]

南楼画角 提交于 2019-12-02 12:31:22

问题


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.


回答1:


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



回答2:


it should work:

df.replace([np.inf, -np.inf], np.nan,inplace=True)


来源:https://stackoverflow.com/questions/49814077/replacing-inf-values-to-np-nan-in-a-feature-pandas-series

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!