gpt4 book ai didi

python - 行过滤,以便我们只保留有限的条目

转载 作者:行者123 更新时间:2023-11-28 22:49:21 25 4
gpt4 key购买 nike

我找到了 this recipe在我的数据框中保留有限条目。

公式为:

df[df == np.Inf] = np.NaN
df.dropna()

但是,当我尝试时:

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

## -- End pasted text --
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-88eed8630e79> in <module>()
----> 1 df[df == np.Inf] = np.NaN

/Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)

/Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/pandas/core/frame.pyc in _setitem_frame(self, key, value)

TypeError: Cannot do boolean setting on mixed-type frame

是否有更好的方法来过滤行,以便我们只在特定列中保留有限 个条目?

最佳答案

使用np.isinf()

x = pandas.DataFrame([
[1, 2, np.inf],
[4, np.inf, 5],
[6, 7, 8]
])
x[np.isinf(x)] = np.nan
print(x)

0 1 2
0 1 2 NaN
1 4 NaN 5
2 6 7 8

然后 x.dropna() 给我:

   0  1  2
2 6 7 8

要仅查看列的子集,请使用 subset kwarg(始终采用列表):

x.dropna(subset=[1])
0 1 2
0 1 2 NaN
2 6 7 8

您也可以采纳 DSM 的建议,直接索引数据框:x[~np.isinf(x).any(axis=1)]

关于python - 行过滤,以便我们只保留有限的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23921766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com