pandas 用 NaN 替换 Inf 导致 AttributeError

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23344498/
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-13 21:58:45  来源:igfitidea点击:

Replacing Inf by NaN results in AttributeError

pythonpandas

提问by Amelio Vazquez-Reina

I have a strange problem in Pandas. I want to replace any entry that has np.Infwith the value np.NaN. However, when I do:

我在 Pandas 中有一个奇怪的问题。我想np.Inf用值替换任何条目np.NaN。但是,当我这样做时:

df[df == np.Inf] = np.NaN

I get:

我得到:

AttributeError: 'float' object has no attribute 'view'

The statement that produces the error specifically is:

具体产生错误的语句是:

df == np.Inf

I wonder if the problem is that I am running the above on a Dataframe with mixed types (see dtypesbelow). But if that is the case, how can I do this replacement still automatically?

我想知道问题是否是我在混合类型的 Dataframe 上运行上述内容(见dtypes下文)。但如果是这种情况,我如何才能仍然自动进行此替换?

In: df.dtypes
Out:
Year                            int64
Week                            int64
item_name                      object
item_uid                       object
Algorithm                      object
item Start                    float64
item 1/4                      float64
item 1/2                      float64
item 3/4                      float64
item Complete                 float64
Daily Nr Impressions          float64
date                   datetime64[ns]
Weekly rate                   float64
dtype: object

回答by Ffisegydd

You can use df.replaceto replace your np.infvalues.

您可以使用df.replace来替换您的np.inf值。

In [9]: import pandas as pd

In [10]: df = pd.DataFrame([1, 2, np.inf])

In [11]: df.replace(np.inf, np.nan)
Out[11]:
    0
0   1
1   2
2 NaN

[3 rows x 1 columns]