Skip to content

Inconsistent behaviour when dividing by zero #17190

@alexeygrigorev

Description

@alexeygrigorev

Code Sample, a copy-pastable example if possible

import pandas as pd
import numpy as np

def some_func(row):
    try:
        print('type of clicks:', type(row.clicks))
        return row.impressions / row.clicks
    except:
        return np.nan

df = [('a', 1, 1), ('b', 0, 1)]
df = pd.DataFrame(df, columns=['src', 'clicks', 'impressions'])
res = df.apply(lambda row: some_func(row), axis=1)
print(res)

df = [(1, 1), (0, 1)]
df = pd.DataFrame(df, columns=['clicks', 'impressions'])
res = df.apply(lambda row: some_func(row), axis=1)
print(res)

Problem description

The behavior when dividing by zero is inconsistent in these two examples above. The difference is that in the first case there is a column with strings, while in the second example there are only numerical columns.
Additionally, in the first case, type returns int, and in the second - numpy.int64
When the type is python int, an exception is raised, but numpy only issues a warning and returns inf.

Expected Output

These two examples should produce the same output - either inf or NaN

Output of pd.show_versions()

[paste the output of pd.show_versions() here below this line]

In [2]: pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.5.2.final.0
python-bits: 64
OS: Linux
OS-release: 4.2.0-27-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: en_US.UTF-8
LANG: en_US.UTF-8

pandas: 0.18.1
nose: 1.3.7
pip: 9.0.1
setuptools: 27.2.0
Cython: 0.25.2
numpy: 1.12.1
scipy: 0.19.0
statsmodels: 0.6.1
xarray: None
IPython: 5.1.0
sphinx: 1.4.6
patsy: 0.4.1
dateutil: 2.5.3
pytz: 2016.6.1
blosc: None
bottleneck: 1.1.0
tables: 3.2.3.1
numexpr: 2.6.2
matplotlib: 1.5.3
openpyxl: 2.3.2
xlrd: 1.0.0
xlwt: 1.1.2
xlsxwriter: 0.9.3
lxml: 3.6.4
bs4: 4.5.1
html5lib: None
httplib2: None
apiclient: None
sqlalchemy: 1.0.13
pymysql: None
psycopg2: None
jinja2: 2.8
boto: 2.42.0
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    ApplyApply, Aggregate, Transform, MapClosing CandidateMay be closeable, needs more eyeballsDtype ConversionsUnexpected or buggy dtype conversionsNumeric OperationsArithmetic, Comparison, and Logical operations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions