为什么Pandas在一个案例中导致'ZeroDivisionError'而在另一个案例中没有?

时间:2012-09-10 14:04:02

标签: python pandas

我有一个Pandas数据帧'dt = myfunc()',并将IDLE的屏幕输出复制如下:

>>> from __future__ import division
>>> dt = __get_stk_data__(['*'], frq='CQQ', from_db=False) # my function
>>> dt = dt[dt['ebt']==0][['tax','ebt']]
>>> type(dt)
<class 'pandas.core.frame.DataFrame'>
>>> dt
                tax ebt
STK_ID RPT_Date        
000719 20100331   0   0
       20100630   0   0
       20100930   0   0
       20110331   0   0
002164 20080331   0   0
300155 20120331   0   0
600094 20090331   0   0
       20090630   0   0
       20090930   0   0
600180 20090331   0   0
600757 20110331   0   0
>>> dt['tax_rate'] = dt.tax/dt.ebt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python\Lib\site-packages\pandas\core\series.py", line 72, in wrapper
    return Series(na_op(self.values, other.values),
  File "D:\Python\Lib\site-packages\pandas\core\series.py", line 53, in na_op
    result = op(x, y)
ZeroDivisionError: float division
>>> 

我花了很多时间来弄清楚为什么Pandas会提出'ZeroDivisionError:float division',而Pandas在下面的示例代码中效果非常好:

tuples = [('000719','20100331'),('000719','20100930'),('002164','20080331')]
index = MultiIndex.from_tuples(tuples, names=['STK_ID', 'RPT_Date'])
dt =DataFrame({'tax':[0,0,0],'ebt':[0,0,0]},index=index)
dt['tax_rate'] = dt.tax/dt.ebt

>>> dt
                 ebt  tax  tax_rate
STK_ID RPT_Date                    
000719 20100331    0    0       NaN
       20100930    0    0       NaN
002164 20080331    0    0       NaN
>>> 

我希望Pandas为这两种情况提供'NaN',为什么'ZeroDivisionError'会在第一种情况下发生?怎么解决?


以下代码&amp;附加屏幕输出以提供进一步的调试信息

def __by_Q__(df):
    ''' this function transforms the input financial report data (which
        is accumulative) to qurterly data
    '''
    df_q1=df[df.index.map(lambda x: x[1].endswith("0331"))]

    print 'before diff:\n'
    print df.dtypes
    df_delta = df.diff()
    print '\nafter diff: \n'
    print df_delta.dtypes


    q1_mask = df_delta.index.map(lambda x: x[1].endswith("0331"));
    df_q234 = df_delta[~q1_mask]

    rst = concat([df_q1,df_q234])

    rst=rst.sort_index()
    return rst

屏幕输出:

before diff:

sales                      float64
discount                    object
net_sales                  float64
cogs                       float64
ebt                        float64
tax                        float64

after diff: 

sales                      object
discount                   object
net_sales                  object
cogs                       object
ebt                        object
tax                        object

2 个答案:

答案 0 :(得分:3)

@bigbug,你是如何从SQLite后端获取数据的?如果您查看pandas.io.sqlread_frame方法会有一个coerce_float参数,如果可能,应将数值数据转换为浮点数。

你的第二个例子是有效的,因为DataFrame构造函数试图对类型很聪明。如果将dtype设置为object,则它将失败:

In [16]: dt = DataFrame({'tax':[0,0,0], 'ebt':[0,0,0]},index=index,dtype=object)

In [17]: dt.tax/dt.ebt
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)

再次检查您的数据导入代码,让我知道您找到了什么?

答案 1 :(得分:0)

我不能重现那种行为(我尝试从整数,浮点数和numpy数组创建DataFrames),我认为最好将NaN分配到tax_rate列并且然后在ebt非零时覆盖值:

dt['tax_rate'] = numpy.nan
dt['tax_rate'][dt.ebt != 0] = dt.tax[dt.ebt != 0] / dt.ebt[dt.ebt != 0]