Skip to content

ENH: Change NDFrame.div() to be truediv in Python 2.X #5356

Closed
@jtratner

Description

@jtratner

Now that we have all the arithmetic methods, there's no reason to keep it as before. Not having this means that operating on an int column with missing values switches operation result from floordiv to truediv.

@wesm You had, at one point, said that you would consider this. I believe this change would iron over a long-standing Python wart and make pandas easier to use:

Existing behavior (note how the future import doesn't affect div at all because it's defined in a separate file, but does affect division because Python will call __truediv__ instead of __div__):

In [22]: from __future__ import division

In [23]: ser1 / ser2
Out[23]:
0    0.0
1    0.5
2    1.0
3    1.5
dtype: float64

In [24]: ser1.div(ser2)
Out[24]:
0    0
1    0
2    1
3    1
dtype: int64

And missing values immediately causes this behavior to change (because coerces to float)

In [11]: from pandas import Series

In [12]: ser1 = Series([0, 1, 2, 3])

In [13]: ser2 = Series([2, 2, 2, 2])

In [14]: ser1.div(ser2)
Out[14]:
0    0
1    0
2    1
3    1
dtype: int64
In [15]: ser1[0] = np.nan

In [16]: ser1.div(ser2)
Out[18]:
0    NaN
1    0.5
2    1.0
3    1.5
dtype: float64

And this distinction is totally eliminated in Python 3:

In [11]: from pandas import Series

In [12]: ser1 = Series([0, 1, 2, 3])

In [13]: ser2 = Series([2, 2, 2, 2])

In [14]: ser1.div(ser2)
Out[14]:
0    0.0
1    0.5
2    1.0
3    1.5
dtype: float64
In [15]: ser1[0] = np.nan

In [16]: ser1.div(ser2)
Out[18]:
0    NaN
1    0.5
2    1.0
3    1.5
dtype: float64

Trivial to fix and, while slightly backwards incompatible, would mostly just make things simpler. We should still leave a / b to be dependent upon the future import.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions