以下脚本-旨在显示按关键字排名位置的平均点击率差异-突出显示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中的数据都是点击次数,展示次数+浮动率(点击率,排名)的整数。
脚本中是否存在错误或可能是数据格式化问题?
答案 0 :(得分:0)
似乎您得到[run]
omit =
*/environment/*
*/migrations/*
Amazon_customers/*
manage.py
为零的行,因此只需添加针对这种情况的检查:
mad_ctr
如果row['score'] = round(float( (1 * (ctr - median_ctr))/mad_ctr ), 3 ) if mad_ctr != 0 else 0
为零,这会将score
设置为零。但是,您也可以根据需要使用mad_ctr
或其他一些默认值。
答案 1 :(得分:0)
如果我正确地读取了错误,则在某一点上某行的变量mad_ctr(作为计算分数的除法器)等于零(似乎发生在索引为317的行中)
由于mad函数计算平均绝对偏差,因此对于该特定行,所有值可能都相同,因此偏差为零。
这是与您拥有的数据和要计算的事物有关的问题。