Pandas Float Index Series

I am trying to use float numbers as an index for the pandas Series, but it does not work properly. For example, in the following code, when I try to call the value policy [9.7], it returns an error. I believe this is due to the fact that the floating point number 9.7 is not stored exactly like 9.7 on the computer (for example, 9.7000000001). Is there any way around this? Or is it just not recommended to use the float index?

Any input is appreciated. Thanks!

import numpy as np import pandas as pd W_grid = np.arange(100)*0.1 policy = pd.Series(np.random.rand(100), index = W_grid) policy[9.7] 

 KeyError Traceback (most recent call last) <ipython-input-224-89dfc3470c3d> in <module>() ----> 1 policy[9.7] D:\Warren\Anaconda\lib\site-packages\pandas\core\series.pyc in __getitem__(self, key) 482 def __getitem__(self, key): 483 try: --> 484 result = self.index.get_value(self, key) 485 486 if not np.isscalar(result): D:\Warren\Anaconda\lib\site-packages\pandas\core\index.pyc in get_value(self, series, key) 2038 2039 k = _values_from_object(key) -> 2040 loc = self.get_loc(k) 2041 new_values = series.values[loc] 2042 if np.isscalar(new_values) or new_values is None: D:\Warren\Anaconda\lib\site-packages\pandas\core\index.pyc in get_loc(self, key) 2091 except (TypeError, NotImplementedError): 2092 pass -> 2093 return super(Float64Index, self).get_loc(key) 2094 2095 @property D:\Warren\Anaconda\lib\site-packages\pandas\core\index.pyc in get_loc(self, key) 1179 loc : int if unique index, possibly slice or mask if not 1180 """ -> 1181 return self._engine.get_loc(_values_from_object(key)) 1182 1183 def get_value(self, series, key): D:\Warren\Anaconda\lib\site-packages\pandas\index.pyd in pandas.index.IndexEngine.get_loc (pandas\index.c:3656)() D:\Warren\Anaconda\lib\site-packages\pandas\index.pyd in pandas.index.IndexEngine.get_loc (pandas\index.c:3534)() D:\Warren\Anaconda\lib\site-packages\pandas\hashtable.pyd in pandas.hashtable.Float64HashTable.get_item (pandas\hashtable.c:9645)() D:\Warren\Anaconda\lib\site-packages\pandas\hashtable.pyd in pandas.hashtable.Float64HashTable.get_item (pandas\hashtable.c:9586)() KeyError: 9.7 
+5
source share
1 answer

What version of Pandas are you using?

In the documents :

Float64index

Note. Starting with version 0.14.0, Float64Index is supported by the native float64 dtype array. Prior to 0.14.0, an array of dtype objects was supported by Float64Index. Using the float64 type in the backend speeds up arithmetic operations by about 30x, and indexing buffering operations on the Float64Index itself are approximately 2x. New in version 0.13.0.

By default, Float64Index will be automatically created when transferring floating or mixed integer values ​​when creating the index. This allows you to use the shortcut-based cut-based paradigm, which makes [], ix, loc for scalar indexing and slicing work exactly the same.

0
source

Source: https://habr.com/ru/post/1216011/


All Articles