gpt4 book ai didi

python - Pandas Series float 索引

转载 作者:太空狗 更新时间:2023-10-30 01:37:59 25 4
gpt4 key购买 nike

我正在尝试使用 float 作为 pandas 系列的索引,但它似乎无法正常工作。例如,在下面的代码中,当我尝试调用值 policy[9.7] 时,它返回错误。我认为这是因为 float 9.7 在计算机中没有准确存储为 9.7(例如 9.7000000001)。无论如何要解决这个问题?或者使用 float 索引根本不是一个好主意?

非常感谢任何输入。谢谢!

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

最佳答案

您使用的是哪个版本的 Pandas?

根据 documents :

Float64Index

Note As of 0.14.0, Float64Index is backed by a native float64 dtype array. Prior to 0.14.0, Float64Index was backed by an object dtype array. Using a float64 dtype in the backend speeds up arithmetic operations by about 30x and boolean indexing operations on the Float64Index itself are about 2x as fast. New in version 0.13.0.

By default a Float64Index will be automatically created when passing floating, or mixed-integer-floating values in index creation. This enables a pure label-based slicing paradigm that makes [],ix,loc for scalar indexing and slicing work exactly the same.

关于python - Pandas Series float 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29237678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com