【问题标题】:ZeroDivisionError - PandasZeroDivisionError - 熊猫
【发布时间】:2018-06-26 10:15:19
【问题描述】:

脚本如下 - 旨在按关键字排名位置显示平均点击率的差异 - 突出显示 ctrs 表现不佳的查询/页面。

直到最近它一直运行良好 - 但是它现在给了我下面的 ZeroDivisionError。

import os
import sys
import math
from statistics import median
import numpy as np
import pandas as pd

in_file = 'data.csv'
thresh = 5

df = pd.read_csv(in_file)
# Round position to tenths
df = df.round({'position': 1})
# Restrict garbage 1 impression, 1 click, 100% CTR entries
df = df[df.clicks >= thresh]
df.head()

def apply_stats(row, df):

    if int(row['impressions']) > 5:

        ctr = float(row['ctr'])
        pos = row['position']

        # Median
        median_ctr = median(df.ctr[df.position==pos])
        # Mad
        mad_ctr = df.ctr[df.position==pos].mad()

        row['score'] = round(float( (1 * (ctr - median_ctr))/mad_ctr ), 3 ) 
        row['mad'] = mad_ctr
        row['median'] = median_ctr

    return row

df = df.apply(apply_stats, args=(df,), axis = 1)
df.to_csv('out2_' + in_file)
df.head()

我收到的错误是这样的:

-----------------------------------------
ZeroDivisionErrorTraceback (most recent call last)
<ipython-input-33-f1eef41d1c9a> in <module>()
----> 1 df = df.apply(apply_stats, args=(df,), axis = 1)
      2 df.to_csv('out2_' + in_file)
      3 df.head()

~\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds)
   6002                          args=args,
   6003                          kwds=kwds)
-> 6004         return op.get_result()
   6005 
   6006     def applymap(self, func):

~\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
    140             return self.apply_raw()
    141 
--> 142         return self.apply_standard()
    143 
    144     def apply_empty_result(self):

~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
    246 
    247         # compute the result using the series generator
--> 248         self.apply_series_generator()
    249 
    250         # wrap results

~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_series_generator(self)
    275             try:
    276                 for i, v in enumerate(series_gen):
--> 277                     results[i] = self.f(v)
    278                     keys.append(v.name)
    279             except Exception as e:

~\Anaconda3\lib\site-packages\pandas\core\apply.py in f(x)
     72         if kwds or args and not isinstance(func, np.ufunc):
     73             def f(x):
---> 74                 return func(x, *args, **kwds)
     75         else:
     76             f = func

<ipython-input-32-900a8cda8fce> in apply_stats(row, df)
     11         mad_ctr = df.ctr[df.position==pos].mad()
     12 
---> 13         row['score'] = round(float( (1 * (ctr - median_ctr))/mad_ctr ), 3 )
     14         row['mad'] = mad_ctr
     15         row['median'] = median_ctr

ZeroDivisionError: ('float division by zero', 'occurred at index 317')

CSV 中的数据都是整数,表示点击次数、展示次数 + 浮动次数表示 ctr、位置。

脚本中是否有错误或可能是数据格式问题?

【问题讨论】:

标签: python pandas division zero divide-by-zero


【解决方案1】:

看起来你得到了mad_ctr 为零的行,所以只需为这种情况添加一个检查:

row['score'] = round(float( (1 * (ctr - median_ctr))/mad_ctr ), 3 ) if mad_ctr != 0 else 0

如果mad_ctr 为零,这会将score 设置为零。但如果您愿意,也可以使用None 或其他默认值。

【讨论】:

    【解决方案2】:

    如果我正确地阅读了错误,您在某个点上的某行变量 mad_ctr(显示为计算分数的除法器)等于 0(它似乎发生在索引为 317 的行上) .

    由于 mad 函数计算平均绝对偏差,因此对于该特定行,所有值可能都相同,因此偏差为零。

    这是一个与你拥有的数据和你想要计算的东西有关的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 2020-06-03
      • 2021-05-23
      • 2013-01-12
      • 2020-12-12
      • 2016-04-05
      • 2019-02-24
      相关资源
      最近更新 更多