pandas 在特性pandas.series 中将-inf 值替换为np.nan

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49814077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:27:47  来源:igfitidea点击:

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

pythonpandasnumpyreplaceseries

提问by Javiss

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.

我想将 pandas.series 特征(我的数据帧的列)中的 -inf 值替换为 np.nan,但我无法做到。

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.

不起作用。

回答by shivsn

it should work:

它应该工作:

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

回答by jpp

The problem may be that you are not assigning back to the original series.

问题可能是您没有分配回原始系列。

Note that pd.Series.replaceis notan in-place operation by default. The below code is a minimal example.

请注意,pd.Series.replace不是默认就地操作。下面的代码是一个最小的例子。

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