grouby() function in Pandas returning IndexError: index 2 is out of bounds for axis 0 with size 2

grouby() function in Pandas returning IndexError: index 2 is out of bounds for axis 0 with size 2

升级 Python 环境后,我注意到 pandas 库 returns 中的函数 groupby() 类型为

的错误消息
IndexError: index 2 is out of bounds for axis 0 with size 2

偶尔,即使在较旧的 Python 环境中一切 运行 都很好。在这种特殊情况下,错误实际上意味着在某个列中有两个唯一值(例如 ab),但相关的 pandas 函数生成索引 [0, 1, 2]。这意味着索引 2 没有自己的唯一值。因此错误消息。

由于错误似乎没有遵循任何明显的模式,我“潜入”pandas 代码。我能够在 sorting.py 文件中的函数 decons_group_index() 中找到问题的根源。该问题可以在以下代码中说明。

import numpy as np

x = np.array([2076999867579399,
              2077965839147919,
              2078931810716439,
              2079897782284959,
              2080863753853479,
              2081829725421999,
              2082795696990519,
              2083761668559039])

y = np.array([0, 0, 0, 0, 0, 0, 0 , 0])
factor = 160995261420
shape = 1

labels = (x - y) % (factor * shape) // factor

print(labels)

如果我 运行 python 3.7.3.final.0 中的代码,我会得到 [0 0 0 0 0 0 0 0],这是预期的行为。但是,如果我 运行 它在 python 3.9.6.final.0 中,我得到 [1 1 1 1 1 1 1 1],这会触发上述类型的错误。

不知道你有没有遇到过类似的事情,有没有什么简单优雅的方法可以解决这个问题。我也不确定这是否可以被视为错误,因此应该在某处报告。

提前致谢,

麦基

好的 - 结果证明这是 numpy 中的一个错误。已举报 here.

麦基