我(自认为)知道如何检查某个值是否包含在 pandas 系列的索引中,但我无法在下面的示例中使用它。也许这是一个错误?
首先,我生成一些随机数:
import numpy as np
import pandas as pd
some_numbers = np.random.randint(0,4,size=10)
print(some_numbers)
输出:
[0 2 2 3 1 1 2 2 3 2]
然后,我用这些数字创建一个系列并计算它们的频率
s = pd.Series(some_numbers)
gb = s.groupby(s).size() / len(s)
print(gb)
输出:
0 0.1
1 0.2
2 0.5
3 0.2
dtype: float64
到目前为止,还不错。但是我不明白下一行代码的输出:
1.3 in gb
输出:
True
输出不应该是 False 吗? (我在 Python 3.6.2 上有 pandas 0.20.3)
我知道我可以用
1.3 in list(gb.index)
但是如果 Series 很大,这不是很有效。
显示错误的简单示例
import pandas as pd
s = pd.Series([.1,.2,.3])
print(s)
0 0.1
1 0.2
2 0.3
dtype: float64
3.4 in s
False
但是,等等……
s = pd.Series([.1,.2,.3,.4])
print(s)
0 0.1
1 0.2
2 0.3
3 0.4
dtype: float64
3.4 in s
True
最佳答案
我认为问题在于 gb.index
是一个 int64
索引:
>>> gb.index
Int64Index([0, 1, 2, 3], dtype='int64')
>>> type(gb.index)
<class 'pandas.core.indexes.numeric.Int64Index'>
因此,当您与 1.3
进行比较时,该值被转换为 int。一些证据表明,小于 3.99999
的值将返回 True
,因为将其转换为 int
会得到 3
,但是,gb.index 中的 4.000001
返回 False
因为将 4.000001
转换为 int
返回 4
(不在 gb.index
中)
如果你强制它为一个浮点索引,你最终会得到 false,因为 1.3
不在 Float64Index([0.0, 1.0, 2.0, 3.0], dtype='float64' )
:
>>> 1.3 in gb.index.astype('float')
False
测试 pandas '0.21.1'
, python 3.6.3
关于python - 检查 pandas.Series.index 是否包含一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51563433/