熊猫错误:[<class 'decimal.DivisionUndefined'>]

Vik*_*r.w 3 python pandas

我的数据框如下所示:

timestamp   topAsk  topBid  CPA midprice    CPB spread  s

    0   2019-03-14 00:00:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
    1   2019-03-14 00:01:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
    2   2019-03-14 00:02:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
    3   2019-03-14 00:03:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
    4   2019-03-14 00:04:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
    5   2019-03-14 00:05:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
    6   2019-03-14 00:06:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
    7   2019-03-14 00:07:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
    8   2019-03-14 00:08:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
    9   2019-03-14 00:09:00 0.00005000  0.00004957  0.00004979  0.00004979  0.00004979  4.3E-7  0.008636272343844145410725045190
Run Code Online (Sandbox Code Playgroud)

当我尝试使用以下代码行添加新列时:df['gamma'] = ((df['midprice'] - df['CPB']) / df['spread'])我收到以下错误消息=Pandas error: [<class 'decimal.DivisionUndefined'>]

是不是因为我的专栏df['spread']太小了?我有点卡住了,谢谢!

df.info() 显示:

在此输入图像描述

Ser*_*sta 8

decimal.InvalidOperation: [<class 'decimal.DivisionUndefined'>]意味着你在某个地方0/0使用Decimal值进行了划分。通过首先测试是否为 0,很容易找到解决方法df['spread'],但您确实应该尝试找出为什么以及如何将作为除数的值设为空。在这种情况下,我将使用 NaN 作为结果。代码可以是:

df['gamma'] = df.apply(lambda x:
     (x['midprice'] - x['CPB']) / x['spread'] if x['spread'] != 0
     else decimal.Decimal('NaN'), axis=1)
Run Code Online (Sandbox Code Playgroud)