use*_*808 9 python indexing series pandas
我(我想)知道如何检查一个值是否包含在pandas系列的索引中,但我不能让它在下面的例子中工作.这可能是一个错误吗?
首先,我生成一些随机数:
import numpy as np
import pandas as pd
some_numbers = np.random.randint(0,4,size=10)
print(some_numbers)
Run Code Online (Sandbox Code Playgroud)
输出:
[0 2 2 3 1 1 2 2 3 2]
Run Code Online (Sandbox Code Playgroud)
然后,我创建一个包含这些数字的系列并计算它们的频率
s = pd.Series(some_numbers)
gb = s.groupby(s).size() / len(s)
print(gb)
Run Code Online (Sandbox Code Playgroud)
输出:
0 0.1
1 0.2
2 0.5
3 0.2
dtype: float64
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.但我不明白下一行代码的输出:
1.3 in gb
Run Code Online (Sandbox Code Playgroud)
输出:
True
Run Code Online (Sandbox Code Playgroud)
输出不应该是假的吗?(我在Python 3.6.2上有pandas 0.20.3)
我知道我可以使用
1.3 in list(gb.index)
Run Code Online (Sandbox Code Playgroud)
但如果系列很大,这个效率不高.
import pandas as pd
s = pd.Series([.1,.2,.3])
print(s)
0 0.1
1 0.2
2 0.3
dtype: float64
Run Code Online (Sandbox Code Playgroud)
3.4 in s
False
Run Code Online (Sandbox Code Playgroud)
但是,等一下......
s = pd.Series([.1,.2,.3,.4])
print(s)
0 0.1
1 0.2
2 0.3
3 0.4
dtype: float64
Run Code Online (Sandbox Code Playgroud)
3.4 in s
True
Run Code Online (Sandbox Code Playgroud)
sac*_*cuL 10
我相信问题是这gb.index是一个int64指数:
>>> gb.index
Int64Index([0, 1, 2, 3], dtype='int64')
>>> type(gb.index)
<class 'pandas.core.indexes.numeric.Int64Index'>
Run Code Online (Sandbox Code Playgroud)
所以在进行比较时1.3,该值正在转换为int.一些证据表明这是一个价值达3.99999将返回True,因为转换,为了int给你3,然而,4.000001 in gb.index返回False因为转换4.000001到int回报率4(这是不是gb.index)
如果强制它为float索引,最终会得到false,因为1.3它不在Float64Index([0.0, 1.0, 2.0, 3.0], dtype='float64'):
>>> 1.3 in gb.index.astype('float')
False
Run Code Online (Sandbox Code Playgroud)
测试中 pandas '0.21.1',python 3.6.3
| 归档时间: |
|
| 查看次数: |
1048 次 |
| 最近记录: |