Python 行过滤,这样我们只保留有限的条目

Python 行过滤,这样我们只保留有限的条目,python,pandas,Python,Pandas,我发现在我的数据框中保留有限的条目 公式是: df[df == np.Inf] = np.NaN df.dropna() 但是,当我尝试时: In: df[df == np.Inf] = np.NaN ## -- End pasted text -- --------------------------------------------------------------------------- TypeError Trac

我发现在我的数据框中保留有限的条目

公式是:

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
In:df[df==np.Inf]=np.NaN
##--结束粘贴的文本--
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->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:无法在混合类型框架上进行布尔设置
有没有更好的方法来过滤行,以便我们在特定列中只保留有限的条目?

使用
np.isinf()

因此,
x.dropna()
给了我:

   0  1  2
2  6  7  8
要仅查看列的子集,请使用
子集
kwarg(始终获取列表):

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

因此,
x.dropna()
给了我:

   0  1  2
2  6  7  8
要仅查看列的子集,请使用
子集
kwarg(始终获取列表):

您也可以采纳DSM的建议,直接为数据帧编制索引:
x[~np.isinf(x).any(axis=1)]
如建议,您可以使用
模式。使用inf\u As\u null

In [14]: df = DataFrame({'a': randint(3,size=10)})

In [15]: df['b'] = tm.choice([2,3,nan,inf,-inf], size=len(df))

In [16]: df
Out[16]:
   a       b
0  1     inf
1  2    -inf
2  0  3.0000
3  1    -inf
4  2     NaN
5  1  3.0000
6  1     inf
7  0  2.0000
8  2    -inf
9  2     inf

In [17]: with pd.option_context('mode.use_inf_as_null', True):
   ....:     res = df.dropna()
   ....:

In [18]: res
Out[18]:
   a  b
2  0  3
5  1  3
7  0  2
按照建议,您可以使用
模式。将\u inf\u用作\u null

In [14]: df = DataFrame({'a': randint(3,size=10)})

In [15]: df['b'] = tm.choice([2,3,nan,inf,-inf], size=len(df))

In [16]: df
Out[16]:
   a       b
0  1     inf
1  2    -inf
2  0  3.0000
3  1    -inf
4  2     NaN
5  1  3.0000
6  1     inf
7  0  2.0000
8  2    -inf
9  2     inf

In [17]: with pd.option_context('mode.use_inf_as_null', True):
   ....:     res = df.dropna()
   ....:

In [18]: res
Out[18]:
   a  b
2  0  3
5  1  3
7  0  2

您也可以使用
isinf
而不使用它来替换值,例如
x[~np.isinf(x).any(axis=1)]
.Hmm@DSM I get:
TypeError:ufunc'isinf'不支持输入类型
向我展示一个示例数据帧和代码来重现它,我们应该能够得到平方使用。(@user815423426)您也可以使用
isinf
而不使用它来替换值,例如
x[~np.isinf(x).any(axis=1)]
.Hmm@DSM I get:
TypeError:ufunc'isinf'不支持输入类型
向我展示一个示例数据帧和代码来重现它,我们应该能够得到平方使用。(@user815423426)