我有一个大型数据框,不同列中包含 inf、-inf 值。我想用 NaN 替换所有 inf、-inf 值
我可以逐栏这样做。所以这有效:
df['column name'] = df['column name'].replace(np.inf, np.nan)
但我的代码一次性跨过数据框却没有这样做。
df.replace([np.inf, -np.inf], np.nan)
输出不会替换 inf 值
TL;DR
-
df.replace https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html更换速度最快
±inf
-
but您只需设置即可避免完全替换mode.use_inf_as_na https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#available-options
更换inf
and -inf
df = df.replace([np.inf, -np.inf], np.nan)
Note that inplace
is possible but not recommended https://stackoverflow.com/a/60020384/13138364 and will soon be deprecated https://github.com/pandas-dev/pandas/issues/16529.
Slower df.applymap https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.applymap.html选项:
df = df.applymap(lambda x: np.nan if x in [np.inf, -np.inf] else x)
df = df.applymap(lambda x: np.nan if np.isinf(x) else x)
df = df.applymap(lambda x: x if np.isfinite(x) else np.nan)
Setting mode.use_inf_as_na https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#available-options
请注意,我们实际上不必修改df
根本不。环境mode.use_inf_as_na https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#available-options只会改变方式inf
and -inf
被解释为:
True
意思是对待None
, nan
, -inf
, inf
as null
False
means None
and nan
为空,但是inf
, -inf
不为空(默认)
-
要么全局启用
pd.set_option('mode.use_inf_as_na', True)
-
或者通过上下文管理器在本地
with pd.option_context('mode.use_inf_as_na', True):
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)