Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

python - Reducing pandas series with multiple nan values to a set gives multiple nan values

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])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Therefore,

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 contains np.nans, which are identical, so

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

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]

so set does not treat them as equal:

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

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.])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...