python除以0

时间:2016-09-05 15:21:57

标签: python dataframe

我正在尝试比较表中的值,因此有些可能为零,因此我得到一条错误消息,我不能将其除以0。 为什么脚本没有返回inf而不是错误? 当我在具有一列的数据框架上测试此脚本时,它可以工作,有多个列,它会因零分区错误而中断。

table[change] = ['{0}%'.format(str(round(100*x,2)) for x in \
                                         (table.ix[:,table.shape[1]-1] - table.ix[:,0]) / table.ix[:,0]]

表示例:

         0      1      2      3      4      5      6  \
numbers  0.0  100.0  120.0  220.0  250.0  300.0  500.0\\
revenues 50.0  100.0  120.0  220.0  250.0  300.0  500.0

table.ix[:,0]为0.0。

table.ix[:,0]的某些值为零而其他值不是,因此,请尝试除非我的经验不起作用,因为一旦值divisible等于0,脚本就会中断。

我尝试了其他两种方法,但它们对我不起作用。

你的回答能否更具描述性?我正在努力采取给出的方法。

我有另一种方法,我正在尝试,但它无法正常工作。还没看到问题是什么:

for index, row in table.iterrows():
    if row[0] == 0:
        table[change] = 'Nan'
    else:
        x = (row[-1] - row[0]) / row[0]
        table[change] = '{0} {1}%'.format( str(round(100 * x, 2)))

'变化' column包含相同的值(即表的最后一个比较)

2 个答案:

答案 0 :(得分:1)

看起来python有一个特定的ZeroDivisionError,在这种情况下你应该使用try except做其他事情。

try:
    table[change] = ['{0}%'.format(str(round(100*x,2)) for x in \
                                         (table.ix[:,table.shape[1]-1] - table.ix[:,0]) / table.ix[:,0]]
except ZeroDivisionError:
    table[change] = inf

在这种情况下,您可以分割整个系列,而Pandas将为您进行inf替换。类似的东西:

if df1.ndim == 1:
    table[change] = inf
elif df1.ndim > 1 and df1.shape[0] > 1:
    table[change] = ['{0}%'.format(str(round(100*x,2)) for x in \
                                             (table.ix[:,table.shape[1]-1] - table.ix[:,0]) / table.ix[:,0]]

您的原始示例只有一行这一事实似乎使Pandas在该单元格中获取该分区的值。如果使用包含多行的数组进行除法,则会出现我认为您最初期望的行为。

编辑:

我刚刚发现了我完全忽略的发电机表情。这比我想象的要容易得多。 然后执行规范化,如果您的熊猫版本是最新的,那么您可以根据需要进行回合。

table["change"] = 100 * ((table.iloc[:, -1] - table.iloc[:, 0])/ table.iloc[:, 0])
#And if you're running Pandas v 0.17.0
table.round({"change" : 2})

答案 1 :(得分:1)

除以零通常是一个严重的错误;默认为无穷大并不适合大多数情况。

在尝试计算值之前,请检查除数(在这种情况下为In [4]: df Out[4]: Category Feature valueCount 0 A color 153 1 A color 7 2 A color 48 3 A color 16 4 B length 5 5 C height 1 6 C height 16 In [5]: df.groupby(df['Category']).sum() Out[5]: valueCount Category A 224 B 5 C 17 )是否等于零。如果是,则跳过计算并只分配您想要的任何值。

或者你可以按照@Andrew的建议将分区计算包装在try / except块中。