Why does
>> import pandas as pd
>> import numpy as np
>> list(pd.Series([np.nan, np.nan, 2, np.nan, 2])) == [np.nan, np.nan, 2, np.nan, 2]
return False
? I get the same result with pd.Series([np.nan, np.nan, 2, np.nan, 2]).tolist()
. I was trying to count the most common element in a pandas groupby object (so basically, a pandas Series) through the following function
def get_most_common(srs):
"""
Returns the most common value in a list. For ties, it returns whatever
value collections.Counter.most_common(1) gives.
"""
from collections import Counter
x = list(srs)
my_counter = Counter(x)
most_common_value = my_counter.most_common(1)[0][0]
return most_common_value
and just realized that I get wrong counts for multiple NaNs even if I have a step x = list(srs)
.
EDIT: Just to clarify why this is an issue for me:
>>> from collections import Counter
>>> Counter(pd.Series([np.nan, np.nan, np.nan, 2, 2, 1, 5]).tolist())
Counter({nan: 1, nan: 1, nan: 1, 2.0: 2, 1.0: 1, 5.0: 1}) # each nan is counted differently
>>> Counter([np.nan, np.nan, np.nan, 2, 2, 1, 5])
Counter({nan: 3, 2: 2, 1: 1, 5: 1}) # nan count of 3 is correct