将具有多个 nan 值的 pandas 系列减少到一个集合会给出多个 nan 值

2022-01-17 00:00:00 python numpy pandas nan set

问题描述

我希望得到 set([nan,0,1]) 但我得到 set([nan, 0.0, nan, 1.0]):

I'm expecting to get set([nan,0,1]) but I get set([nan, 0.0, nan, 1.0]):

>>> import numpy as np
>>> import pandas as pd
>>> l= [np.nan,0,1,np.nan]
>>> set(pd.Series(l))
set([nan, 0.0, nan, 1.0])
>>> set(pd.Series(l).tolist())
set([nan, 0.0, nan, 1.0])
>>> set(l)
set([nan, 0, 1])


解决方案

并非所有的 nan 都是相同的:

Not all nans are identical:

In [182]: np.nan is np.nan
Out[182]: True

In [183]: float('nan') is float('nan')
Out[183]: False

In [184]: np.float64('nan') is np.float64('nan')
Out[184]: False

因此,

In [178]: set([np.nan, np.nan])
Out[178]: {nan}

In [179]: set([float('nan'), float('nan')])
Out[179]: {nan, nan}

In [180]: set([np.float64('nan'), np.float64('nan')])
Out[180]: {nan, nan}

l 包含 np.nan,它们是相同的,所以

l contains np.nans, which are identical, so

In [158]: set(l)
Out[158]: {nan, 0, 1}

pd.Series(l).tolist() 包含不完全相同的 np.float64('nan'):

but pd.Series(l).tolist() contains np.float64('nan')s which are not identical:

In [160]: [type(item) for item in pd.Series(l).tolist()]
Out[160]: [numpy.float64, numpy.float64, numpy.float64, numpy.float64]

所以 set 不会将它们视为平等:

so set does not treat them as equal:

In [157]: set(pd.Series(l).tolist())
Out[157]: {nan, 0.0, nan, 1.0}

<小时>

如果您有 Pandas 系列,请使用它的 unique 方法而不是 set 来查找唯一值:


If you have a Pandas Series, use it's unique method instead of set to find unique values:

>>> s = pd.Series(l)
>>> s.unique()
array([ nan,   0.,   1.])

相关文章