Skip to content

Additional tests for ufunc(Series) #26951

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jun 21, 2019
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -769,7 +769,7 @@ Sparse
- Bug in :class:`SparseFrame` constructor where passing ``None`` as the data would cause ``default_fill_value`` to be ignored (:issue:`16807`)
- Bug in :class:`SparseDataFrame` when adding a column in which the length of values does not match length of index, ``AssertionError`` is raised instead of raising ``ValueError`` (:issue:`25484`)
- Introduce a better error message in :meth:`Series.sparse.from_coo` so it returns a ``TypeError`` for inputs that are not coo matrices (:issue:`26554`)
- Bug in :func:`numpy.modf` on a :class:`SparseArray`. Now a tuple of :class:`SparseArray` is returned.
- Bug in :func:`numpy.modf` on a :class:`SparseArray`. Now a tuple of :class:`SparseArray` is returned (:issue:`26946`).

Other
^^^^^
Expand Down
185 changes: 185 additions & 0 deletions pandas/tests/series/test_ufunc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import string

import numpy as np
import pytest

import pandas as pd
import pandas.util.testing as tm

UNARY_UFUNCS = [np.positive, np.floor, np.exp]
BINARY_UFUNCS = [
np.add, # dunder op
np.logaddexp,
]
SPARSE = [
pytest.param(True,
marks=pytest.mark.xfail(reason="Series.__array_ufunc__")),
False,
]
SPARSE_IDS = ['sparse', 'dense']
SHUFFLE = [
pytest.param(True, marks=pytest.mark.xfail(reason="GH-26945",
strict=False)),
False
]


@pytest.fixture
def arrays_for_binary_ufunc():
"""
A pair of random, length-100 integer-dtype arrays, that are mostly 0.
"""
a1 = np.random.randint(0, 10, 100, dtype='int64')
a2 = np.random.randint(0, 10, 100, dtype='int64')
a1[::3] = 0
a2[::4] = 0
return a1, a2


@pytest.mark.parametrize("ufunc", UNARY_UFUNCS)
@pytest.mark.parametrize("sparse", SPARSE, ids=SPARSE_IDS)
def test_unary_ufunc(ufunc, sparse):
array = np.random.randint(0, 10, 10, dtype='int64')
array[::2] = 0
if sparse:
array = pd.SparseArray(array, dtype=pd.SparseDtype('int', 0))

index = list(string.ascii_letters[:10])
name = "name"
series = pd.Series(array, index=index, name=name)

result = ufunc(series)
expected = pd.Series(ufunc(array), index=index, name=name)
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize("ufunc", BINARY_UFUNCS)
@pytest.mark.parametrize("sparse", SPARSE, ids=SPARSE_IDS)
@pytest.mark.parametrize("shuffle", SHUFFLE)
@pytest.mark.parametrize("box_other", ['series', 'index', 'raw'])
@pytest.mark.parametrize("flip", [True, False],
ids=['flipped', 'straight'])
def test_binary_ufunc(ufunc, sparse, shuffle, box_other,
flip,
arrays_for_binary_ufunc):
# Check the invariant that
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you give a little expl of what the parametizations do if not obvious, e.g. flip & shuffle actually are not immediately obvious

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I may split those out to separate tests. It'll be a bit more code, but much clearer.

# ufunc(Series(a), Series(b)) == Series(ufunc(a, b))
# with alignment.
a1, a2 = arrays_for_binary_ufunc
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you call these: left_array, right_array

I know its a bit longer, but more readable IMHO

if sparse:
a1 = pd.SparseArray(a1, dtype=pd.SparseDtype('int', 0))
a2 = pd.SparseArray(a2, dtype=pd.SparseDtype('int', 0))

name = "name"
s1 = pd.Series(a1, name=name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

left_series and right_series

if box_other == 'series':
s2 = pd.Series(a2, name=name)
elif box_other == 'index':
# Index should defer to Series
s2 = pd.Index(a2, naame=name)
else:
s2 = a2

idx = np.random.permutation(len(s1))

if shuffle:
s2 = s2.take(idx)
if box_other != 'series':
# when other is a Series, we align, so we don't
# need to shuffle the array for expected. In all
# other cases, we do.
a2 = a2.take(idx)

a, b = s1, s2
c, d = a1, a2
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find this very confusing, can you use the same terms and not use a, b, c, d?


if flip:
a, b = b, a
c, d = d, c

result = ufunc(a, b)
expected = pd.Series(ufunc(c, d), name=name)
if box_other == 'index' and flip:
raise pytest.xfail("Index should defer to Series")
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize("ufunc", BINARY_UFUNCS)
@pytest.mark.parametrize("sparse", SPARSE, ids=SPARSE_IDS)
@pytest.mark.parametrize("flip", [True, False])
def test_binary_ufunc_scalar(ufunc, sparse, flip, arrays_for_binary_ufunc):
array, _ = arrays_for_binary_ufunc
if sparse:
array = pd.SparseArray(array)
other = 2
series = pd.Series(array, name="name")

a, b = series, other
c, d = array, other
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above if you can make this more clear

if flip:
c, d = b, c
a, b = b, a

expected = pd.Series(ufunc(a, b), name="name")
result = pd.Series(ufunc(c, d), name="name")
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize("ufunc", [np.divmod]) # any others?
@pytest.mark.parametrize("sparse", SPARSE, ids=SPARSE_IDS)
@pytest.mark.parametrize("shuffle", SHUFFLE)
@pytest.mark.filterwarnings("ignore:divide by zero:RuntimeWarning")
def test_multiple_ouput_binary_ufuncs(ufunc, sparse, shuffle,
arrays_for_binary_ufunc):
a1, a2 = arrays_for_binary_ufunc

if sparse:
a1 = pd.SparseArray(a1, dtype=pd.SparseDtype('int', 0))
a2 = pd.SparseArray(a2, dtype=pd.SparseDtype('int', 0))

s1 = pd.Series(a1)
s2 = pd.Series(a2)

if shuffle:
# ensure we align before applying the ufunc
s2 = s2.sample(frac=1)

expected = ufunc(a1, a2)
assert isinstance(expected, tuple)

result = ufunc(s1, s2)
assert isinstance(result, tuple)
tm.assert_series_equal(result[0], pd.Series(expected[0]))
tm.assert_series_equal(result[1], pd.Series(expected[1]))


@pytest.mark.parametrize("sparse", SPARSE, ids=SPARSE_IDS)
def test_multiple_ouput_ufunc(sparse, arrays_for_binary_ufunc):
array, _ = arrays_for_binary_ufunc

if sparse:
array = pd.SparseArray(array)

series = pd.Series(array, name="name")
result = np.modf(series)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok I c you are doing this here

expected = np.modf(array)

assert isinstance(result, tuple)
assert isinstance(expected, tuple)

tm.assert_series_equal(result[0], pd.Series(expected[0], name="name"))
tm.assert_series_equal(result[1], pd.Series(expected[1], name="name"))


@pytest.mark.parametrize("sparse", SPARSE, ids=SPARSE_IDS)
@pytest.mark.parametrize("ufunc", BINARY_UFUNCS)
@pytest.mark.xfail(reason="Series.__array_ufunc__")
def test_binary_ufunc_drops_series_name(ufunc, sparse,
arrays_for_binary_ufunc):
# Drop the names when they differ.
a1, a2 = arrays_for_binary_ufunc
s1 = pd.Series(a1, name='a')
s2 = pd.Series(a2, name='b')

result = ufunc(s1, s2)
assert result.name is None