【问题标题】:Possible pandas bug?可能的熊猫错误?
【发布时间】:2021-04-02 13:27:51
【问题描述】:

只是看看 Python/Pandas 中的一些奇怪行为。

我知道设置很复杂,我正在做一些……挑战。

def lucas_n(n):
    '''Return the fist n lucas numbers modulo 1_000_007'''
    my_list = [1,3]
    while len(my_list) < n:
        my_list.append((my_list[-1]+my_list[-2])%1_000_007)
    return my_list

def f(seq):
    '''Look up https://projecteuler.net/problem=739'''
    
    df = pd.Series(seq)
    
    for i in range(len(seq)-1):
        df = df.iloc[1:].cumsum()
        
    return df.iloc[0]

x = lucas_n(1e4)

f(x)

>>> -8402283173942682253

简而言之,x 是一个正整数序列,f 应用连续的.iloc[1:].cumsum() 操作。

而且输出是负数...

这是一个错误吗?数据类型问题?

【问题讨论】:

  • 看起来像整数溢出或smth,因为以1e3为参数,一切正常。
  • mortada.net/can-integer-operations-overflow-in-python.html。在 Python 本身中,整数不能溢出,但由于 pandas/numpy 使用 C 作为后端,因此这些包的溢出是真实的。
  • 它看起来可能会在 x = lucas_n(1e4)[0:4442]x = lucas_n(1e4)[0:4443] 之间流动
  • 谢谢 - 结合起来,我很高兴接受底层 C 后端存在溢出。如果您将其作为答案,我会接受。

标签: python pandas type-conversion integer


【解决方案1】:

看来你有一个整数溢出。在 Python 本身中,整数可以具有任意精度,但由于 pandas/numpy 默认使用 C 数据类型,可能会发生溢出:

enter link description here

为了解决这个问题,您可能需要手动将数据转换为 Python 整数:

def f(seq):
    '''Look up https://projecteuler.net/problem=739'''
    
    df = pd.Series(seq).astype('int') # Casting to Python integer type
    
    for i in range(len(seq)-1):
        df = df.iloc[1:].cumsum()
        
    return df.iloc[0]

这解决了我测试中的溢出问题。

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 2019-06-23
    • 2015-01-20
    • 2017-05-24
    • 2016-06-11
    • 2013-05-15
    • 2017-05-23
    • 2018-09-06
    • 1970-01-01
    相关资源
    最近更新 更多