我有一个带有数值数据的 Pandas 系列,我想找到它的唯一值及其出现频率。我用的是标准程序
# Given the my_data is a column of a pd.Dataframe df
unique = df[my_data].value_counts()
print unique
这是我得到的结果
# -------------------OUTPUT
-0.010000 46483
-0.010000 16895
-0.027497 12215
-0.294492 11915
0.027497 11397
我不明白的是为什么“相同的值”(-0.01) 出现两次。这是一个内部阈值(小值)还是我做错了什么?
更新
如果我将数据帧存储在 csv 中并再次读取它,我会得到正确的结果,即:
# ------------------输出
-0.010000 63378
-0.027497 12215
-0.294492 11915
0.027497 11397
解决方案
根据讨论,我找到了问题的根源和解决方案。如前所述,它是一个浮点精度,可以通过舍入值来解决。不过,如果没有
,我将无法看到它pd.set_option('display.float_format', repr)
非常感谢您的帮助!!
最佳答案
我认为这是一个类似于以下的浮点精度问题:
In [1]: 0.1 + 0.2
Out[1]: 0.30000000000000004
In [2]: 0.1 + 0.2 == 0.3
Out[2]: False
所以试试这个:
df[my_data].round(6).value_counts()
更新:
演示:
In [14]: s = pd.Series([-0.01, -0.01, -0.01000000000123, 0.2])
In [15]: s
Out[15]:
0 -0.01
1 -0.01
2 -0.01
3 0.20
dtype: float64
In [16]: s.value_counts()
Out[16]:
-0.01 2
-0.01 1
0.20 1
dtype: int64
In [17]: s.round(6).value_counts()
Out[17]:
-0.01 3
0.20 1
dtype: int64
关于python - Pandas Series.value_counts() 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105629/