在函数pandas.series中将-inf值替换为np.nan

Jav*_*iss 1 python replace numpy series pandas

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

我试过了:

    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)
Run Code Online (Sandbox Code Playgroud)

但它不起作用.任何想法如何取代这些价值观?

编辑:

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

作品

但:

df =  df.replace(-np.inf, np.nan)
Run Code Online (Sandbox Code Playgroud)

不起作用.

jpp*_*jpp 11

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
Run Code Online (Sandbox Code Playgroud)


shi*_*vsn 6

它应该工作:

df.replace([np.inf, -np.inf], np.nan,inplace=True)
Run Code Online (Sandbox Code Playgroud)