8000 TST/REF: share method tests between DataFrame and Series by jbrockmendel · Pull Request #37596 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

TST/REF: share method tests between DataFrame and Series #37596

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 8 commits into from
Nov 3, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
TST/REF: share to_period tests
  • Loading branch information
jbrockmendel committed Nov 2, 2020
commit 2ee25f0de316a7292dce88369dcba6f942066f0a
10 changes: 10 additions & 0 deletions pandas/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,16 @@ def unique_nulls_fixture(request):
# ----------------------------------------------------------------
# Classes
# ----------------------------------------------------------------


@pytest.fixture(params=[pd.DataFrame, pd.Series])
def frame_or_series(request):
"""
Fixture to parametrize over DataFrame and Series.
"""
return request.param


@pytest.fixture(
params=[pd.Index, pd.Series], ids=["index", "series"] # type: ignore[list-item]
)
Expand Down
14 changes: 13 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,13 @@
from pandas.core.construction import extract_array
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.indexes import base as ibase
from pandas.core.indexes.api import Index, ensure_index, ensure_index_from_sequences
from pandas.core.indexes.api import (
DatetimeIndex,
Index,
PeriodIndex,
ensure_index,
ensure_index_from_sequences,
)
from pandas.core.indexes.multi import MultiIndex, maybe_droplevels
from pandas.core.indexing import check_bool_indexer, convert_to_index_sliceable
from pandas.core.internals import BlockManager
Expand Down Expand Up @@ -9253,6 +9259,9 @@ def to_timestamp(

axis_name = self._get_axis_name(axis)
old_ax = getattr(self, axis_name)
if not isinstance(old_ax, PeriodIndex):
raise TypeError(f"unsupported Type {type(old_ax).__name__}")

new_ax = old_ax.to_timestamp(freq=freq, how=how)

setattr(new_obj, axis_name, new_ax)
Expand Down Expand Up @@ -9282,6 +9291,9 @@ def to_period(self, freq=None, axis: Axis = 0, copy: bool = True) -> DataFrame:

axis_name = self._get_axis_name(axis)
old_ax = getattr(self, axis_name)
if not isinstance(old_ax, DatetimeIndex):
raise TypeError(f"unsupported Type {type(old_ax).__name__}")

new_ax = old_ax.to_period(freq=freq)

setattr(new_obj, axis_name, new_ax)
Expand Down
77 changes: 64 additions & 13 deletions pandas/tests/frame/methods/test_to_period.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,87 @@
import numpy as np
import pytest

from pandas import DataFrame, date_range, period_range
from pandas import (
DataFrame,
DatetimeIndex,
PeriodIndex,
Series,
date_range,
period_range,
)
import pandas._testing as tm


class TestToPeriod:
def test_frame_to_period(self):
def test_to_period(self, frame_or_series):
K = 5

dr = date_range("1/1/2000", "1/1/2001")
pr = period_range("1/1/2000", "1/1/2001")
df = DataFrame(np.random.randn(len(dr), K), index=dr)
df["mix"] = "a"
dr = date_range("1/1/2000", "1/1/2001", freq="D")
obj = DataFrame(
np.random.randn(len(dr), K), index=dr, columns=["A", "B", "C", "D", "E"]
)
obj["mix"] = "a"
if frame_or_series is Series:
obj = obj["A"]

pts = df.to_period()
exp = df.copy()
exp.index = pr
tm.assert_frame_equal(pts, exp)
pts = obj.to_period()
exp = obj.copy()
exp.index = period_range("1/1/2000", "1/1/2001")
tm.assert_equal(pts, exp)

pts = df.to_period("M")
tm.assert_index_equal(pts.index, exp.index.asfreq("M"))
pts = obj.to_period("M")
exp.index = exp.index.asfreq("M")
tm.assert_equal(pts, exp)

def test_to_period_without_freq(self, frame_or_series):
# GH#7606 without freq
idx = DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"])
exp_idx = PeriodIndex(
["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], freq="D"
)

obj = DataFrame(np.random.randn(4, 4), index=idx, columns=idx)
if frame_or_series is Series:
obj = obj[idx[0]]
expected = obj.copy()
expected.index = exp_idx
tm.assert_equal(obj.to_period(), expected)

if frame_or_series is DataFrame:
expected = obj.copy()
expected.columns = exp_idx
tm.assert_frame_equal(obj.to_period(axis=1), expected)

def test_to_period_columns(self):
dr = date_range("1/1/2000", "1/1/2001")
df = DataFrame(np.random.randn(len(dr), 5), index=dr)
df["mix"] = "a"

df = df.T
pts = df.to_period(axis=1)
exp = df.copy()
exp.columns = pr
exp.columns = period_range("1/1/2000", "1/1/2001")
tm.assert_frame_equal(pts, exp)

pts = df.to_period("M", axis=1)
tm.assert_index_equal(pts.columns, exp.columns.asfreq("M"))

def test_to_period_invalid_axis(self):
dr = date_range("1/1/2000", "1/1/2001")
df = DataFrame(np.random.randn(len(dr), 5), index=dr)
df["mix"] = "a"

msg = "No axis named 2 for object type DataFrame"
with pytest.raises(ValueError, match=msg):
df.to_period(axis=2)

def test_to_period_raises(self, index, frame_or_series):
# https://github.com/pandas-dev/pandas/issues/33327
obj = Series(index=index, dtype=object)
if frame_or_series is DataFrame:
obj = obj.to_frame()

if not isinstance(index, DatetimeIndex):
msg = f"unsupported Type {type(index).__name__}"
with pytest.raises(TypeError, match=msg):
obj.to_period()
89 changes: 70 additions & 19 deletions pandas/tests/frame/methods/test_to_timestamp.py
77F4
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from pandas import (
DataFrame,
DatetimeIndex,
PeriodIndex,
Series,
Timedelta,
date_range,
period_range,
Expand All @@ -14,48 +16,70 @@
import pandas._testing as tm


def _get_with_delta(delta, freq="A-DEC"):
return date_range(
to_datetime("1/1/2001") + delta,
to_datetime("12/31/2009") + delta,
freq=freq,
)


class TestToTimestamp:
def test_frame_to_time_stamp(self):
def test_to_timestamp(self, frame_or_series):
K = 5
index = period_range(freq="A", start="1/1/2001", end="12/1/2009")
df = DataFrame(np.random.randn(len(index), K), index=index)
df["mix"] = "a"
obj = DataFrame(
np.random.randn(len(index), K),
index=index,
columns=["A", "B", "C", "D", "E"],
)
obj["mix"] = "a"
if frame_or_series is Series:
obj = obj["A"]

exp_index = date_range("1/1/2001", end="12/31/2009", freq="A-DEC")
exp_index = exp_index + Timedelta(1, "D") - Timedelta(1, "ns")
result = df.to_timestamp("D", "end")
result = obj.to_timestamp("D", "end")
tm.assert_index_equal(result.index, exp_index)
tm.assert_numpy_array_equal(result.values, df.values)
tm.assert_numpy_array_equal(result.values, obj.values)
if frame_or_series is Series:
assert result.name == "A"

exp_index = date_range("1/1/2001", end="1/1/2009", freq="AS-JAN")
result = df.to_timestamp("D", "start")
result = obj.to_timestamp("D", "start")
tm.assert_index_equal(result.index, exp_index)

def _get_with_delta(delta, freq="A-DEC"):
return date_range(
to_datetime("1/1/2001") + delta,
to_datetime("12/31/2009") + delta,
freq=freq,
)
result = obj.to_timestamp(how="start")
tm.assert_index_equal(result.index, exp_index)

delta = timedelta(hours=23)
result = df.to_timestamp("H", "end")
result = obj.to_timestamp("H", "end")
exp_index = _get_with_delta(delta)
exp_index = exp_index + Timedelta(1, "h") - Timedelta(1, "ns")
tm.assert_index_equal(result.index, exp_index)

delta = timedelta(hours=23, minutes=59)
result = df.to_timestamp("T", "end")
result = obj.to_timestamp("T", "end")
exp_index = _get_with_delta(delta)
exp_index = exp_index + Timedelta(1, "m") - Timedelta(1, "ns")
tm.assert_index_equal(result.index, exp_index)

result = df.to_timestamp("S", "end")
result = obj.to_timestamp("S", "end")
delta = timedelta(hours=23, minutes=59, seconds=59)
exp_index = _get_with_delta(delta)
exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
tm.assert_index_equal(result.index, exp_index)

def test_to_timestamp_columns(self):
K = 5
index = period_range(freq="A", start="1/1/2001", end="12/1/2009")
df = DataFrame(
np.random.randn(len(index), K),
index=index,
columns=["A", "B", "C", "D", "E"],
)
df["mix"] = "a"

# columns
df = df.T

Expand Down Expand Up @@ -87,10 +111,6 @@ def _get_with_delta(delta, freq="A-DEC"):
exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
tm.assert_index_equal(result.columns, exp_index)

# invalid axis
with pytest.raises(ValueError, match="axis"):
df.to_timestamp(axis=2)

result1 = df.to_timestamp("5t", axis=1)
result2 = df.to_timestamp("t", axis=1)
expected = date_range("2001-01-01", "2009-01-01", freq="AS")
Expand All @@ -101,3 +121,34 @@ def _get_with_delta(delta, freq="A-DEC"):
# PeriodIndex.to_timestamp always use 'infer'
assert result1.columns.freqstr == "AS-JAN"
assert result2.columns.freqstr == "AS-JAN"

def to_timestamp_invalid_axis(self):
index = period_range(freq="A", start="1/1/2001", end="12/1/2009")
obj = DataFrame(np.random.randn(len(index), 5), index=index)

# invalid axis
with pytest.raises(ValueError, match="axis"):
obj.to_timestamp(axis=2)

def test_to_timestamp_hourly(self, frame_or_series):

index = period_range(freq="H", start="1/1/2001", end="1/2/2001")
obj = Series(1, index=index, name="foo")
if frame_or_series is not Series:
obj = obj.to_frame()

exp_index = date_range("1/1/2001 00:59:59", end="1/2/2001 00:59:59", freq="H")
result = obj.to_timestamp(how="end")
exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
tm.assert_index_equal(result.index, exp_index)
if frame_or_series is Series:
assert result.name == "foo"

def test_to_timestamp_raises(self, index, frame_or_series):
# GH#33327
obj = frame_or_series(index=index, dtype=object)

if not isinstance(index, PeriodIndex):
msg = f"unsupported Type {type(index).__name__}"
with pytest.raises(TypeError, match=msg):
obj.to_timestamp()
56 changes: 0 additions & 56 deletions pandas/tests/series/methods/test_to_period.py

This file was deleted.

Loading
0