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
?我得到相同的结果pd.Series([np.nan, np.nan, 2, np.nan, 2]).tolist()
。我试图通过以下函数来计算 pandas groupby 对象(基本上是 pandas Series)中最常见的元素
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
刚刚意识到即使我有一个步骤,我也会得到多个 NaN 的错误计数x = list(srs)
.
编辑:
只是为了澄清为什么这对我来说是一个问题:
>>> 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