这里的问题是由于浮点不精确,您可以使用该方法get_slice_bound
返回该行的序号位置:
In [237]:
df.iloc[df.index.get_slice_bound(0.47, side='left', kind='loc')]
Out[237]:
0 0.854001
Name: 0.47, dtype: float64
我们可以看到该索引标签的实际值:
In [238]:
df.index[df.index.get_slice_bound(0.47, side='left', kind='loc')]
Out[238]:
0.47000000000000003
虽然 pandas 确实支持float64Index
通过这样做,精确的标签查找将会出现问题,你最好坚持使用默认值Int64Index
get_slice_bound
是一个未记录的方法,但文档字符串为您提供了足够的信息:
Signature: df.index.get_slice_bound(label, side, kind) Docstring: Calculate slice bound that corresponds to given label.
Returns leftmost (one-past-the-rightmost if ``side=='right'``) position of given label.
Parameters
---------- label : object side : {'left', 'right'} kind : {'ix', 'loc', 'getitem'}
您还可以使用get_loc http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html并通过method='nearest'
达到同样的目的:
In [240]:
df.iloc[df.index.get_loc(0.47, method='nearest')]
Out[240]:
0 0.854001
Name: 0.47, dtype: float64