Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/pandas/tests/api/__pycache__/test_api.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__init__.pyAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/common.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/conftest.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_array_ops.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_categorical.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_interval.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_numeric.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_object.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_period.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/arithmetic/common.pyAdded+155
- lib/python3.12/site-packages/pandas/tests/arithmetic/conftest.pyAdded+139
- lib/python3.12/site-packages/pandas/tests/arithmetic/test_array_ops.pyAdded+39
- lib/python3.12/site-packages/pandas/tests/arithmetic/test_categorical.pyAdded+25
- lib/python3.12/site-packages/pandas/tests/arithmetic/test_datetime64.pyAdded+2469
- lib/python3.12/site-packages/pandas/tests/arithmetic/test_interval.pyAdded+306
- lib/python3.12/site-packages/pandas/tests/arithmetic/test_numeric.pyAdded+1567
- lib/python3.12/site-packages/pandas/tests/arithmetic/test_object.pyAdded+420
- lib/python3.12/site-packages/pandas/tests/arithmetic/test_period.pyAdded+1675
- lib/python3.12/site-packages/pandas/tests/arithmetic/test_timedelta64.pyAdded+2179
- lib/python3.12/site-packages/pandas/tests/config/__init__.pyAdded
- lib/python3.12/site-packages/pandas/tests/config/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/config/__pycache__/test_config.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/config/__pycache__/test_localization.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/config/test_config.pyAdded+437
- lib/python3.12/site-packages/pandas/tests/config/test_localization.pyAdded+156
- lib/python3.12/site-packages/pandas/tests/copy_view/__init__.pyAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_array.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_astype.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_chained_assignment_deprecation.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_clip.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_constructors.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_core_functionalities.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_functions.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_indexing.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_internals.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_interp_fillna.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_replace.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_setitem.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_util.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/util.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/index/__init__.pyAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/test_datetimeindex.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/test_index.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/test_periodindex.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/test_timedeltaindex.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/copy_view/index/test_datetimeindex.pyAdded+69
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Assertion helpers for arithmetic tests."""import numpy as npimport pytest
from pandas import ( DataFrame, Index, Series, array,)import pandas._testing as tmfrom pandas.core.arrays import ( BooleanArray, NumpyExtensionArray,)
def assert_cannot_add(left, right, msg="cannot add"): """ Helper to assert that left and right cannot be added.
Parameters ---------- left : object right : object msg : str, default "cannot add" """ with pytest.raises(TypeError, match=msg): left + right with pytest.raises(TypeError, match=msg): right + left
def assert_invalid_addsub_type(left, right, msg=None): """ Helper to assert that left and right can be neither added nor subtracted.
Parameters ---------- left : object right : object msg : str or None, default None """ with pytest.raises(TypeError, match=msg): left + right with pytest.raises(TypeError, match=msg): right + left with pytest.raises(TypeError, match=msg): left - right with pytest.raises(TypeError, match=msg): right - left
def get_upcast_box(left, right, is_cmp: bool = False): """ Get the box to use for 'expected' in an arithmetic or comparison operation.
Parameters left : Any right : Any is_cmp : bool, default False Whether the operation is a comparison method. """
if isinstance(left, DataFrame) or isinstance(right, DataFrame): return DataFrame if isinstance(left, Series) or isinstance(right, Series): if is_cmp and isinstance(left, Index): # Index does not defer for comparisons return np.array return Series if isinstance(left, Index) or isinstance(right, Index): if is_cmp: return np.array return Index return tm.to_array
def assert_invalid_comparison(left, right, box): """ Assert that comparison operations with mismatched types behave correctly.
Parameters ---------- left : np.ndarray, ExtensionArray, Index, or Series right : object box : {pd.DataFrame, pd.Series, pd.Index, pd.array, tm.to_array} """ # Not for tznaive-tzaware comparison
# Note: not quite the same as how we do this for tm.box_expected xbox = box if box not in [Index, array] else np.array
def xbox2(x): # Eventually we'd like this to be tighter, but for now we'll # just exclude NumpyExtensionArray[bool] if isinstance(x, NumpyExtensionArray): return x._ndarray if isinstance(x, BooleanArray): # NB: we are assuming no pd.NAs for now return x.astype(bool) return x
# rev_box: box to use for reversed comparisons rev_box = xbox if isinstance(right, Index) and isinstance(left, Series): rev_box = np.array
result = xbox2(left == right) expected = xbox(np.zeros(result.shape, dtype=np.bool_))
tm.assert_equal(result, expected)
result = xbox2(right == left) tm.assert_equal(result, rev_box(expected))
result = xbox2(left != right) tm.assert_equal(result, ~expected)
result = xbox2(right != left) tm.assert_equal(result, rev_box(~expected))
msg = "|".join( [ "Invalid comparison between", "Cannot compare type", "not supported between", "invalid type promotion", ( # GH#36706 npdev 1.20.0 2020-09-28 r"The DTypes <class 'numpy.dtype\[datetime64\]'> and " r"<class 'numpy.dtype\[int64\]'> do not have a common DType. " "For example they cannot be stored in a single array unless the " "dtype is `object`." ), ] ) with pytest.raises(TypeError, match=msg): left < right with pytest.raises(TypeError, match=msg): left <= right with pytest.raises(TypeError, match=msg): left > right with pytest.raises(TypeError, match=msg): left >= right with pytest.raises(TypeError, match=msg): right < left with pytest.raises(TypeError, match=msg): right <= left with pytest.raises(TypeError, match=msg): right > left with pytest.raises(TypeError, match=msg): right >= left123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139import numpy as npimport pytest
import pandas as pdfrom pandas import Index
@pytest.fixture(params=[1, np.array(1, dtype=np.int64)])def one(request): """ Several variants of integer value 1. The zero-dim integer array behaves like an integer.
This fixture can be used to check that datetimelike indexes handle addition and subtraction of integers and zero-dimensional arrays of integers.
Examples -------- dti = pd.date_range('2016-01-01', periods=2, freq='h') dti DatetimeIndex(['2016-01-01 00:00:00', '2016-01-01 01:00:00'], dtype='datetime64[ns]', freq='h') dti + one DatetimeIndex(['2016-01-01 01:00:00', '2016-01-01 02:00:00'], dtype='datetime64[ns]', freq='h') """ return request.param
zeros = [ box_cls([0] * 5, dtype=dtype) for box_cls in [Index, np.array, pd.array] for dtype in [np.int64, np.uint64, np.float64]]zeros.extend([box_cls([-0.0] * 5, dtype=np.float64) for box_cls in [Index, np.array]])zeros.extend([np.array(0, dtype=dtype) for dtype in [np.int64, np.uint64, np.float64]])zeros.extend([np.array(-0.0, dtype=np.float64)])zeros.extend([0, 0.0, -0.0])
@pytest.fixture(params=zeros)def zero(request): """ Several types of scalar zeros and length 5 vectors of zeros.
This fixture can be used to check that numeric-dtype indexes handle division by any zero numeric-dtype.
Uses vector of length 5 for broadcasting with `numeric_idx` fixture, which creates numeric-dtype vectors also of length 5.
Examples -------- arr = RangeIndex(5) arr / zeros Index([nan, inf, inf, inf, inf], dtype='float64') """ return request.param
# ------------------------------------------------------------------# Scalar Fixtures
@pytest.fixture( params=[ pd.Timedelta("10m7s").to_pytimedelta(), pd.Timedelta("10m7s"), pd.Timedelta("10m7s").to_timedelta64(), ], ids=lambda x: type(x).__name__,)def scalar_td(request): """ Several variants of Timedelta scalars representing 10 minutes and 7 seconds. """ return request.param
@pytest.fixture( params=[ pd.offsets.Day(3), pd.offsets.Hour(72), pd.Timedelta(days=3).to_pytimedelta(), pd.Timedelta("72:00:00"), np.timedelta64(3, "D"), np.timedelta64(72, "h"), ], ids=lambda x: type(x).__name__,)def three_days(request): """ Several timedelta-like and DateOffset objects that each represent a 3-day timedelta """ return request.param
@pytest.fixture( params=[ pd.offsets.Hour(2), pd.offsets.Minute(120), pd.Timedelta(hours=2).to_pytimedelta(), pd.Timedelta(seconds=2 * 3600), np.timedelta64(2, "h"), np.timedelta64(120, "m"), ], ids=lambda x: type(x).__name__,)def two_hours(request): """ Several timedelta-like and DateOffset objects that each represent a 2-hour timedelta """ return request.param
_common_mismatch = [ pd.offsets.YearBegin(2), pd.offsets.MonthBegin(1), pd.offsets.Minute(),]
@pytest.fixture( params=[ np.timedelta64(4, "h"), pd.Timedelta(hours=23).to_pytimedelta(), pd.Timedelta("23:00:00"), ] + _common_mismatch)def not_daily(request): """ Several timedelta-like and DateOffset instances that are _not_ compatible with Daily frequencies. """ return request.param123456789101112131415161718192021222324252627282930313233343536373839import operator
import numpy as npimport pytest
import pandas._testing as tmfrom pandas.core.ops.array_ops import ( comparison_op, na_logical_op,)
def test_na_logical_op_2d(): left = np.arange(8).reshape(4, 2) right = left.astype(object) right[0, 0] = np.nan
# Check that we fall back to the vec_binop branch with pytest.raises(TypeError, match="unsupported operand type"): operator.or_(left, right)
result = na_logical_op(left, right, operator.or_) expected = right tm.assert_numpy_array_equal(result, expected)
def test_object_comparison_2d(): left = np.arange(9).reshape(3, 3).astype(object) right = left.T
result = comparison_op(left, right, operator.eq) expected = np.eye(3).astype(bool) tm.assert_numpy_array_equal(result, expected)
# Ensure that cython doesn't raise on non-writeable arg, which # we can get from np.broadcast_to right.flags.writeable = False result = comparison_op(left, right, operator.ne) tm.assert_numpy_array_equal(result, ~expected)12345678910111213141516171819202122232425import numpy as np
from pandas import ( Categorical, Series,)import pandas._testing as tm
class TestCategoricalComparisons: def test_categorical_nan_equality(self): cat = Series(Categorical(["a", "b", "c", np.nan])) expected = Series([True, True, True, False]) result = cat == cat tm.assert_series_equal(result, expected)
def test_categorical_tuple_equality(self): # GH 18050 ser = Series([(0, 0), (0, 1), (0, 0), (1, 0), (1, 1)]) expected = Series([True, False, True, False, False]) result = ser == (0, 0) tm.assert_series_equal(result, expected)
result = ser.astype("category") == (0, 0) tm.assert_series_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469# Arithmetic tests for DataFrame/Series/Index/Array classes that should# behave identically.# Specifically for datetime64 and datetime64tz dtypesfrom datetime import ( datetime, time, timedelta,)from itertools import ( product, starmap,)import operator
import numpy as npimport pytestimport pytz
from pandas._libs.tslibs.conversion import localize_pydatetimefrom pandas._libs.tslibs.offsets import shift_monthsfrom pandas.errors import PerformanceWarning
import pandas as pdfrom pandas import ( DateOffset, DatetimeIndex, NaT, Period, Series, Timedelta, TimedeltaIndex, Timestamp, date_range,)import pandas._testing as tmfrom pandas.core import roperatorfrom pandas.tests.arithmetic.common import ( assert_cannot_add, assert_invalid_addsub_type, assert_invalid_comparison, get_upcast_box,)
# ------------------------------------------------------------------# Comparisons
class TestDatetime64ArrayLikeComparisons: # Comparison tests for datetime64 vectors fully parametrized over # DataFrame/Series/DatetimeIndex/DatetimeArray. Ideally all comparison # tests will eventually end up here.
def test_compare_zerodim(self, tz_naive_fixture, box_with_array): # Test comparison with zero-dimensional array is unboxed tz = tz_naive_fixture box = box_with_array dti = date_range("20130101", periods=3, tz=tz)
other = np.array(dti.to_numpy()[0])
dtarr = tm.box_expected(dti, box) xbox = get_upcast_box(dtarr, other, True) result = dtarr <= other expected = np.array([True, False, False]) expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected)
@pytest.mark.parametrize( "other", [ "foo", -1, 99, 4.0, object(), timedelta(days=2), # GH#19800, GH#19301 datetime.date comparison raises to # match DatetimeIndex/Timestamp. This also matches the behavior # of stdlib datetime.datetime datetime(2001, 1, 1).date(), # GH#19301 None and NaN are *not* cast to NaT for comparisons None, np.nan, ], ) def test_dt64arr_cmp_scalar_invalid(self, other, tz_naive_fixture, box_with_array): # GH#22074, GH#15966 tz = tz_naive_fixture
rng = date_range("1/1/2000", periods=10, tz=tz) dtarr = tm.box_expected(rng, box_with_array) assert_invalid_comparison(dtarr, other, box_with_array)
@pytest.mark.parametrize( "other", [ # GH#4968 invalid date/int comparisons list(range(10)), np.arange(10), np.arange(10).astype(np.float32), np.arange(10).astype(object), pd.timedelta_range("1ns", periods=10).array, np.array(pd.timedelta_range("1ns", periods=10)), list(pd.timedelta_range("1ns", periods=10)), pd.timedelta_range("1 Day", periods=10).astype(object), pd.period_range("1971-01-01", freq="D", periods=10).array, pd.period_range("1971-01-01", freq="D", periods=10).astype(object), ], ) def test_dt64arr_cmp_arraylike_invalid( self, other, tz_naive_fixture, box_with_array ): tz = tz_naive_fixture
dta = date_range("1970-01-01", freq="ns", periods=10, tz=tz)._data obj = tm.box_expected(dta, box_with_array) assert_invalid_comparison(obj, other, box_with_array)
def test_dt64arr_cmp_mixed_invalid(self, tz_naive_fixture): tz = tz_naive_fixture
dta = date_range("1970-01-01", freq="h", periods=5, tz=tz)._data
other = np.array([0, 1, 2, dta[3], Timedelta(days=1)]) result = dta == other expected = np.array([False, False, False, True, False]) tm.assert_numpy_array_equal(result, expected)
result = dta != other tm.assert_numpy_array_equal(result, ~expected)
msg = "Invalid comparison between|Cannot compare type|not supported between" with pytest.raises(TypeError, match=msg): dta < other with pytest.raises(TypeError, match=msg): dta > other with pytest.raises(TypeError, match=msg): dta <= other with pytest.raises(TypeError, match=msg): dta >= other
def test_dt64arr_nat_comparison(self, tz_naive_fixture, box_with_array): # GH#22242, GH#22163 DataFrame considered NaT == ts incorrectly tz = tz_naive_fixture box = box_with_array
ts = Timestamp("2021-01-01", tz=tz) ser = Series([ts, NaT])
obj = tm.box_expected(ser, box) xbox = get_upcast_box(obj, ts, True)
expected = Series([True, False], dtype=np.bool_) expected = tm.box_expected(expected, xbox)
result = obj == ts tm.assert_equal(result, expected)
class TestDatetime64SeriesComparison: # TODO: moved from tests.series.test_operators; needs cleanup
@pytest.mark.parametrize( "pair", [ ( [Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")], [NaT, NaT, Timestamp("2011-01-03")], ), ( [Timedelta("1 days"), NaT, Timedelta("3 days")], [NaT, NaT, Timedelta("3 days")], ), ( [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")], [NaT, NaT, Period("2011-03", freq="M")], ), ], ) @pytest.mark.parametrize("reverse", [True, False]) @pytest.mark.parametrize("dtype", [None, object]) @pytest.mark.parametrize( "op, expected", [ (operator.eq, Series([False, False, True])), (operator.ne, Series([True, True, False])), (operator.lt, Series([False, False, False])), (operator.gt, Series([False, False, False])), (operator.ge, Series([False, False, True])), (operator.le, Series([False, False, True])), ], ) def test_nat_comparisons( self, dtype, index_or_series, reverse, pair, op, expected, ): box = index_or_series lhs, rhs = pair if reverse: # add lhs / rhs switched data lhs, rhs = rhs, lhs
left = Series(lhs, dtype=dtype) right = box(rhs, dtype=dtype)
result = op(left, right)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "data", [ [Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")], [Timedelta("1 days"), NaT, Timedelta("3 days")], [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")], ], ) @pytest.mark.parametrize("dtype", [None, object]) def test_nat_comparisons_scalar(self, dtype, data, box_with_array): box = box_with_array
left = Series(data, dtype=dtype) left = tm.box_expected(left, box) xbox = get_upcast_box(left, NaT, True)
expected = [False, False, False] expected = tm.box_expected(expected, xbox) if box is pd.array and dtype is object: expected = pd.array(expected, dtype="bool")
tm.assert_equal(left == NaT, expected) tm.assert_equal(NaT == left, expected)
expected = [True, True, True] expected = tm.box_expected(expected, xbox) if box is pd.array and dtype is object: expected = pd.array(expected, dtype="bool") tm.assert_equal(left != NaT, expected) tm.assert_equal(NaT != left, expected)
expected = [False, False, False] expected = tm.box_expected(expected, xbox) if box is pd.array and dtype is object: expected = pd.array(expected, dtype="bool") tm.assert_equal(left < NaT, expected) tm.assert_equal(NaT > left, expected) tm.assert_equal(left <= NaT, expected) tm.assert_equal(NaT >= left, expected)
tm.assert_equal(left > NaT, expected) tm.assert_equal(NaT < left, expected) tm.assert_equal(left >= NaT, expected) tm.assert_equal(NaT <= left, expected)
@pytest.mark.parametrize("val", [datetime(2000, 1, 4), datetime(2000, 1, 5)]) def test_series_comparison_scalars(self, val): series = Series(date_range("1/1/2000", periods=10))
result = series > val expected = Series([x > val for x in series]) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "left,right", [("lt", "gt"), ("le", "ge"), ("eq", "eq"), ("ne", "ne")] ) def test_timestamp_compare_series(self, left, right): # see gh-4982 # Make sure we can compare Timestamps on the right AND left hand side. ser = Series(date_range("20010101", periods=10), name="dates") s_nat = ser.copy(deep=True)
ser[0] = Timestamp("nat") ser[3] = Timestamp("nat")
left_f = getattr(operator, left) right_f = getattr(operator, right)
# No NaT expected = left_f(ser, Timestamp("20010109")) result = right_f(Timestamp("20010109"), ser) tm.assert_series_equal(result, expected)
# NaT expected = left_f(ser, Timestamp("nat")) result = right_f(Timestamp("nat"), ser) tm.assert_series_equal(result, expected)
# Compare to Timestamp with series containing NaT expected = left_f(s_nat, Timestamp("20010109")) result = right_f(Timestamp("20010109"), s_nat) tm.assert_series_equal(result, expected)
# Compare to NaT with series containing NaT expected = left_f(s_nat, NaT) result = right_f(NaT, s_nat) tm.assert_series_equal(result, expected)
def test_dt64arr_timestamp_equality(self, box_with_array): # GH#11034 box = box_with_array
ser = Series([Timestamp("2000-01-29 01:59:00"), Timestamp("2000-01-30"), NaT]) ser = tm.box_expected(ser, box) xbox = get_upcast_box(ser, ser, True)
result = ser != ser expected = tm.box_expected([False, False, True], xbox) tm.assert_equal(result, expected)
if box is pd.DataFrame: # alignment for frame vs series comparisons deprecated # in GH#46795 enforced 2.0 with pytest.raises(ValueError, match="not aligned"): ser != ser[0]
else: result = ser != ser[0] expected = tm.box_expected([False, True, True], xbox) tm.assert_equal(result, expected)
if box is pd.DataFrame: # alignment for frame vs series comparisons deprecated # in GH#46795 enforced 2.0 with pytest.raises(ValueError, match="not aligned"): ser != ser[2] else: result = ser != ser[2] expected = tm.box_expected([True, True, True], xbox) tm.assert_equal(result, expected)
result = ser == ser expected = tm.box_expected([True, True, False], xbox) tm.assert_equal(result, expected)
if box is pd.DataFrame: # alignment for frame vs series comparisons deprecated # in GH#46795 enforced 2.0 with pytest.raises(ValueError, match="not aligned"): ser == ser[0] else: result = ser == ser[0] expected = tm.box_expected([True, False, False], xbox) tm.assert_equal(result, expected)
if box is pd.DataFrame: # alignment for frame vs series comparisons deprecated # in GH#46795 enforced 2.0 with pytest.raises(ValueError, match="not aligned"): ser == ser[2] else: result = ser == ser[2] expected = tm.box_expected([False, False, False], xbox) tm.assert_equal(result, expected)
@pytest.mark.parametrize( "datetimelike", [ Timestamp("20130101"), datetime(2013, 1, 1), np.datetime64("2013-01-01T00:00", "ns"), ], ) @pytest.mark.parametrize( "op,expected", [ (operator.lt, [True, False, False, False]), (operator.le, [True, True, False, False]), (operator.eq, [False, True, False, False]), (operator.gt, [False, False, False, True]), ], ) def test_dt64_compare_datetime_scalar(self, datetimelike, op, expected): # GH#17965, test for ability to compare datetime64[ns] columns # to datetimelike ser = Series( [ Timestamp("20120101"), Timestamp("20130101"), np.nan, Timestamp("20130103"), ], name="A", ) result = op(ser, datetimelike) expected = Series(expected, name="A") tm.assert_series_equal(result, expected)
class TestDatetimeIndexComparisons: # TODO: moved from tests.indexes.test_base; parametrize and de-duplicate def test_comparators(self, comparison_op): index = date_range("2020-01-01", periods=10) element = index[len(index) // 2] element = Timestamp(element).to_datetime64()
arr = np.array(index) arr_result = comparison_op(arr, element) index_result = comparison_op(index, element)
assert isinstance(index_result, np.ndarray) tm.assert_numpy_array_equal(arr_result, index_result)
@pytest.mark.parametrize( "other", [datetime(2016, 1, 1), Timestamp("2016-01-01"), np.datetime64("2016-01-01")], ) def test_dti_cmp_datetimelike(self, other, tz_naive_fixture): tz = tz_naive_fixture dti = date_range("2016-01-01", periods=2, tz=tz) if tz is not None: if isinstance(other, np.datetime64): pytest.skip(f"{type(other).__name__} is not tz aware") other = localize_pydatetime(other, dti.tzinfo)
result = dti == other expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected)
result = dti > other expected = np.array([False, True]) tm.assert_numpy_array_equal(result, expected)
result = dti >= other expected = np.array([True, True]) tm.assert_numpy_array_equal(result, expected)
result = dti < other expected = np.array([False, False]) tm.assert_numpy_array_equal(result, expected)
result = dti <= other expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("dtype", [None, object]) def test_dti_cmp_nat(self, dtype, box_with_array): left = DatetimeIndex([Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")]) right = DatetimeIndex([NaT, NaT, Timestamp("2011-01-03")])
left = tm.box_expected(left, box_with_array) right = tm.box_expected(right, box_with_array) xbox = get_upcast_box(left, right, True)
lhs, rhs = left, right if dtype is object: lhs, rhs = left.astype(object), right.astype(object)
result = rhs == lhs expected = np.array([False, False, True]) expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected)
result = lhs != rhs expected = np.array([True, True, False]) expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected)
expected = np.array([False, False, False]) expected = tm.box_expected(expected, xbox) tm.assert_equal(lhs == NaT, expected) tm.assert_equal(NaT == rhs, expected)
expected = np.array([True, True, True]) expected = tm.box_expected(expected, xbox) tm.assert_equal(lhs != NaT, expected) tm.assert_equal(NaT != lhs, expected)
expected = np.array([False, False, False]) expected = tm.box_expected(expected, xbox) tm.assert_equal(lhs < NaT, expected) tm.assert_equal(NaT > lhs, expected)
def test_dti_cmp_nat_behaves_like_float_cmp_nan(self): fidx1 = pd.Index([1.0, np.nan, 3.0, np.nan, 5.0, 7.0]) fidx2 = pd.Index([2.0, 3.0, np.nan, np.nan, 6.0, 7.0])
didx1 = DatetimeIndex( ["2014-01-01", NaT, "2014-03-01", NaT, "2014-05-01", "2014-07-01"] ) didx2 = DatetimeIndex( ["2014-02-01", "2014-03-01", NaT, NaT, "2014-06-01", "2014-07-01"] ) darr = np.array( [ np.datetime64("2014-02-01 00:00"), np.datetime64("2014-03-01 00:00"), np.datetime64("nat"), np.datetime64("nat"), np.datetime64("2014-06-01 00:00"), np.datetime64("2014-07-01 00:00"), ] )
cases = [(fidx1, fidx2), (didx1, didx2), (didx1, darr)]
# Check pd.NaT is handles as the same as np.nan with tm.assert_produces_warning(None): for idx1, idx2 in cases: result = idx1 < idx2 expected = np.array([True, False, False, False, True, False]) tm.assert_numpy_array_equal(result, expected)
result = idx2 > idx1 expected = np.array([True, False, False, False, True, False]) tm.assert_numpy_array_equal(result, expected)
result = idx1 <= idx2 expected = np.array([True, False, False, False, True, True]) tm.assert_numpy_array_equal(result, expected)
result = idx2 >= idx1 expected = np.array([True, False, False, False, True, True]) tm.assert_numpy_array_equal(result, expected)
result = idx1 == idx2 expected = np.array([False, False, False, False, False, True]) tm.assert_numpy_array_equal(result, expected)
result = idx1 != idx2 expected = np.array([True, True, True, True, True, False]) tm.assert_numpy_array_equal(result, expected)
with tm.assert_produces_warning(None): for idx1, val in [(fidx1, np.nan), (didx1, NaT)]: result = idx1 < val expected = np.array([False, False, False, False, False, False]) tm.assert_numpy_array_equal(result, expected) result = idx1 > val tm.assert_numpy_array_equal(result, expected)
result = idx1 <= val tm.assert_numpy_array_equal(result, expected) result = idx1 >= val tm.assert_numpy_array_equal(result, expected)
result = idx1 == val tm.assert_numpy_array_equal(result, expected)
result = idx1 != val expected = np.array([True, True, True, True, True, True]) tm.assert_numpy_array_equal(result, expected)
# Check pd.NaT is handles as the same as np.nan with tm.assert_produces_warning(None): for idx1, val in [(fidx1, 3), (didx1, datetime(2014, 3, 1))]: result = idx1 < val expected = np.array([True, False, False, False, False, False]) tm.assert_numpy_array_equal(result, expected) result = idx1 > val expected = np.array([False, False, False, False, True, True]) tm.assert_numpy_array_equal(result, expected)
result = idx1 <= val expected = np.array([True, False, True, False, False, False]) tm.assert_numpy_array_equal(result, expected) result = idx1 >= val expected = np.array([False, False, True, False, True, True]) tm.assert_numpy_array_equal(result, expected)
result = idx1 == val expected = np.array([False, False, True, False, False, False]) tm.assert_numpy_array_equal(result, expected)
result = idx1 != val expected = np.array([True, True, False, True, True, True]) tm.assert_numpy_array_equal(result, expected)
def test_comparison_tzawareness_compat(self, comparison_op, box_with_array): # GH#18162 op = comparison_op box = box_with_array
dr = date_range("2016-01-01", periods=6) dz = dr.tz_localize("US/Pacific")
dr = tm.box_expected(dr, box) dz = tm.box_expected(dz, box)
if box is pd.DataFrame: tolist = lambda x: x.astype(object).values.tolist()[0] else: tolist = list
if op not in [operator.eq, operator.ne]: msg = ( r"Invalid comparison between dtype=datetime64\[ns.*\] " "and (Timestamp|DatetimeArray|list|ndarray)" ) with pytest.raises(TypeError, match=msg): op(dr, dz)
with pytest.raises(TypeError, match=msg): op(dr, tolist(dz)) with pytest.raises(TypeError, match=msg): op(dr, np.array(tolist(dz), dtype=object)) with pytest.raises(TypeError, match=msg): op(dz, dr)
with pytest.raises(TypeError, match=msg): op(dz, tolist(dr)) with pytest.raises(TypeError, match=msg): op(dz, np.array(tolist(dr), dtype=object))
# The aware==aware and naive==naive comparisons should *not* raise assert np.all(dr == dr) assert np.all(dr == tolist(dr)) assert np.all(tolist(dr) == dr) assert np.all(np.array(tolist(dr), dtype=object) == dr) assert np.all(dr == np.array(tolist(dr), dtype=object))
assert np.all(dz == dz) assert np.all(dz == tolist(dz)) assert np.all(tolist(dz) == dz) assert np.all(np.array(tolist(dz), dtype=object) == dz) assert np.all(dz == np.array(tolist(dz), dtype=object))
def test_comparison_tzawareness_compat_scalars(self, comparison_op, box_with_array): # GH#18162 op = comparison_op
dr = date_range("2016-01-01", periods=6) dz = dr.tz_localize("US/Pacific")
dr = tm.box_expected(dr, box_with_array) dz = tm.box_expected(dz, box_with_array)
# Check comparisons against scalar Timestamps ts = Timestamp("2000-03-14 01:59") ts_tz = Timestamp("2000-03-14 01:59", tz="Europe/Amsterdam")
assert np.all(dr > ts) msg = r"Invalid comparison between dtype=datetime64\[ns.*\] and Timestamp" if op not in [operator.eq, operator.ne]: with pytest.raises(TypeError, match=msg): op(dr, ts_tz)
assert np.all(dz > ts_tz) if op not in [operator.eq, operator.ne]: with pytest.raises(TypeError, match=msg): op(dz, ts)
if op not in [operator.eq, operator.ne]: # GH#12601: Check comparison against Timestamps and DatetimeIndex with pytest.raises(TypeError, match=msg): op(ts, dz)
@pytest.mark.parametrize( "other", [datetime(2016, 1, 1), Timestamp("2016-01-01"), np.datetime64("2016-01-01")], ) # Bug in NumPy? https://github.com/numpy/numpy/issues/13841 # Raising in __eq__ will fallback to NumPy, which warns, fails, # then re-raises the original exception. So we just need to ignore. @pytest.mark.filterwarnings("ignore:elementwise comp:DeprecationWarning") def test_scalar_comparison_tzawareness( self, comparison_op, other, tz_aware_fixture, box_with_array ): op = comparison_op tz = tz_aware_fixture dti = date_range("2016-01-01", periods=2, tz=tz)
dtarr = tm.box_expected(dti, box_with_array) xbox = get_upcast_box(dtarr, other, True) if op in [operator.eq, operator.ne]: exbool = op is operator.ne expected = np.array([exbool, exbool], dtype=bool) expected = tm.box_expected(expected, xbox)
result = op(dtarr, other) tm.assert_equal(result, expected)
result = op(other, dtarr) tm.assert_equal(result, expected) else: msg = ( r"Invalid comparison between dtype=datetime64\[ns, .*\] " f"and {type(other).__name__}" ) with pytest.raises(TypeError, match=msg): op(dtarr, other) with pytest.raises(TypeError, match=msg): op(other, dtarr)
def test_nat_comparison_tzawareness(self, comparison_op): # GH#19276 # tzaware DatetimeIndex should not raise when compared to NaT op = comparison_op
dti = DatetimeIndex( ["2014-01-01", NaT, "2014-03-01", NaT, "2014-05-01", "2014-07-01"] ) expected = np.array([op == operator.ne] * len(dti)) result = op(dti, NaT) tm.assert_numpy_array_equal(result, expected)
result = op(dti.tz_localize("US/Pacific"), NaT) tm.assert_numpy_array_equal(result, expected)
def test_dti_cmp_str(self, tz_naive_fixture): # GH#22074 # regardless of tz, we expect these comparisons are valid tz = tz_naive_fixture rng = date_range("1/1/2000", periods=10, tz=tz) other = "1/1/2000"
result = rng == other expected = np.array([True] + [False] * 9) tm.assert_numpy_array_equal(result, expected)
result = rng != other expected = np.array([False] + [True] * 9) tm.assert_numpy_array_equal(result, expected)
result = rng < other expected = np.array([False] * 10) tm.assert_numpy_array_equal(result, expected)
result = rng <= other expected = np.array([True] + [False] * 9) tm.assert_numpy_array_equal(result, expected)
result = rng > other expected = np.array([False] + [True] * 9) tm.assert_numpy_array_equal(result, expected)
result = rng >= other expected = np.array([True] * 10) tm.assert_numpy_array_equal(result, expected)
def test_dti_cmp_list(self): rng = date_range("1/1/2000", periods=10)
result = rng == list(rng) expected = rng == rng tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize( "other", [ pd.timedelta_range("1D", periods=10), pd.timedelta_range("1D", periods=10).to_series(), pd.timedelta_range("1D", periods=10).asi8.view("m8[ns]"), ], ids=lambda x: type(x).__name__, ) def test_dti_cmp_tdi_tzawareness(self, other): # GH#22074 # reversion test that we _don't_ call _assert_tzawareness_compat # when comparing against TimedeltaIndex dti = date_range("2000-01-01", periods=10, tz="Asia/Tokyo")
result = dti == other expected = np.array([False] * 10) tm.assert_numpy_array_equal(result, expected)
result = dti != other expected = np.array([True] * 10) tm.assert_numpy_array_equal(result, expected) msg = "Invalid comparison between" with pytest.raises(TypeError, match=msg): dti < other with pytest.raises(TypeError, match=msg): dti <= other with pytest.raises(TypeError, match=msg): dti > other with pytest.raises(TypeError, match=msg): dti >= other
def test_dti_cmp_object_dtype(self): # GH#22074 dti = date_range("2000-01-01", periods=10, tz="Asia/Tokyo")
other = dti.astype("O")
result = dti == other expected = np.array([True] * 10) tm.assert_numpy_array_equal(result, expected)
other = dti.tz_localize(None) result = dti != other tm.assert_numpy_array_equal(result, expected)
other = np.array(list(dti[:5]) + [Timedelta(days=1)] * 5) result = dti == other expected = np.array([True] * 5 + [False] * 5) tm.assert_numpy_array_equal(result, expected) msg = ">=' not supported between instances of 'Timestamp' and 'Timedelta'" with pytest.raises(TypeError, match=msg): dti >= other
# ------------------------------------------------------------------# Arithmetic
class TestDatetime64Arithmetic: # This class is intended for "finished" tests that are fully parametrized # over DataFrame/Series/Index/DatetimeArray
# ------------------------------------------------------------- # Addition/Subtraction of timedelta-like
@pytest.mark.arm_slow def test_dt64arr_add_timedeltalike_scalar( self, tz_naive_fixture, two_hours, box_with_array ): # GH#22005, GH#22163 check DataFrame doesn't raise TypeError tz = tz_naive_fixture
rng = date_range("2000-01-01", "2000-02-01", tz=tz) expected = date_range("2000-01-01 02:00", "2000-02-01 02:00", tz=tz)
rng = tm.box_expected(rng, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = rng + two_hours tm.assert_equal(result, expected)
result = two_hours + rng tm.assert_equal(result, expected)
rng += two_hours tm.assert_equal(rng, expected)
def test_dt64arr_sub_timedeltalike_scalar( self, tz_naive_fixture, two_hours, box_with_array ): tz = tz_naive_fixture
rng = date_range("2000-01-01", "2000-02-01", tz=tz) expected = date_range("1999-12-31 22:00", "2000-01-31 22:00", tz=tz)
rng = tm.box_expected(rng, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = rng - two_hours tm.assert_equal(result, expected)
rng -= two_hours tm.assert_equal(rng, expected)
def test_dt64_array_sub_dt_with_different_timezone(self, box_with_array): t1 = date_range("20130101", periods=3).tz_localize("US/Eastern") t1 = tm.box_expected(t1, box_with_array) t2 = Timestamp("20130101").tz_localize("CET") tnaive = Timestamp(20130101)
result = t1 - t2 expected = TimedeltaIndex( ["0 days 06:00:00", "1 days 06:00:00", "2 days 06:00:00"] ) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
result = t2 - t1 expected = TimedeltaIndex( ["-1 days +18:00:00", "-2 days +18:00:00", "-3 days +18:00:00"] ) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
msg = "Cannot subtract tz-naive and tz-aware datetime-like objects" with pytest.raises(TypeError, match=msg): t1 - tnaive
with pytest.raises(TypeError, match=msg): tnaive - t1
def test_dt64_array_sub_dt64_array_with_different_timezone(self, box_with_array): t1 = date_range("20130101", periods=3).tz_localize("US/Eastern") t1 = tm.box_expected(t1, box_with_array) t2 = date_range("20130101", periods=3).tz_localize("CET") t2 = tm.box_expected(t2, box_with_array) tnaive = date_range("20130101", periods=3)
result = t1 - t2 expected = TimedeltaIndex( ["0 days 06:00:00", "0 days 06:00:00", "0 days 06:00:00"] ) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
result = t2 - t1 expected = TimedeltaIndex( ["-1 days +18:00:00", "-1 days +18:00:00", "-1 days +18:00:00"] ) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
msg = "Cannot subtract tz-naive and tz-aware datetime-like objects" with pytest.raises(TypeError, match=msg): t1 - tnaive
with pytest.raises(TypeError, match=msg): tnaive - t1
def test_dt64arr_add_sub_td64_nat(self, box_with_array, tz_naive_fixture): # GH#23320 special handling for timedelta64("NaT") tz = tz_naive_fixture
dti = date_range("1994-04-01", periods=9, tz=tz, freq="QS") other = np.timedelta64("NaT") expected = DatetimeIndex(["NaT"] * 9, tz=tz).as_unit("ns")
obj = tm.box_expected(dti, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = obj + other tm.assert_equal(result, expected) result = other + obj tm.assert_equal(result, expected) result = obj - other tm.assert_equal(result, expected) msg = "cannot subtract" with pytest.raises(TypeError, match=msg): other - obj
def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array): tz = tz_naive_fixture dti = date_range("2016-01-01", periods=3, tz=tz) tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) tdarr = tdi.values
expected = date_range("2015-12-31", "2016-01-02", periods=3, tz=tz)
dtarr = tm.box_expected(dti, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = dtarr + tdarr tm.assert_equal(result, expected) result = tdarr + dtarr tm.assert_equal(result, expected)
expected = date_range("2016-01-02", "2016-01-04", periods=3, tz=tz) expected = tm.box_expected(expected, box_with_array)
result = dtarr - tdarr tm.assert_equal(result, expected) msg = "cannot subtract|(bad|unsupported) operand type for unary" with pytest.raises(TypeError, match=msg): tdarr - dtarr
# ----------------------------------------------------------------- # Subtraction of datetime-like scalars
@pytest.mark.parametrize( "ts", [ Timestamp("2013-01-01"), Timestamp("2013-01-01").to_pydatetime(), Timestamp("2013-01-01").to_datetime64(), # GH#7996, GH#22163 ensure non-nano datetime64 is converted to nano # for DataFrame operation np.datetime64("2013-01-01", "D"), ], ) def test_dt64arr_sub_dtscalar(self, box_with_array, ts): # GH#8554, GH#22163 DataFrame op should _not_ return dt64 dtype idx = date_range("2013-01-01", periods=3)._with_freq(None) idx = tm.box_expected(idx, box_with_array)
expected = TimedeltaIndex(["0 Days", "1 Day", "2 Days"]) expected = tm.box_expected(expected, box_with_array)
result = idx - ts tm.assert_equal(result, expected)
result = ts - idx tm.assert_equal(result, -expected) tm.assert_equal(result, -expected)
def test_dt64arr_sub_timestamp_tzaware(self, box_with_array): ser = date_range("2014-03-17", periods=2, freq="D", tz="US/Eastern") ser = ser._with_freq(None) ts = ser[0]
ser = tm.box_expected(ser, box_with_array)
delta_series = Series([np.timedelta64(0, "D"), np.timedelta64(1, "D")]) expected = tm.box_expected(delta_series, box_with_array)
tm.assert_equal(ser - ts, expected) tm.assert_equal(ts - ser, -expected)
def test_dt64arr_sub_NaT(self, box_with_array, unit): # GH#18808 dti = DatetimeIndex([NaT, Timestamp("19900315")]).as_unit(unit) ser = tm.box_expected(dti, box_with_array)
result = ser - NaT expected = Series([NaT, NaT], dtype=f"timedelta64[{unit}]") expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
dti_tz = dti.tz_localize("Asia/Tokyo") ser_tz = tm.box_expected(dti_tz, box_with_array)
result = ser_tz - NaT expected = Series([NaT, NaT], dtype=f"timedelta64[{unit}]") expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
# ------------------------------------------------------------- # Subtraction of datetime-like array-like
def test_dt64arr_sub_dt64object_array(self, box_with_array, tz_naive_fixture): dti = date_range("2016-01-01", periods=3, tz=tz_naive_fixture) expected = dti - dti
obj = tm.box_expected(dti, box_with_array) expected = tm.box_expected(expected, box_with_array).astype(object)
with tm.assert_produces_warning(PerformanceWarning): result = obj - obj.astype(object) tm.assert_equal(result, expected)
def test_dt64arr_naive_sub_dt64ndarray(self, box_with_array): dti = date_range("2016-01-01", periods=3, tz=None) dt64vals = dti.values
dtarr = tm.box_expected(dti, box_with_array)
expected = dtarr - dtarr result = dtarr - dt64vals tm.assert_equal(result, expected) result = dt64vals - dtarr tm.assert_equal(result, expected)
def test_dt64arr_aware_sub_dt64ndarray_raises( self, tz_aware_fixture, box_with_array ): tz = tz_aware_fixture dti = date_range("2016-01-01", periods=3, tz=tz) dt64vals = dti.values
dtarr = tm.box_expected(dti, box_with_array) msg = "Cannot subtract tz-naive and tz-aware datetime" with pytest.raises(TypeError, match=msg): dtarr - dt64vals with pytest.raises(TypeError, match=msg): dt64vals - dtarr
# ------------------------------------------------------------- # Addition of datetime-like others (invalid)
def test_dt64arr_add_dtlike_raises(self, tz_naive_fixture, box_with_array): # GH#22163 ensure DataFrame doesn't cast Timestamp to i8 # GH#9631 tz = tz_naive_fixture
dti = date_range("2016-01-01", periods=3, tz=tz) if tz is None: dti2 = dti.tz_localize("US/Eastern") else: dti2 = dti.tz_localize(None) dtarr = tm.box_expected(dti, box_with_array)
assert_cannot_add(dtarr, dti.values) assert_cannot_add(dtarr, dti) assert_cannot_add(dtarr, dtarr) assert_cannot_add(dtarr, dti[0]) assert_cannot_add(dtarr, dti[0].to_pydatetime()) assert_cannot_add(dtarr, dti[0].to_datetime64()) assert_cannot_add(dtarr, dti2[0]) assert_cannot_add(dtarr, dti2[0].to_pydatetime()) assert_cannot_add(dtarr, np.datetime64("2011-01-01", "D"))
# ------------------------------------------------------------- # Other Invalid Addition/Subtraction
# Note: freq here includes both Tick and non-Tick offsets; this is # relevant because historically integer-addition was allowed if we had # a freq. @pytest.mark.parametrize("freq", ["h", "D", "W", "2ME", "MS", "QE", "B", None]) @pytest.mark.parametrize("dtype", [None, "uint8"]) def test_dt64arr_addsub_intlike( self, request, dtype, index_or_series_or_array, freq, tz_naive_fixture ): # GH#19959, GH#19123, GH#19012 # GH#55860 use index_or_series_or_array instead of box_with_array # bc DataFrame alignment makes it inapplicable tz = tz_naive_fixture
if freq is None: dti = DatetimeIndex(["NaT", "2017-04-05 06:07:08"], tz=tz) else: dti = date_range("2016-01-01", periods=2, freq=freq, tz=tz)
obj = index_or_series_or_array(dti) other = np.array([4, -1]) if dtype is not None: other = other.astype(dtype)
msg = "|".join( [ "Addition/subtraction of integers", "cannot subtract DatetimeArray from", # IntegerArray "can only perform ops with numeric values", "unsupported operand type.*Categorical", r"unsupported operand type\(s\) for -: 'int' and 'Timestamp'", ] ) assert_invalid_addsub_type(obj, 1, msg) assert_invalid_addsub_type(obj, np.int64(2), msg) assert_invalid_addsub_type(obj, np.array(3, dtype=np.int64), msg) assert_invalid_addsub_type(obj, other, msg) assert_invalid_addsub_type(obj, np.array(other), msg) assert_invalid_addsub_type(obj, pd.array(other), msg) assert_invalid_addsub_type(obj, pd.Categorical(other), msg) assert_invalid_addsub_type(obj, pd.Index(other), msg) assert_invalid_addsub_type(obj, Series(other), msg)
@pytest.mark.parametrize( "other", [ 3.14, np.array([2.0, 3.0]), # GH#13078 datetime +/- Period is invalid Period("2011-01-01", freq="D"), # https://github.com/pandas-dev/pandas/issues/10329 time(1, 2, 3), ], ) @pytest.mark.parametrize("dti_freq", [None, "D"]) def test_dt64arr_add_sub_invalid(self, dti_freq, other, box_with_array): dti = DatetimeIndex(["2011-01-01", "2011-01-02"], freq=dti_freq) dtarr = tm.box_expected(dti, box_with_array) msg = "|".join( [ "unsupported operand type", "cannot (add|subtract)", "cannot use operands with types", "ufunc '?(add|subtract)'? cannot use operands with types", "Concatenation operation is not implemented for NumPy arrays", ] ) assert_invalid_addsub_type(dtarr, other, msg)
@pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "h"]) @pytest.mark.parametrize("dti_freq", [None, "D"]) def test_dt64arr_add_sub_parr( self, dti_freq, pi_freq, box_with_array, box_with_array2 ): # GH#20049 subtracting PeriodIndex should raise TypeError dti = DatetimeIndex(["2011-01-01", "2011-01-02"], freq=dti_freq) pi = dti.to_period(pi_freq)
dtarr = tm.box_expected(dti, box_with_array) parr = tm.box_expected(pi, box_with_array2) msg = "|".join( [ "cannot (add|subtract)", "unsupported operand", "descriptor.*requires", "ufunc.*cannot use operands", ] ) assert_invalid_addsub_type(dtarr, parr, msg)
@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") def test_dt64arr_addsub_time_objects_raises(self, box_with_array, tz_naive_fixture): # https://github.com/pandas-dev/pandas/issues/10329
tz = tz_naive_fixture
obj1 = date_range("2012-01-01", periods=3, tz=tz) obj2 = [time(i, i, i) for i in range(3)]
obj1 = tm.box_expected(obj1, box_with_array) obj2 = tm.box_expected(obj2, box_with_array)
msg = "|".join( [ "unsupported operand", "cannot subtract DatetimeArray from ndarray", ] ) # pandas.errors.PerformanceWarning: Non-vectorized DateOffset being # applied to Series or DatetimeIndex # we aren't testing that here, so ignore. assert_invalid_addsub_type(obj1, obj2, msg=msg)
# ------------------------------------------------------------- # Other invalid operations
@pytest.mark.parametrize( "dt64_series", [ Series([Timestamp("19900315"), Timestamp("19900315")]), Series([NaT, Timestamp("19900315")]), Series([NaT, NaT], dtype="datetime64[ns]"), ], ) @pytest.mark.parametrize("one", [1, 1.0, np.array(1)]) def test_dt64_mul_div_numeric_invalid(self, one, dt64_series, box_with_array): obj = tm.box_expected(dt64_series, box_with_array)
msg = "cannot perform .* with this index type"
# multiplication with pytest.raises(TypeError, match=msg): obj * one with pytest.raises(TypeError, match=msg): one * obj
# division with pytest.raises(TypeError, match=msg): obj / one with pytest.raises(TypeError, match=msg): one / obj
class TestDatetime64DateOffsetArithmetic: # ------------------------------------------------------------- # Tick DateOffsets
# TODO: parametrize over timezone? @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) def test_dt64arr_series_add_tick_DateOffset(self, box_with_array, unit): # GH#4532 # operate with pd.offsets ser = Series( [Timestamp("20130101 9:01"), Timestamp("20130101 9:02")] ).dt.as_unit(unit) expected = Series( [Timestamp("20130101 9:01:05"), Timestamp("20130101 9:02:05")] ).dt.as_unit(unit)
ser = tm.box_expected(ser, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = ser + pd.offsets.Second(5) tm.assert_equal(result, expected)
result2 = pd.offsets.Second(5) + ser tm.assert_equal(result2, expected)
def test_dt64arr_series_sub_tick_DateOffset(self, box_with_array): # GH#4532 # operate with pd.offsets ser = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")]) expected = Series( [Timestamp("20130101 9:00:55"), Timestamp("20130101 9:01:55")] )
ser = tm.box_expected(ser, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = ser - pd.offsets.Second(5) tm.assert_equal(result, expected)
result2 = -pd.offsets.Second(5) + ser tm.assert_equal(result2, expected) msg = "(bad|unsupported) operand type for unary" with pytest.raises(TypeError, match=msg): pd.offsets.Second(5) - ser
@pytest.mark.parametrize( "cls_name", ["Day", "Hour", "Minute", "Second", "Milli", "Micro", "Nano"] ) def test_dt64arr_add_sub_tick_DateOffset_smoke(self, cls_name, box_with_array): # GH#4532 # smoke tests for valid DateOffsets ser = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")]) ser = tm.box_expected(ser, box_with_array)
offset_cls = getattr(pd.offsets, cls_name) ser + offset_cls(5) offset_cls(5) + ser ser - offset_cls(5)
def test_dti_add_tick_tzaware(self, tz_aware_fixture, box_with_array): # GH#21610, GH#22163 ensure DataFrame doesn't return object-dtype tz = tz_aware_fixture if tz == "US/Pacific": dates = date_range("2012-11-01", periods=3, tz=tz) offset = dates + pd.offsets.Hour(5) assert dates[0] + pd.offsets.Hour(5) == offset[0]
dates = date_range("2010-11-01 00:00", periods=3, tz=tz, freq="h") expected = DatetimeIndex( ["2010-11-01 05:00", "2010-11-01 06:00", "2010-11-01 07:00"], freq="h", tz=tz, ).as_unit("ns")
dates = tm.box_expected(dates, box_with_array) expected = tm.box_expected(expected, box_with_array)
for scalar in [pd.offsets.Hour(5), np.timedelta64(5, "h"), timedelta(hours=5)]: offset = dates + scalar tm.assert_equal(offset, expected) offset = scalar + dates tm.assert_equal(offset, expected)
roundtrip = offset - scalar tm.assert_equal(roundtrip, dates)
msg = "|".join( ["bad operand type for unary -", "cannot subtract DatetimeArray"] ) with pytest.raises(TypeError, match=msg): scalar - dates
# ------------------------------------------------------------- # RelativeDelta DateOffsets
@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array, unit): # GH#10699 vec = DatetimeIndex( [ Timestamp("2000-01-05 00:15:00"), Timestamp("2000-01-31 00:23:00"), Timestamp("2000-01-01"), Timestamp("2000-03-31"), Timestamp("2000-02-29"), Timestamp("2000-12-31"), Timestamp("2000-05-15"), Timestamp("2001-06-15"), ] ).as_unit(unit) vec = tm.box_expected(vec, box_with_array) vec_items = vec.iloc[0] if box_with_array is pd.DataFrame else vec
# DateOffset relativedelta fastpath relative_kwargs = [ ("years", 2), ("months", 5), ("days", 3), ("hours", 5), ("minutes", 10), ("seconds", 2), ("microseconds", 5), ] for i, (offset_unit, value) in enumerate(relative_kwargs): off = DateOffset(**{offset_unit: value})
exp_unit = unit if offset_unit == "microseconds" and unit != "ns": exp_unit = "us"
# TODO(GH#55564): as_unit will be unnecessary expected = DatetimeIndex([x + off for x in vec_items]).as_unit(exp_unit) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(expected, vec + off)
expected = DatetimeIndex([x - off for x in vec_items]).as_unit(exp_unit) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(expected, vec - off)
off = DateOffset(**dict(relative_kwargs[: i + 1]))
expected = DatetimeIndex([x + off for x in vec_items]).as_unit(exp_unit) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(expected, vec + off)
expected = DatetimeIndex([x - off for x in vec_items]).as_unit(exp_unit) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(expected, vec - off) msg = "(bad|unsupported) operand type for unary" with pytest.raises(TypeError, match=msg): off - vec
# ------------------------------------------------------------- # Non-Tick, Non-RelativeDelta DateOffsets
# TODO: redundant with test_dt64arr_add_sub_DateOffset? that includes # tz-aware cases which this does not @pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") @pytest.mark.parametrize( "cls_and_kwargs", [ "YearBegin", ("YearBegin", {"month": 5}), "YearEnd", ("YearEnd", {"month": 5}), "MonthBegin", "MonthEnd", "SemiMonthEnd", "SemiMonthBegin", "Week", ("Week", {"weekday": 3}), "Week", ("Week", {"weekday": 6}), "BusinessDay", "BDay", "QuarterEnd", "QuarterBegin", "CustomBusinessDay", "CDay", "CBMonthEnd", "CBMonthBegin", "BMonthBegin", "BMonthEnd", "BusinessHour", "BYearBegin", "BYearEnd", "BQuarterBegin", ("LastWeekOfMonth", {"weekday": 2}), ( "FY5253Quarter", { "qtr_with_extra_week": 1, "startingMonth": 1, "weekday": 2, "variation": "nearest", }, ), ("FY5253", {"weekday": 0, "startingMonth": 2, "variation": "nearest"}), ("WeekOfMonth", {"weekday": 2, "week": 2}), "Easter", ("DateOffset", {"day": 4}), ("DateOffset", {"month": 5}), ], ) @pytest.mark.parametrize("normalize", [True, False]) @pytest.mark.parametrize("n", [0, 5]) @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) @pytest.mark.parametrize("tz", [None, "US/Central"]) def test_dt64arr_add_sub_DateOffsets( self, box_with_array, n, normalize, cls_and_kwargs, unit, tz ): # GH#10699 # assert vectorized operation matches pointwise operations
if isinstance(cls_and_kwargs, tuple): # If cls_name param is a tuple, then 2nd entry is kwargs for # the offset constructor cls_name, kwargs = cls_and_kwargs else: cls_name = cls_and_kwargs kwargs = {}
if n == 0 and cls_name in [ "WeekOfMonth", "LastWeekOfMonth", "FY5253Quarter", "FY5253", ]: # passing n = 0 is invalid for these offset classes return
vec = ( DatetimeIndex( [ Timestamp("2000-01-05 00:15:00"), Timestamp("2000-01-31 00:23:00"), Timestamp("2000-01-01"), Timestamp("2000-03-31"), Timestamp("2000-02-29"), Timestamp("2000-12-31"), Timestamp("2000-05-15"), Timestamp("2001-06-15"), ] ) .as_unit(unit) .tz_localize(tz) ) vec = tm.box_expected(vec, box_with_array) vec_items = vec.iloc[0] if box_with_array is pd.DataFrame else vec
offset_cls = getattr(pd.offsets, cls_name) offset = offset_cls(n, normalize=normalize, **kwargs)
# TODO(GH#55564): as_unit will be unnecessary expected = DatetimeIndex([x + offset for x in vec_items]).as_unit(unit) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(expected, vec + offset) tm.assert_equal(expected, offset + vec)
expected = DatetimeIndex([x - offset for x in vec_items]).as_unit(unit) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(expected, vec - offset)
expected = DatetimeIndex([offset + x for x in vec_items]).as_unit(unit) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(expected, offset + vec) msg = "(bad|unsupported) operand type for unary" with pytest.raises(TypeError, match=msg): offset - vec
@pytest.mark.parametrize( "other", [ np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)]), np.array([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()]), np.array( # matching offsets [pd.offsets.DateOffset(years=1), pd.offsets.DateOffset(years=1)] ), ], ) @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub]) def test_dt64arr_add_sub_offset_array( self, tz_naive_fixture, box_with_array, op, other ): # GH#18849 # GH#10699 array of offsets
tz = tz_naive_fixture dti = date_range("2017-01-01", periods=2, tz=tz) dtarr = tm.box_expected(dti, box_with_array)
expected = DatetimeIndex([op(dti[n], other[n]) for n in range(len(dti))]) expected = tm.box_expected(expected, box_with_array).astype(object)
with tm.assert_produces_warning(PerformanceWarning): res = op(dtarr, other) tm.assert_equal(res, expected)
# Same thing but boxing other other = tm.box_expected(other, box_with_array) if box_with_array is pd.array and op is roperator.radd: # We expect a NumpyExtensionArray, not ndarray[object] here expected = pd.array(expected, dtype=object) with tm.assert_produces_warning(PerformanceWarning): res = op(dtarr, other) tm.assert_equal(res, expected)
@pytest.mark.parametrize( "op, offset, exp, exp_freq", [ ( "__add__", DateOffset(months=3, days=10), [ Timestamp("2014-04-11"), Timestamp("2015-04-11"), Timestamp("2016-04-11"), Timestamp("2017-04-11"), ], None, ), ( "__add__", DateOffset(months=3), [ Timestamp("2014-04-01"), Timestamp("2015-04-01"), Timestamp("2016-04-01"), Timestamp("2017-04-01"), ], "YS-APR", ), ( "__sub__", DateOffset(months=3, days=10), [ Timestamp("2013-09-21"), Timestamp("2014-09-21"), Timestamp("2015-09-21"), Timestamp("2016-09-21"), ], None, ), ( "__sub__", DateOffset(months=3), [ Timestamp("2013-10-01"), Timestamp("2014-10-01"), Timestamp("2015-10-01"), Timestamp("2016-10-01"), ], "YS-OCT", ), ], ) def test_dti_add_sub_nonzero_mth_offset( self, op, offset, exp, exp_freq, tz_aware_fixture, box_with_array ): # GH 26258 tz = tz_aware_fixture date = date_range(start="01 Jan 2014", end="01 Jan 2017", freq="YS", tz=tz) date = tm.box_expected(date, box_with_array, False) mth = getattr(date, op) result = mth(offset)
expected = DatetimeIndex(exp, tz=tz).as_unit("ns") expected = tm.box_expected(expected, box_with_array, False) tm.assert_equal(result, expected)
def test_dt64arr_series_add_DateOffset_with_milli(self): # GH 57529 dti = DatetimeIndex( [ "2000-01-01 00:00:00.012345678", "2000-01-31 00:00:00.012345678", "2000-02-29 00:00:00.012345678", ], dtype="datetime64[ns]", ) result = dti + DateOffset(milliseconds=4) expected = DatetimeIndex( [ "2000-01-01 00:00:00.016345678", "2000-01-31 00:00:00.016345678", "2000-02-29 00:00:00.016345678", ], dtype="datetime64[ns]", ) tm.assert_index_equal(result, expected)
result = dti + DateOffset(days=1, milliseconds=4) expected = DatetimeIndex( [ "2000-01-02 00:00:00.016345678", "2000-02-01 00:00:00.016345678", "2000-03-01 00:00:00.016345678", ], dtype="datetime64[ns]", ) tm.assert_index_equal(result, expected)
class TestDatetime64OverflowHandling: # TODO: box + de-duplicate
def test_dt64_overflow_masking(self, box_with_array): # GH#25317 left = Series([Timestamp("1969-12-31")], dtype="M8[ns]") right = Series([NaT])
left = tm.box_expected(left, box_with_array) right = tm.box_expected(right, box_with_array)
expected = TimedeltaIndex([NaT], dtype="m8[ns]") expected = tm.box_expected(expected, box_with_array)
result = left - right tm.assert_equal(result, expected)
def test_dt64_series_arith_overflow(self): # GH#12534, fixed by GH#19024 dt = Timestamp("1700-01-31") td = Timedelta("20000 Days") dti = date_range("1949-09-30", freq="100YE", periods=4) ser = Series(dti) msg = "Overflow in int64 addition" with pytest.raises(OverflowError, match=msg): ser - dt with pytest.raises(OverflowError, match=msg): dt - ser with pytest.raises(OverflowError, match=msg): ser + td with pytest.raises(OverflowError, match=msg): td + ser
ser.iloc[-1] = NaT expected = Series( ["2004-10-03", "2104-10-04", "2204-10-04", "NaT"], dtype="datetime64[ns]" ) res = ser + td tm.assert_series_equal(res, expected) res = td + ser tm.assert_series_equal(res, expected)
ser.iloc[1:] = NaT expected = Series(["91279 Days", "NaT", "NaT", "NaT"], dtype="timedelta64[ns]") res = ser - dt tm.assert_series_equal(res, expected) res = dt - ser tm.assert_series_equal(res, -expected)
def test_datetimeindex_sub_timestamp_overflow(self): dtimax = pd.to_datetime(["2021-12-28 17:19", Timestamp.max]).as_unit("ns") dtimin = pd.to_datetime(["2021-12-28 17:19", Timestamp.min]).as_unit("ns")
tsneg = Timestamp("1950-01-01").as_unit("ns") ts_neg_variants = [ tsneg, tsneg.to_pydatetime(), tsneg.to_datetime64().astype("datetime64[ns]"), tsneg.to_datetime64().astype("datetime64[D]"), ]
tspos = Timestamp("1980-01-01").as_unit("ns") ts_pos_variants = [ tspos, tspos.to_pydatetime(), tspos.to_datetime64().astype("datetime64[ns]"), tspos.to_datetime64().astype("datetime64[D]"), ] msg = "Overflow in int64 addition" for variant in ts_neg_variants: with pytest.raises(OverflowError, match=msg): dtimax - variant
expected = Timestamp.max._value - tspos._value for variant in ts_pos_variants: res = dtimax - variant assert res[1]._value == expected
expected = Timestamp.min._value - tsneg._value for variant in ts_neg_variants: res = dtimin - variant assert res[1]._value == expected
for variant in ts_pos_variants: with pytest.raises(OverflowError, match=msg): dtimin - variant
def test_datetimeindex_sub_datetimeindex_overflow(self): # GH#22492, GH#22508 dtimax = pd.to_datetime(["2021-12-28 17:19", Timestamp.max]).as_unit("ns") dtimin = pd.to_datetime(["2021-12-28 17:19", Timestamp.min]).as_unit("ns")
ts_neg = pd.to_datetime(["1950-01-01", "1950-01-01"]).as_unit("ns") ts_pos = pd.to_datetime(["1980-01-01", "1980-01-01"]).as_unit("ns")
# General tests expected = Timestamp.max._value - ts_pos[1]._value result = dtimax - ts_pos assert result[1]._value == expected
expected = Timestamp.min._value - ts_neg[1]._value result = dtimin - ts_neg assert result[1]._value == expected msg = "Overflow in int64 addition" with pytest.raises(OverflowError, match=msg): dtimax - ts_neg
with pytest.raises(OverflowError, match=msg): dtimin - ts_pos
# Edge cases tmin = pd.to_datetime([Timestamp.min]) t1 = tmin + Timedelta.max + Timedelta("1us") with pytest.raises(OverflowError, match=msg): t1 - tmin
tmax = pd.to_datetime([Timestamp.max]) t2 = tmax + Timedelta.min - Timedelta("1us") with pytest.raises(OverflowError, match=msg): tmax - t2
class TestTimestampSeriesArithmetic: def test_empty_series_add_sub(self, box_with_array): # GH#13844 a = Series(dtype="M8[ns]") b = Series(dtype="m8[ns]") a = box_with_array(a) b = box_with_array(b) tm.assert_equal(a, a + b) tm.assert_equal(a, a - b) tm.assert_equal(a, b + a) msg = "cannot subtract" with pytest.raises(TypeError, match=msg): b - a
def test_operators_datetimelike(self): # ## timedelta64 ### td1 = Series([timedelta(minutes=5, seconds=3)] * 3) td1.iloc[2] = np.nan
# ## datetime64 ### dt1 = Series( [ Timestamp("20111230"), Timestamp("20120101"), Timestamp("20120103"), ] ) dt1.iloc[2] = np.nan dt2 = Series( [ Timestamp("20111231"), Timestamp("20120102"), Timestamp("20120104"), ] ) dt1 - dt2 dt2 - dt1
# datetime64 with timetimedelta dt1 + td1 td1 + dt1 dt1 - td1
# timetimedelta with datetime64 td1 + dt1 dt1 + td1
def test_dt64ser_sub_datetime_dtype(self, unit): ts = Timestamp(datetime(1993, 1, 7, 13, 30, 00)) dt = datetime(1993, 6, 22, 13, 30) ser = Series([ts], dtype=f"M8[{unit}]") result = ser - dt
# the expected unit is the max of `unit` and the unit imputed to `dt`, # which is "us" exp_unit = tm.get_finest_unit(unit, "us") assert result.dtype == f"timedelta64[{exp_unit}]"
# ------------------------------------------------------------- # TODO: This next block of tests came from tests.series.test_operators, # needs to be de-duplicated and parametrized over `box` classes
@pytest.mark.parametrize( "left, right, op_fail", [ [ [Timestamp("20111230"), Timestamp("20120101"), NaT], [Timestamp("20111231"), Timestamp("20120102"), Timestamp("20120104")], ["__sub__", "__rsub__"], ], [ [Timestamp("20111230"), Timestamp("20120101"), NaT], [timedelta(minutes=5, seconds=3), timedelta(minutes=5, seconds=3), NaT], ["__add__", "__radd__", "__sub__"], ], [ [ Timestamp("20111230", tz="US/Eastern"), Timestamp("20111230", tz="US/Eastern"), NaT, ], [timedelta(minutes=5, seconds=3), NaT, timedelta(minutes=5, seconds=3)], ["__add__", "__radd__", "__sub__"], ], ], ) def test_operators_datetimelike_invalid( self, left, right, op_fail, all_arithmetic_operators ): # these are all TypeError ops op_str = all_arithmetic_operators arg1 = Series(left) arg2 = Series(right) # check that we are getting a TypeError # with 'operate' (from core/ops.py) for the ops that are not # defined op = getattr(arg1, op_str, None) # Previously, _validate_for_numeric_binop in core/indexes/base.py # did this for us. if op_str not in op_fail: with pytest.raises( TypeError, match="operate|[cC]annot|unsupported operand" ): op(arg2) else: # Smoke test op(arg2)
def test_sub_single_tz(self, unit): # GH#12290 s1 = Series([Timestamp("2016-02-10", tz="America/Sao_Paulo")]).dt.as_unit(unit) s2 = Series([Timestamp("2016-02-08", tz="America/Sao_Paulo")]).dt.as_unit(unit) result = s1 - s2 expected = Series([Timedelta("2days")]).dt.as_unit(unit) tm.assert_series_equal(result, expected) result = s2 - s1 expected = Series([Timedelta("-2days")]).dt.as_unit(unit) tm.assert_series_equal(result, expected)
def test_dt64tz_series_sub_dtitz(self): # GH#19071 subtracting tzaware DatetimeIndex from tzaware Series # (with same tz) raises, fixed by #19024 dti = date_range("1999-09-30", periods=10, tz="US/Pacific") ser = Series(dti) expected = Series(TimedeltaIndex(["0days"] * 10))
res = dti - ser tm.assert_series_equal(res, expected) res = ser - dti tm.assert_series_equal(res, expected)
def test_sub_datetime_compat(self, unit): # see GH#14088 ser = Series([datetime(2016, 8, 23, 12, tzinfo=pytz.utc), NaT]).dt.as_unit(unit) dt = datetime(2016, 8, 22, 12, tzinfo=pytz.utc) # The datetime object has "us" so we upcast lower units exp_unit = tm.get_finest_unit(unit, "us") exp = Series([Timedelta("1 days"), NaT]).dt.as_unit(exp_unit) result = ser - dt tm.assert_series_equal(result, exp) result2 = ser - Timestamp(dt) tm.assert_series_equal(result2, exp)
def test_dt64_series_add_mixed_tick_DateOffset(self): # GH#4532 # operate with pd.offsets s = Series([Timestamp("20130101 9:01"), Timestamp("20130101 9:02")])
result = s + pd.offsets.Milli(5) result2 = pd.offsets.Milli(5) + s expected = Series( [Timestamp("20130101 9:01:00.005"), Timestamp("20130101 9:02:00.005")] ) tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected)
result = s + pd.offsets.Minute(5) + pd.offsets.Milli(5) expected = Series( [Timestamp("20130101 9:06:00.005"), Timestamp("20130101 9:07:00.005")] ) tm.assert_series_equal(result, expected)
def test_datetime64_ops_nat(self, unit): # GH#11349 datetime_series = Series([NaT, Timestamp("19900315")]).dt.as_unit(unit) nat_series_dtype_timestamp = Series([NaT, NaT], dtype=f"datetime64[{unit}]") single_nat_dtype_datetime = Series([NaT], dtype=f"datetime64[{unit}]")
# subtraction tm.assert_series_equal(-NaT + datetime_series, nat_series_dtype_timestamp) msg = "bad operand type for unary -: 'DatetimeArray'" with pytest.raises(TypeError, match=msg): -single_nat_dtype_datetime + datetime_series
tm.assert_series_equal( -NaT + nat_series_dtype_timestamp, nat_series_dtype_timestamp ) with pytest.raises(TypeError, match=msg): -single_nat_dtype_datetime + nat_series_dtype_timestamp
# addition tm.assert_series_equal( nat_series_dtype_timestamp + NaT, nat_series_dtype_timestamp ) tm.assert_series_equal( NaT + nat_series_dtype_timestamp, nat_series_dtype_timestamp )
tm.assert_series_equal( nat_series_dtype_timestamp + NaT, nat_series_dtype_timestamp ) tm.assert_series_equal( NaT + nat_series_dtype_timestamp, nat_series_dtype_timestamp )
# ------------------------------------------------------------- # Timezone-Centric Tests
def test_operators_datetimelike_with_timezones(self): tz = "US/Eastern" dt1 = Series(date_range("2000-01-01 09:00:00", periods=5, tz=tz), name="foo") dt2 = dt1.copy() dt2.iloc[2] = np.nan
td1 = Series(pd.timedelta_range("1 days 1 min", periods=5, freq="h")) td2 = td1.copy() td2.iloc[1] = np.nan assert td2._values.freq is None
result = dt1 + td1[0] exp = (dt1.dt.tz_localize(None) + td1[0]).dt.tz_localize(tz) tm.assert_series_equal(result, exp)
result = dt2 + td2[0] exp = (dt2.dt.tz_localize(None) + td2[0]).dt.tz_localize(tz) tm.assert_series_equal(result, exp)
# odd numpy behavior with scalar timedeltas result = td1[0] + dt1 exp = (dt1.dt.tz_localize(None) + td1[0]).dt.tz_localize(tz) tm.assert_series_equal(result, exp)
result = td2[0] + dt2 exp = (dt2.dt.tz_localize(None) + td2[0]).dt.tz_localize(tz) tm.assert_series_equal(result, exp)
result = dt1 - td1[0] exp = (dt1.dt.tz_localize(None) - td1[0]).dt.tz_localize(tz) tm.assert_series_equal(result, exp) msg = "(bad|unsupported) operand type for unary" with pytest.raises(TypeError, match=msg): td1[0] - dt1
result = dt2 - td2[0] exp = (dt2.dt.tz_localize(None) - td2[0]).dt.tz_localize(tz) tm.assert_series_equal(result, exp) with pytest.raises(TypeError, match=msg): td2[0] - dt2
result = dt1 + td1 exp = (dt1.dt.tz_localize(None) + td1).dt.tz_localize(tz) tm.assert_series_equal(result, exp)
result = dt2 + td2 exp = (dt2.dt.tz_localize(None) + td2).dt.tz_localize(tz) tm.assert_series_equal(result, exp)
result = dt1 - td1 exp = (dt1.dt.tz_localize(None) - td1).dt.tz_localize(tz) tm.assert_series_equal(result, exp)
result = dt2 - td2 exp = (dt2.dt.tz_localize(None) - td2).dt.tz_localize(tz) tm.assert_series_equal(result, exp) msg = "cannot (add|subtract)" with pytest.raises(TypeError, match=msg): td1 - dt1 with pytest.raises(TypeError, match=msg): td2 - dt2
class TestDatetimeIndexArithmetic: # ------------------------------------------------------------- # Binary operations DatetimeIndex and TimedeltaIndex/array
def test_dti_add_tdi(self, tz_naive_fixture): # GH#17558 tz = tz_naive_fixture dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) tdi = pd.timedelta_range("0 days", periods=10) expected = date_range("2017-01-01", periods=10, tz=tz) expected = expected._with_freq(None)
# add with TimedeltaIndex result = dti + tdi tm.assert_index_equal(result, expected)
result = tdi + dti tm.assert_index_equal(result, expected)
# add with timedelta64 array result = dti + tdi.values tm.assert_index_equal(result, expected)
result = tdi.values + dti tm.assert_index_equal(result, expected)
def test_dti_iadd_tdi(self, tz_naive_fixture): # GH#17558 tz = tz_naive_fixture dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) tdi = pd.timedelta_range("0 days", periods=10) expected = date_range("2017-01-01", periods=10, tz=tz) expected = expected._with_freq(None)
# iadd with TimedeltaIndex result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) result += tdi tm.assert_index_equal(result, expected)
result = pd.timedelta_range("0 days", periods=10) result += dti tm.assert_index_equal(result, expected)
# iadd with timedelta64 array result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) result += tdi.values tm.assert_index_equal(result, expected)
result = pd.timedelta_range("0 days", periods=10) result += dti tm.assert_index_equal(result, expected)
def test_dti_sub_tdi(self, tz_naive_fixture): # GH#17558 tz = tz_naive_fixture dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) tdi = pd.timedelta_range("0 days", periods=10) expected = date_range("2017-01-01", periods=10, tz=tz, freq="-1D") expected = expected._with_freq(None)
# sub with TimedeltaIndex result = dti - tdi tm.assert_index_equal(result, expected)
msg = "cannot subtract .*TimedeltaArray" with pytest.raises(TypeError, match=msg): tdi - dti
# sub with timedelta64 array result = dti - tdi.values tm.assert_index_equal(result, expected)
msg = "cannot subtract a datelike from a TimedeltaArray" with pytest.raises(TypeError, match=msg): tdi.values - dti
def test_dti_isub_tdi(self, tz_naive_fixture, unit): # GH#17558 tz = tz_naive_fixture dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10).as_unit(unit) tdi = pd.timedelta_range("0 days", periods=10, unit=unit) expected = date_range("2017-01-01", periods=10, tz=tz, freq="-1D", unit=unit) expected = expected._with_freq(None)
# isub with TimedeltaIndex result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10).as_unit(unit) result -= tdi tm.assert_index_equal(result, expected)
# DTA.__isub__ GH#43904 dta = dti._data.copy() dta -= tdi tm.assert_datetime_array_equal(dta, expected._data)
out = dti._data.copy() np.subtract(out, tdi, out=out) tm.assert_datetime_array_equal(out, expected._data)
msg = "cannot subtract a datelike from a TimedeltaArray" with pytest.raises(TypeError, match=msg): tdi -= dti
# isub with timedelta64 array result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10).as_unit(unit) result -= tdi.values tm.assert_index_equal(result, expected)
with pytest.raises(TypeError, match=msg): tdi.values -= dti
with pytest.raises(TypeError, match=msg): tdi._values -= dti
# ------------------------------------------------------------- # Binary Operations DatetimeIndex and datetime-like # TODO: A couple other tests belong in this section. Move them in # A PR where there isn't already a giant diff.
# -------------------------------------------------------------
def test_dta_add_sub_index(self, tz_naive_fixture): # Check that DatetimeArray defers to Index classes dti = date_range("20130101", periods=3, tz=tz_naive_fixture) dta = dti.array result = dta - dti expected = dti - dti tm.assert_index_equal(result, expected)
tdi = result result = dta + tdi expected = dti + tdi tm.assert_index_equal(result, expected)
result = dta - tdi expected = dti - tdi tm.assert_index_equal(result, expected)
def test_sub_dti_dti(self, unit): # previously performed setop (deprecated in 0.16.0), now changed to # return subtraction -> TimeDeltaIndex (GH ...)
dti = date_range("20130101", periods=3, unit=unit) dti_tz = date_range("20130101", periods=3, unit=unit).tz_localize("US/Eastern") expected = TimedeltaIndex([0, 0, 0]).as_unit(unit)
result = dti - dti tm.assert_index_equal(result, expected)
result = dti_tz - dti_tz tm.assert_index_equal(result, expected) msg = "Cannot subtract tz-naive and tz-aware datetime-like objects" with pytest.raises(TypeError, match=msg): dti_tz - dti
with pytest.raises(TypeError, match=msg): dti - dti_tz
# isub dti -= dti tm.assert_index_equal(dti, expected)
# different length raises ValueError dti1 = date_range("20130101", periods=3, unit=unit) dti2 = date_range("20130101", periods=4, unit=unit) msg = "cannot add indices of unequal length" with pytest.raises(ValueError, match=msg): dti1 - dti2
# NaN propagation dti1 = DatetimeIndex(["2012-01-01", np.nan, "2012-01-03"]).as_unit(unit) dti2 = DatetimeIndex(["2012-01-02", "2012-01-03", np.nan]).as_unit(unit) expected = TimedeltaIndex(["1 days", np.nan, np.nan]).as_unit(unit) result = dti2 - dti1 tm.assert_index_equal(result, expected)
# ------------------------------------------------------------------- # TODO: Most of this block is moved from series or frame tests, needs # cleanup, box-parametrization, and de-duplication
@pytest.mark.parametrize("op", [operator.add, operator.sub]) def test_timedelta64_equal_timedelta_supported_ops(self, op, box_with_array): ser = Series( [ Timestamp("20130301"), Timestamp("20130228 23:00:00"), Timestamp("20130228 22:00:00"), Timestamp("20130228 21:00:00"), ] ) obj = box_with_array(ser)
intervals = ["D", "h", "m", "s", "us"]
def timedelta64(*args): # see casting notes in NumPy gh-12927 return np.sum(list(starmap(np.timedelta64, zip(args, intervals))))
for d, h, m, s, us in product(*([range(2)] * 5)): nptd = timedelta64(d, h, m, s, us) pytd = timedelta(days=d, hours=h, minutes=m, seconds=s, microseconds=us) lhs = op(obj, nptd) rhs = op(obj, pytd)
tm.assert_equal(lhs, rhs)
def test_ops_nat_mixed_datetime64_timedelta64(self): # GH#11349 timedelta_series = Series([NaT, Timedelta("1s")]) datetime_series = Series([NaT, Timestamp("19900315")]) nat_series_dtype_timedelta = Series([NaT, NaT], dtype="timedelta64[ns]") nat_series_dtype_timestamp = Series([NaT, NaT], dtype="datetime64[ns]") single_nat_dtype_datetime = Series([NaT], dtype="datetime64[ns]") single_nat_dtype_timedelta = Series([NaT], dtype="timedelta64[ns]")
# subtraction tm.assert_series_equal( datetime_series - single_nat_dtype_datetime, nat_series_dtype_timedelta )
tm.assert_series_equal( datetime_series - single_nat_dtype_timedelta, nat_series_dtype_timestamp ) tm.assert_series_equal( -single_nat_dtype_timedelta + datetime_series, nat_series_dtype_timestamp )
# without a Series wrapping the NaT, it is ambiguous # whether it is a datetime64 or timedelta64 # defaults to interpreting it as timedelta64 tm.assert_series_equal( nat_series_dtype_timestamp - single_nat_dtype_datetime, nat_series_dtype_timedelta, )
tm.assert_series_equal( nat_series_dtype_timestamp - single_nat_dtype_timedelta, nat_series_dtype_timestamp, ) tm.assert_series_equal( -single_nat_dtype_timedelta + nat_series_dtype_timestamp, nat_series_dtype_timestamp, ) msg = "cannot subtract a datelike" with pytest.raises(TypeError, match=msg): timedelta_series - single_nat_dtype_datetime
# addition tm.assert_series_equal( nat_series_dtype_timestamp + single_nat_dtype_timedelta, nat_series_dtype_timestamp, ) tm.assert_series_equal( single_nat_dtype_timedelta + nat_series_dtype_timestamp, nat_series_dtype_timestamp, )
tm.assert_series_equal( nat_series_dtype_timestamp + single_nat_dtype_timedelta, nat_series_dtype_timestamp, ) tm.assert_series_equal( single_nat_dtype_timedelta + nat_series_dtype_timestamp, nat_series_dtype_timestamp, )
tm.assert_series_equal( nat_series_dtype_timedelta + single_nat_dtype_datetime, nat_series_dtype_timestamp, ) tm.assert_series_equal( single_nat_dtype_datetime + nat_series_dtype_timedelta, nat_series_dtype_timestamp, )
def test_ufunc_coercions(self, unit): idx = date_range("2011-01-01", periods=3, freq="2D", name="x", unit=unit)
delta = np.timedelta64(1, "D") exp = date_range("2011-01-02", periods=3, freq="2D", name="x", unit=unit) for result in [idx + delta, np.add(idx, delta)]: assert isinstance(result, DatetimeIndex) tm.assert_index_equal(result, exp) assert result.freq == "2D"
exp = date_range("2010-12-31", periods=3, freq="2D", name="x", unit=unit)
for result in [idx - delta, np.subtract(idx, delta)]: assert isinstance(result, DatetimeIndex) tm.assert_index_equal(result, exp) assert result.freq == "2D"
# When adding/subtracting an ndarray (which has no .freq), the result # does not infer freq idx = idx._with_freq(None) delta = np.array( [np.timedelta64(1, "D"), np.timedelta64(2, "D"), np.timedelta64(3, "D")] ) exp = DatetimeIndex( ["2011-01-02", "2011-01-05", "2011-01-08"], name="x" ).as_unit(unit)
for result in [idx + delta, np.add(idx, delta)]: tm.assert_index_equal(result, exp) assert result.freq == exp.freq
exp = DatetimeIndex( ["2010-12-31", "2011-01-01", "2011-01-02"], name="x" ).as_unit(unit) for result in [idx - delta, np.subtract(idx, delta)]: assert isinstance(result, DatetimeIndex) tm.assert_index_equal(result, exp) assert result.freq == exp.freq
def test_dti_add_series(self, tz_naive_fixture, names): # GH#13905 tz = tz_naive_fixture index = DatetimeIndex( ["2016-06-28 05:30", "2016-06-28 05:31"], tz=tz, name=names[0] ).as_unit("ns") ser = Series([Timedelta(seconds=5)] * 2, index=index, name=names[1]) expected = Series(index + Timedelta(seconds=5), index=index, name=names[2])
# passing name arg isn't enough when names[2] is None expected.name = names[2] assert expected.dtype == index.dtype result = ser + index tm.assert_series_equal(result, expected) result2 = index + ser tm.assert_series_equal(result2, expected)
expected = index + Timedelta(seconds=5) result3 = ser.values + index tm.assert_index_equal(result3, expected) result4 = index + ser.values tm.assert_index_equal(result4, expected)
@pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub]) def test_dti_addsub_offset_arraylike( self, tz_naive_fixture, names, op, index_or_series ): # GH#18849, GH#19744 other_box = index_or_series
tz = tz_naive_fixture dti = date_range("2017-01-01", periods=2, tz=tz, name=names[0]) other = other_box([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)], name=names[1])
xbox = get_upcast_box(dti, other)
with tm.assert_produces_warning(PerformanceWarning): res = op(dti, other)
expected = DatetimeIndex( [op(dti[n], other[n]) for n in range(len(dti))], name=names[2], freq="infer" ) expected = tm.box_expected(expected, xbox).astype(object) tm.assert_equal(res, expected)
@pytest.mark.parametrize("other_box", [pd.Index, np.array]) def test_dti_addsub_object_arraylike( self, tz_naive_fixture, box_with_array, other_box ): tz = tz_naive_fixture
dti = date_range("2017-01-01", periods=2, tz=tz) dtarr = tm.box_expected(dti, box_with_array) other = other_box([pd.offsets.MonthEnd(), Timedelta(days=4)]) xbox = get_upcast_box(dtarr, other)
expected = DatetimeIndex(["2017-01-31", "2017-01-06"], tz=tz_naive_fixture) expected = tm.box_expected(expected, xbox).astype(object)
with tm.assert_produces_warning(PerformanceWarning): result = dtarr + other tm.assert_equal(result, expected)
expected = DatetimeIndex(["2016-12-31", "2016-12-29"], tz=tz_naive_fixture) expected = tm.box_expected(expected, xbox).astype(object)
with tm.assert_produces_warning(PerformanceWarning): result = dtarr - other tm.assert_equal(result, expected)
@pytest.mark.parametrize("years", [-1, 0, 1])@pytest.mark.parametrize("months", [-2, 0, 2])@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])def test_shift_months(years, months, unit): dti = DatetimeIndex( [ Timestamp("2000-01-05 00:15:00"), Timestamp("2000-01-31 00:23:00"), Timestamp("2000-01-01"), Timestamp("2000-02-29"), Timestamp("2000-12-31"), ] ).as_unit(unit) shifted = shift_months(dti.asi8, years * 12 + months, reso=dti._data._creso) shifted_dt64 = shifted.view(f"M8[{dti.unit}]") actual = DatetimeIndex(shifted_dt64)
raw = [x + pd.offsets.DateOffset(years=years, months=months) for x in dti] expected = DatetimeIndex(raw).as_unit(dti.unit) tm.assert_index_equal(actual, expected)
def test_dt64arr_addsub_object_dtype_2d(): # block-wise DataFrame operations will require operating on 2D # DatetimeArray/TimedeltaArray, so check that specifically. dti = date_range("1994-02-13", freq="2W", periods=4) dta = dti._data.reshape((4, 1))
other = np.array([[pd.offsets.Day(n)] for n in range(4)]) assert other.shape == dta.shape
with tm.assert_produces_warning(PerformanceWarning): result = dta + other with tm.assert_produces_warning(PerformanceWarning): expected = (dta[:, 0] + other[:, 0]).reshape(-1, 1)
tm.assert_numpy_array_equal(result, expected)
with tm.assert_produces_warning(PerformanceWarning): # Case where we expect to get a TimedeltaArray back result2 = dta - dta.astype(object)
assert result2.shape == (4, 1) assert all(td._value == 0 for td in result2.ravel())
def test_non_nano_dt64_addsub_np_nat_scalars(): # GH 52295 ser = Series([1233242342344, 232432434324, 332434242344], dtype="datetime64[ms]") result = ser - np.datetime64("nat", "ms") expected = Series([NaT] * 3, dtype="timedelta64[ms]") tm.assert_series_equal(result, expected)
result = ser + np.timedelta64("nat", "ms") expected = Series([NaT] * 3, dtype="datetime64[ms]") tm.assert_series_equal(result, expected)
def test_non_nano_dt64_addsub_np_nat_scalars_unitless(): # GH 52295 # TODO: Can we default to the ser unit? ser = Series([1233242342344, 232432434324, 332434242344], dtype="datetime64[ms]") result = ser - np.datetime64("nat") expected = Series([NaT] * 3, dtype="timedelta64[ns]") tm.assert_series_equal(result, expected)
result = ser + np.timedelta64("nat") expected = Series([NaT] * 3, dtype="datetime64[ns]") tm.assert_series_equal(result, expected)
def test_non_nano_dt64_addsub_np_nat_scalars_unsupported_unit(): # GH 52295 ser = Series([12332, 23243, 33243], dtype="datetime64[s]") result = ser - np.datetime64("nat", "D") expected = Series([NaT] * 3, dtype="timedelta64[s]") tm.assert_series_equal(result, expected)
result = ser + np.timedelta64("nat", "D") expected = Series([NaT] * 3, dtype="datetime64[s]") tm.assert_series_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306import operator
import numpy as npimport pytest
from pandas.core.dtypes.common import is_list_like
import pandas as pdfrom pandas import ( Categorical, Index, Interval, IntervalIndex, Period, Series, Timedelta, Timestamp, date_range, period_range, timedelta_range,)import pandas._testing as tmfrom pandas.core.arrays import ( BooleanArray, IntervalArray,)from pandas.tests.arithmetic.common import get_upcast_box
@pytest.fixture( params=[ (Index([0, 2, 4, 4]), Index([1, 3, 5, 8])), (Index([0.0, 1.0, 2.0, np.nan]), Index([1.0, 2.0, 3.0, np.nan])), ( timedelta_range("0 days", periods=3).insert(3, pd.NaT), timedelta_range("1 day", periods=3).insert(3, pd.NaT), ), ( date_range("20170101", periods=3).insert(3, pd.NaT), date_range("20170102", periods=3).insert(3, pd.NaT), ), ( date_range("20170101", periods=3, tz="US/Eastern").insert(3, pd.NaT), date_range("20170102", periods=3, tz="US/Eastern").insert(3, pd.NaT), ), ], ids=lambda x: str(x[0].dtype),)def left_right_dtypes(request): """ Fixture for building an IntervalArray from various dtypes """ return request.param
@pytest.fixturedef interval_array(left_right_dtypes): """ Fixture to generate an IntervalArray of various dtypes containing NA if possible """ left, right = left_right_dtypes return IntervalArray.from_arrays(left, right)
def create_categorical_intervals(left, right, closed="right"): return Categorical(IntervalIndex.from_arrays(left, right, closed))
def create_series_intervals(left, right, closed="right"): return Series(IntervalArray.from_arrays(left, right, closed))
def create_series_categorical_intervals(left, right, closed="right"): return Series(Categorical(IntervalIndex.from_arrays(left, right, closed)))
class TestComparison: @pytest.fixture(params=[operator.eq, operator.ne]) def op(self, request): return request.param
@pytest.fixture( params=[ IntervalArray.from_arrays, IntervalIndex.from_arrays, create_categorical_intervals, create_series_intervals, create_series_categorical_intervals, ], ids=[ "IntervalArray", "IntervalIndex", "Categorical[Interval]", "Series[Interval]", "Series[Categorical[Interval]]", ], ) def interval_constructor(self, request): """ Fixture for all pandas native interval constructors. To be used as the LHS of IntervalArray comparisons. """ return request.param
def elementwise_comparison(self, op, interval_array, other): """ Helper that performs elementwise comparisons between `array` and `other` """ other = other if is_list_like(other) else [other] * len(interval_array) expected = np.array([op(x, y) for x, y in zip(interval_array, other)]) if isinstance(other, Series): return Series(expected, index=other.index) return expected
def test_compare_scalar_interval(self, op, interval_array): # matches first interval other = interval_array[0] result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_numpy_array_equal(result, expected)
# matches on a single endpoint but not both other = Interval(interval_array.left[0], interval_array.right[1]) result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_numpy_array_equal(result, expected)
def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed): interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed) other = Interval(0, 1, closed=other_closed)
result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_numpy_array_equal(result, expected)
def test_compare_scalar_na(self, op, interval_array, nulls_fixture, box_with_array): box = box_with_array obj = tm.box_expected(interval_array, box) result = op(obj, nulls_fixture)
if nulls_fixture is pd.NA: # GH#31882 exp = np.ones(interval_array.shape, dtype=bool) expected = BooleanArray(exp, exp) else: expected = self.elementwise_comparison(op, interval_array, nulls_fixture)
if not (box is Index and nulls_fixture is pd.NA): # don't cast expected from BooleanArray to ndarray[object] xbox = get_upcast_box(obj, nulls_fixture, True) expected = tm.box_expected(expected, xbox)
tm.assert_equal(result, expected)
rev = op(nulls_fixture, obj) tm.assert_equal(rev, expected)
@pytest.mark.parametrize( "other", [ 0, 1.0, True, "foo", Timestamp("2017-01-01"), Timestamp("2017-01-01", tz="US/Eastern"), Timedelta("0 days"), Period("2017-01-01", "D"), ], ) def test_compare_scalar_other(self, op, interval_array, other): result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_numpy_array_equal(result, expected)
def test_compare_list_like_interval(self, op, interval_array, interval_constructor): # same endpoints other = interval_constructor(interval_array.left, interval_array.right) result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_equal(result, expected)
# different endpoints other = interval_constructor( interval_array.left[::-1], interval_array.right[::-1] ) result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_equal(result, expected)
# all nan endpoints other = interval_constructor([np.nan] * 4, [np.nan] * 4) result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_equal(result, expected)
def test_compare_list_like_interval_mixed_closed( self, op, interval_constructor, closed, other_closed ): interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed) other = interval_constructor(range(2), range(1, 3), closed=other_closed)
result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_equal(result, expected)
@pytest.mark.parametrize( "other", [ ( Interval(0, 1), Interval(Timedelta("1 day"), Timedelta("2 days")), Interval(4, 5, "both"), Interval(10, 20, "neither"), ), (0, 1.5, Timestamp("20170103"), np.nan), ( Timestamp("20170102", tz="US/Eastern"), Timedelta("2 days"), "baz", pd.NaT, ), ], ) def test_compare_list_like_object(self, op, interval_array, other): result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_numpy_array_equal(result, expected)
def test_compare_list_like_nan(self, op, interval_array, nulls_fixture): other = [nulls_fixture] * 4 result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other)
tm.assert_equal(result, expected)
@pytest.mark.parametrize( "other", [ np.arange(4, dtype="int64"), np.arange(4, dtype="float64"), date_range("2017-01-01", periods=4), date_range("2017-01-01", periods=4, tz="US/Eastern"), timedelta_range("0 days", periods=4), period_range("2017-01-01", periods=4, freq="D"), Categorical(list("abab")), Categorical(date_range("2017-01-01", periods=4)), pd.array(list("abcd")), pd.array(["foo", 3.14, None, object()], dtype=object), ], ids=lambda x: str(x.dtype), ) def test_compare_list_like_other(self, op, interval_array, other): result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("length", [1, 3, 5]) @pytest.mark.parametrize("other_constructor", [IntervalArray, list]) def test_compare_length_mismatch_errors(self, op, other_constructor, length): interval_array = IntervalArray.from_arrays(range(4), range(1, 5)) other = other_constructor([Interval(0, 1)] * length) with pytest.raises(ValueError, match="Lengths must match to compare"): op(interval_array, other)
@pytest.mark.parametrize( "constructor, expected_type, assert_func", [ (IntervalIndex, np.array, tm.assert_numpy_array_equal), (Series, Series, tm.assert_series_equal), ], ) def test_index_series_compat(self, op, constructor, expected_type, assert_func): # IntervalIndex/Series that rely on IntervalArray for comparisons breaks = range(4) index = constructor(IntervalIndex.from_breaks(breaks))
# scalar comparisons other = index[0] result = op(index, other) expected = expected_type(self.elementwise_comparison(op, index, other)) assert_func(result, expected)
other = breaks[0] result = op(index, other) expected = expected_type(self.elementwise_comparison(op, index, other)) assert_func(result, expected)
# list-like comparisons other = IntervalArray.from_breaks(breaks) result = op(index, other) expected = expected_type(self.elementwise_comparison(op, index, other)) assert_func(result, expected)
other = [index[0], breaks[0], "foo"] result = op(index, other) expected = expected_type(self.elementwise_comparison(op, index, other)) assert_func(result, expected)
@pytest.mark.parametrize("scalars", ["a", False, 1, 1.0, None]) def test_comparison_operations(self, scalars): # GH #28981 expected = Series([False, False]) s = Series([Interval(0, 1), Interval(1, 2)], dtype="interval") result = s == scalars tm.assert_series_equal(result, expected)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567# Arithmetic tests for DataFrame/Series/Index/Array classes that should# behave identically.# Specifically for numeric dtypesfrom __future__ import annotations
from collections import abcfrom datetime import timedeltafrom decimal import Decimalimport operator
import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, RangeIndex, Series, Timedelta, TimedeltaIndex, array, date_range,)import pandas._testing as tmfrom pandas.core import opsfrom pandas.core.computation import expressions as exprfrom pandas.tests.arithmetic.common import ( assert_invalid_addsub_type, assert_invalid_comparison,)
@pytest.fixture(autouse=True, params=[0, 1000000], ids=["numexpr", "python"])def switch_numexpr_min_elements(request, monkeypatch): with monkeypatch.context() as m: m.setattr(expr, "_MIN_ELEMENTS", request.param) yield request.param
@pytest.fixture(params=[Index, Series, tm.to_array])def box_pandas_1d_array(request): """ Fixture to test behavior for Index, Series and tm.to_array classes """ return request.param
@pytest.fixture( params=[ # TODO: add more dtypes here Index(np.arange(5, dtype="float64")), Index(np.arange(5, dtype="int64")), Index(np.arange(5, dtype="uint64")), RangeIndex(5), ], ids=lambda x: type(x).__name__,)def numeric_idx(request): """ Several types of numeric-dtypes Index objects """ return request.param
@pytest.fixture( params=[Index, Series, tm.to_array, np.array, list], ids=lambda x: x.__name__)def box_1d_array(request): """ Fixture to test behavior for Index, Series, tm.to_array, numpy Array and list classes """ return request.param
def adjust_negative_zero(zero, expected): """ Helper to adjust the expected result if we are dividing by -0.0 as opposed to 0.0 """ if np.signbit(np.array(zero)).any(): # All entries in the `zero` fixture should be either # all-negative or no-negative. assert np.signbit(np.array(zero)).all()
expected *= -1
return expected
def compare_op(series, other, op): left = np.abs(series) if op in (ops.rpow, operator.pow) else series right = np.abs(other) if op in (ops.rpow, operator.pow) else other
cython_or_numpy = op(left, right) python = left.combine(right, op) if isinstance(other, Series) and not other.index.equals(series.index): python.index = python.index._with_freq(None) tm.assert_series_equal(cython_or_numpy, python)
# TODO: remove this kludge once mypy stops giving false positives here# List comprehension has incompatible type List[PandasObject]; expected List[RangeIndex]# See GH#29725_ldtypes = ["i1", "i2", "i4", "i8", "u1", "u2", "u4", "u8", "f2", "f4", "f8"]lefts: list[Index | Series] = [RangeIndex(10, 40, 10)]lefts.extend([Series([10, 20, 30], dtype=dtype) for dtype in _ldtypes])lefts.extend([Index([10, 20, 30], dtype=dtype) for dtype in _ldtypes if dtype != "f2"])
# ------------------------------------------------------------------# Comparisons
class TestNumericComparisons: def test_operator_series_comparison_zerorank(self): # GH#13006 result = np.float64(0) > Series([1, 2, 3]) expected = 0.0 > Series([1, 2, 3]) tm.assert_series_equal(result, expected) result = Series([1, 2, 3]) < np.float64(0) expected = Series([1, 2, 3]) < 0.0 tm.assert_series_equal(result, expected) result = np.array([0, 1, 2])[0] > Series([0, 1, 2]) expected = 0.0 > Series([1, 2, 3]) tm.assert_series_equal(result, expected)
def test_df_numeric_cmp_dt64_raises(self, box_with_array, fixed_now_ts): # GH#8932, GH#22163 ts = fixed_now_ts obj = np.array(range(5)) obj = tm.box_expected(obj, box_with_array)
assert_invalid_comparison(obj, ts, box_with_array)
def test_compare_invalid(self): # GH#8058 # ops testing a = Series(np.random.default_rng(2).standard_normal(5), name=0) b = Series(np.random.default_rng(2).standard_normal(5)) b.name = pd.Timestamp("2000-01-01") tm.assert_series_equal(a / b, 1 / (b / a))
def test_numeric_cmp_string_numexpr_path(self, box_with_array, monkeypatch): # GH#36377, GH#35700 box = box_with_array xbox = box if box is not Index else np.ndarray
obj = Series(np.random.default_rng(2).standard_normal(51)) obj = tm.box_expected(obj, box, transpose=False) with monkeypatch.context() as m: m.setattr(expr, "_MIN_ELEMENTS", 50) result = obj == "a"
expected = Series(np.zeros(51, dtype=bool)) expected = tm.box_expected(expected, xbox, transpose=False) tm.assert_equal(result, expected)
with monkeypatch.context() as m: m.setattr(expr, "_MIN_ELEMENTS", 50) result = obj != "a" tm.assert_equal(result, ~expected)
msg = "Invalid comparison between dtype=float64 and str" with pytest.raises(TypeError, match=msg): obj < "a"
# ------------------------------------------------------------------# Numeric dtypes Arithmetic with Datetime/Timedelta Scalar
class TestNumericArraylikeArithmeticWithDatetimeLike: @pytest.mark.parametrize("box_cls", [np.array, Index, Series]) @pytest.mark.parametrize( "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype) ) def test_mul_td64arr(self, left, box_cls): # GH#22390 right = np.array([1, 2, 3], dtype="m8[s]") right = box_cls(right)
expected = TimedeltaIndex(["10s", "40s", "90s"], dtype=right.dtype)
if isinstance(left, Series) or box_cls is Series: expected = Series(expected) assert expected.dtype == right.dtype
result = left * right tm.assert_equal(result, expected)
result = right * left tm.assert_equal(result, expected)
@pytest.mark.parametrize("box_cls", [np.array, Index, Series]) @pytest.mark.parametrize( "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype) ) def test_div_td64arr(self, left, box_cls): # GH#22390 right = np.array([10, 40, 90], dtype="m8[s]") right = box_cls(right)
expected = TimedeltaIndex(["1s", "2s", "3s"], dtype=right.dtype) if isinstance(left, Series) or box_cls is Series: expected = Series(expected) assert expected.dtype == right.dtype
result = right / left tm.assert_equal(result, expected)
result = right // left tm.assert_equal(result, expected)
# (true_) needed for min-versions build 2022-12-26 msg = "ufunc '(true_)?divide' cannot use operands with types" with pytest.raises(TypeError, match=msg): left / right
msg = "ufunc 'floor_divide' cannot use operands with types" with pytest.raises(TypeError, match=msg): left // right
# TODO: also test Tick objects; # see test_numeric_arr_rdiv_tdscalar for note on these failing @pytest.mark.parametrize( "scalar_td", [ Timedelta(days=1), Timedelta(days=1).to_timedelta64(), Timedelta(days=1).to_pytimedelta(), Timedelta(days=1).to_timedelta64().astype("timedelta64[s]"), Timedelta(days=1).to_timedelta64().astype("timedelta64[ms]"), ], ids=lambda x: type(x).__name__, ) def test_numeric_arr_mul_tdscalar(self, scalar_td, numeric_idx, box_with_array): # GH#19333 box = box_with_array index = numeric_idx expected = TimedeltaIndex([Timedelta(days=n) for n in range(len(index))]) if isinstance(scalar_td, np.timedelta64): dtype = scalar_td.dtype expected = expected.astype(dtype) elif type(scalar_td) is timedelta: expected = expected.astype("m8[us]")
index = tm.box_expected(index, box) expected = tm.box_expected(expected, box)
result = index * scalar_td tm.assert_equal(result, expected)
commute = scalar_td * index tm.assert_equal(commute, expected)
@pytest.mark.parametrize( "scalar_td", [ Timedelta(days=1), Timedelta(days=1).to_timedelta64(), Timedelta(days=1).to_pytimedelta(), ], ids=lambda x: type(x).__name__, ) @pytest.mark.parametrize("dtype", [np.int64, np.float64]) def test_numeric_arr_mul_tdscalar_numexpr_path( self, dtype, scalar_td, box_with_array ): # GH#44772 for the float64 case box = box_with_array
arr_i8 = np.arange(2 * 10**4).astype(np.int64, copy=False) arr = arr_i8.astype(dtype, copy=False) obj = tm.box_expected(arr, box, transpose=False)
expected = arr_i8.view("timedelta64[D]").astype("timedelta64[ns]") if type(scalar_td) is timedelta: expected = expected.astype("timedelta64[us]")
expected = tm.box_expected(expected, box, transpose=False)
result = obj * scalar_td tm.assert_equal(result, expected)
result = scalar_td * obj tm.assert_equal(result, expected)
def test_numeric_arr_rdiv_tdscalar(self, three_days, numeric_idx, box_with_array): box = box_with_array
index = numeric_idx[1:3]
expected = TimedeltaIndex(["3 Days", "36 Hours"]) if isinstance(three_days, np.timedelta64): dtype = three_days.dtype if dtype < np.dtype("m8[s]"): # i.e. resolution is lower -> use lowest supported resolution dtype = np.dtype("m8[s]") expected = expected.astype(dtype) elif type(three_days) is timedelta: expected = expected.astype("m8[us]") elif isinstance( three_days, (pd.offsets.Day, pd.offsets.Hour, pd.offsets.Minute, pd.offsets.Second), ): # closest reso is Second expected = expected.astype("m8[s]")
index = tm.box_expected(index, box) expected = tm.box_expected(expected, box)
result = three_days / index tm.assert_equal(result, expected)
msg = "cannot use operands with types dtype" with pytest.raises(TypeError, match=msg): index / three_days
@pytest.mark.parametrize( "other", [ Timedelta(hours=31), Timedelta(hours=31).to_pytimedelta(), Timedelta(hours=31).to_timedelta64(), Timedelta(hours=31).to_timedelta64().astype("m8[h]"), np.timedelta64("NaT"), np.timedelta64("NaT", "D"), pd.offsets.Minute(3), pd.offsets.Second(0), # GH#28080 numeric+datetimelike should raise; Timestamp used # to raise NullFrequencyError but that behavior was removed in 1.0 pd.Timestamp("2021-01-01", tz="Asia/Tokyo"), pd.Timestamp("2021-01-01"), pd.Timestamp("2021-01-01").to_pydatetime(), pd.Timestamp("2021-01-01", tz="UTC").to_pydatetime(), pd.Timestamp("2021-01-01").to_datetime64(), np.datetime64("NaT", "ns"), pd.NaT, ], ids=repr, ) def test_add_sub_datetimedeltalike_invalid( self, numeric_idx, other, box_with_array ): box = box_with_array
left = tm.box_expected(numeric_idx, box) msg = "|".join( [ "unsupported operand type", "Addition/subtraction of integers and integer-arrays", "Instead of adding/subtracting", "cannot use operands with types dtype", "Concatenation operation is not implemented for NumPy arrays", "Cannot (add|subtract) NaT (to|from) ndarray", # pd.array vs np.datetime64 case r"operand type\(s\) all returned NotImplemented from __array_ufunc__", "can only perform ops with numeric values", "cannot subtract DatetimeArray from ndarray", # pd.Timedelta(1) + Index([0, 1, 2]) "Cannot add or subtract Timedelta from integers", ] ) assert_invalid_addsub_type(left, other, msg)
# ------------------------------------------------------------------# Arithmetic
class TestDivisionByZero: def test_div_zero(self, zero, numeric_idx): idx = numeric_idx
expected = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64) # We only adjust for Index, because Series does not yet apply # the adjustment correctly. expected2 = adjust_negative_zero(zero, expected)
result = idx / zero tm.assert_index_equal(result, expected2) ser_compat = Series(idx).astype("i8") / np.array(zero).astype("i8") tm.assert_series_equal(ser_compat, Series(expected))
def test_floordiv_zero(self, zero, numeric_idx): idx = numeric_idx
expected = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64) # We only adjust for Index, because Series does not yet apply # the adjustment correctly. expected2 = adjust_negative_zero(zero, expected)
result = idx // zero tm.assert_index_equal(result, expected2) ser_compat = Series(idx).astype("i8") // np.array(zero).astype("i8") tm.assert_series_equal(ser_compat, Series(expected))
def test_mod_zero(self, zero, numeric_idx): idx = numeric_idx
expected = Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64) result = idx % zero tm.assert_index_equal(result, expected) ser_compat = Series(idx).astype("i8") % np.array(zero).astype("i8") tm.assert_series_equal(ser_compat, Series(result))
def test_divmod_zero(self, zero, numeric_idx): idx = numeric_idx
exleft = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64) exright = Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64) exleft = adjust_negative_zero(zero, exleft)
result = divmod(idx, zero) tm.assert_index_equal(result[0], exleft) tm.assert_index_equal(result[1], exright)
@pytest.mark.parametrize("op", [operator.truediv, operator.floordiv]) def test_div_negative_zero(self, zero, numeric_idx, op): # Check that -1 / -0.0 returns np.inf, not -np.inf if numeric_idx.dtype == np.uint64: pytest.skip(f"Div by negative 0 not relevant for {numeric_idx.dtype}") idx = numeric_idx - 3
expected = Index([-np.inf, -np.inf, -np.inf, np.nan, np.inf], dtype=np.float64) expected = adjust_negative_zero(zero, expected)
result = op(idx, zero) tm.assert_index_equal(result, expected)
# ------------------------------------------------------------------
@pytest.mark.parametrize("dtype1", [np.int64, np.float64, np.uint64]) def test_ser_div_ser( self, switch_numexpr_min_elements, dtype1, any_real_numpy_dtype, ): # no longer do integer div for any ops, but deal with the 0's dtype2 = any_real_numpy_dtype
first = Series([3, 4, 5, 8], name="first").astype(dtype1) second = Series([0, 0, 0, 3], name="second").astype(dtype2)
with np.errstate(all="ignore"): expected = Series( first.values.astype(np.float64) / second.values, dtype="float64", name=None, ) expected.iloc[0:3] = np.inf if first.dtype == "int64" and second.dtype == "float32": # when using numexpr, the casting rules are slightly different # and int64/float32 combo results in float32 instead of float64 if expr.USE_NUMEXPR and switch_numexpr_min_elements == 0: expected = expected.astype("float32")
result = first / second tm.assert_series_equal(result, expected) assert not result.equals(second / first)
@pytest.mark.parametrize("dtype1", [np.int64, np.float64, np.uint64]) def test_ser_divmod_zero(self, dtype1, any_real_numpy_dtype): # GH#26987 dtype2 = any_real_numpy_dtype left = Series([1, 1]).astype(dtype1) right = Series([0, 2]).astype(dtype2)
# GH#27321 pandas convention is to set 1 // 0 to np.inf, as opposed # to numpy which sets to np.nan; patch `expected[0]` below expected = left // right, left % right expected = list(expected) expected[0] = expected[0].astype(np.float64) expected[0][0] = np.inf result = divmod(left, right)
tm.assert_series_equal(result[0], expected[0]) tm.assert_series_equal(result[1], expected[1])
# rdivmod case result = divmod(left.values, right) tm.assert_series_equal(result[0], expected[0]) tm.assert_series_equal(result[1], expected[1])
def test_ser_divmod_inf(self): left = Series([np.inf, 1.0]) right = Series([np.inf, 2.0])
expected = left // right, left % right result = divmod(left, right)
tm.assert_series_equal(result[0], expected[0]) tm.assert_series_equal(result[1], expected[1])
# rdivmod case result = divmod(left.values, right) tm.assert_series_equal(result[0], expected[0]) tm.assert_series_equal(result[1], expected[1])
def test_rdiv_zero_compat(self): # GH#8674 zero_array = np.array([0] * 5) data = np.random.default_rng(2).standard_normal(5) expected = Series([0.0] * 5)
result = zero_array / Series(data) tm.assert_series_equal(result, expected)
result = Series(zero_array) / data tm.assert_series_equal(result, expected)
result = Series(zero_array) / Series(data) tm.assert_series_equal(result, expected)
def test_div_zero_inf_signs(self): # GH#9144, inf signing ser = Series([-1, 0, 1], name="first") expected = Series([-np.inf, np.nan, np.inf], name="first")
result = ser / 0 tm.assert_series_equal(result, expected)
def test_rdiv_zero(self): # GH#9144 ser = Series([-1, 0, 1], name="first") expected = Series([0.0, np.nan, 0.0], name="first")
result = 0 / ser tm.assert_series_equal(result, expected)
def test_floordiv_div(self): # GH#9144 ser = Series([-1, 0, 1], name="first")
result = ser // 0 expected = Series([-np.inf, np.nan, np.inf], name="first") tm.assert_series_equal(result, expected)
def test_df_div_zero_df(self): # integer div, but deal with the 0's (GH#9144) df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]}) result = df / df
first = Series([1.0, 1.0, 1.0, 1.0]) second = Series([np.nan, np.nan, np.nan, 1]) expected = pd.DataFrame({"first": first, "second": second}) tm.assert_frame_equal(result, expected)
def test_df_div_zero_array(self): # integer div, but deal with the 0's (GH#9144) df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
first = Series([1.0, 1.0, 1.0, 1.0]) second = Series([np.nan, np.nan, np.nan, 1]) expected = pd.DataFrame({"first": first, "second": second})
with np.errstate(all="ignore"): arr = df.values.astype("float") / df.values result = pd.DataFrame(arr, index=df.index, columns=df.columns) tm.assert_frame_equal(result, expected)
def test_df_div_zero_int(self): # integer div, but deal with the 0's (GH#9144) df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
result = df / 0 expected = pd.DataFrame(np.inf, index=df.index, columns=df.columns) expected.iloc[0:3, 1] = np.nan tm.assert_frame_equal(result, expected)
# numpy has a slightly different (wrong) treatment with np.errstate(all="ignore"): arr = df.values.astype("float64") / 0 result2 = pd.DataFrame(arr, index=df.index, columns=df.columns) tm.assert_frame_equal(result2, expected)
def test_df_div_zero_series_does_not_commute(self): # integer div, but deal with the 0's (GH#9144) df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 5))) ser = df[0] res = ser / df res2 = df / ser assert not res.fillna(0).equals(res2.fillna(0))
# ------------------------------------------------------------------ # Mod By Zero
def test_df_mod_zero_df(self, using_array_manager): # GH#3590, modulo as ints df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]}) # this is technically wrong, as the integer portion is coerced to float first = Series([0, 0, 0, 0]) if not using_array_manager: # INFO(ArrayManager) BlockManager doesn't preserve dtype per column # while ArrayManager performs op column-wisedoes and thus preserves # dtype if possible first = first.astype("float64") second = Series([np.nan, np.nan, np.nan, 0]) expected = pd.DataFrame({"first": first, "second": second}) result = df % df tm.assert_frame_equal(result, expected)
# GH#38939 If we dont pass copy=False, df is consolidated and # result["first"] is float64 instead of int64 df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]}, copy=False) first = Series([0, 0, 0, 0], dtype="int64") second = Series([np.nan, np.nan, np.nan, 0]) expected = pd.DataFrame({"first": first, "second": second}) result = df % df tm.assert_frame_equal(result, expected)
def test_df_mod_zero_array(self): # GH#3590, modulo as ints df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
# this is technically wrong, as the integer portion is coerced to float # ### first = Series([0, 0, 0, 0], dtype="float64") second = Series([np.nan, np.nan, np.nan, 0]) expected = pd.DataFrame({"first": first, "second": second})
# numpy has a slightly different (wrong) treatment with np.errstate(all="ignore"): arr = df.values % df.values result2 = pd.DataFrame(arr, index=df.index, columns=df.columns, dtype="float64") result2.iloc[0:3, 1] = np.nan tm.assert_frame_equal(result2, expected)
def test_df_mod_zero_int(self): # GH#3590, modulo as ints df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
result = df % 0 expected = pd.DataFrame(np.nan, index=df.index, columns=df.columns) tm.assert_frame_equal(result, expected)
# numpy has a slightly different (wrong) treatment with np.errstate(all="ignore"): arr = df.values.astype("float64") % 0 result2 = pd.DataFrame(arr, index=df.index, columns=df.columns) tm.assert_frame_equal(result2, expected)
def test_df_mod_zero_series_does_not_commute(self): # GH#3590, modulo as ints # not commutative with series df = pd.DataFrame(np.random.default_rng(2).standard_normal((10, 5))) ser = df[0] res = ser % df res2 = df % ser assert not res.fillna(0).equals(res2.fillna(0))
class TestMultiplicationDivision: # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__ # for non-timestamp/timedelta/period dtypes
def test_divide_decimal(self, box_with_array): # resolves issue GH#9787 box = box_with_array ser = Series([Decimal(10)]) expected = Series([Decimal(5)])
ser = tm.box_expected(ser, box) expected = tm.box_expected(expected, box)
result = ser / Decimal(2)
tm.assert_equal(result, expected)
result = ser // Decimal(2) tm.assert_equal(result, expected)
def test_div_equiv_binop(self): # Test Series.div as well as Series.__div__ # float/integer issue # GH#7785 first = Series([1, 0], name="first") second = Series([-0.01, -0.02], name="second") expected = Series([-0.01, -np.inf])
result = second.div(first) tm.assert_series_equal(result, expected, check_names=False)
result = second / first tm.assert_series_equal(result, expected)
def test_div_int(self, numeric_idx): idx = numeric_idx result = idx / 1 expected = idx.astype("float64") tm.assert_index_equal(result, expected)
result = idx / 2 expected = Index(idx.values / 2) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("op", [operator.mul, ops.rmul, operator.floordiv]) def test_mul_int_identity(self, op, numeric_idx, box_with_array): idx = numeric_idx idx = tm.box_expected(idx, box_with_array)
result = op(idx, 1) tm.assert_equal(result, idx)
def test_mul_int_array(self, numeric_idx): idx = numeric_idx didx = idx * idx
result = idx * np.array(5, dtype="int64") tm.assert_index_equal(result, idx * 5)
arr_dtype = "uint64" if idx.dtype == np.uint64 else "int64" result = idx * np.arange(5, dtype=arr_dtype) tm.assert_index_equal(result, didx)
def test_mul_int_series(self, numeric_idx): idx = numeric_idx didx = idx * idx
arr_dtype = "uint64" if idx.dtype == np.uint64 else "int64" result = idx * Series(np.arange(5, dtype=arr_dtype)) tm.assert_series_equal(result, Series(didx))
def test_mul_float_series(self, numeric_idx): idx = numeric_idx rng5 = np.arange(5, dtype="float64")
result = idx * Series(rng5 + 0.1) expected = Series(rng5 * (rng5 + 0.1)) tm.assert_series_equal(result, expected)
def test_mul_index(self, numeric_idx): idx = numeric_idx
result = idx * idx tm.assert_index_equal(result, idx**2)
def test_mul_datelike_raises(self, numeric_idx): idx = numeric_idx msg = "cannot perform __rmul__ with this index type" with pytest.raises(TypeError, match=msg): idx * date_range("20130101", periods=5)
def test_mul_size_mismatch_raises(self, numeric_idx): idx = numeric_idx msg = "operands could not be broadcast together" with pytest.raises(ValueError, match=msg): idx * idx[0:3] with pytest.raises(ValueError, match=msg): idx * np.array([1, 2])
@pytest.mark.parametrize("op", [operator.pow, ops.rpow]) def test_pow_float(self, op, numeric_idx, box_with_array): # test power calculations both ways, GH#14973 box = box_with_array idx = numeric_idx expected = Index(op(idx.values, 2.0))
idx = tm.box_expected(idx, box) expected = tm.box_expected(expected, box)
result = op(idx, 2.0) tm.assert_equal(result, expected)
def test_modulo(self, numeric_idx, box_with_array): # GH#9244 box = box_with_array idx = numeric_idx expected = Index(idx.values % 2)
idx = tm.box_expected(idx, box) expected = tm.box_expected(expected, box)
result = idx % 2 tm.assert_equal(result, expected)
def test_divmod_scalar(self, numeric_idx): idx = numeric_idx
result = divmod(idx, 2) with np.errstate(all="ignore"): div, mod = divmod(idx.values, 2)
expected = Index(div), Index(mod) for r, e in zip(result, expected): tm.assert_index_equal(r, e)
def test_divmod_ndarray(self, numeric_idx): idx = numeric_idx other = np.ones(idx.values.shape, dtype=idx.values.dtype) * 2
result = divmod(idx, other) with np.errstate(all="ignore"): div, mod = divmod(idx.values, other)
expected = Index(div), Index(mod) for r, e in zip(result, expected): tm.assert_index_equal(r, e)
def test_divmod_series(self, numeric_idx): idx = numeric_idx other = np.ones(idx.values.shape, dtype=idx.values.dtype) * 2
result = divmod(idx, Series(other)) with np.errstate(all="ignore"): div, mod = divmod(idx.values, other)
expected = Series(div), Series(mod) for r, e in zip(result, expected): tm.assert_series_equal(r, e)
@pytest.mark.parametrize("other", [np.nan, 7, -23, 2.718, -3.14, np.inf]) def test_ops_np_scalar(self, other): vals = np.random.default_rng(2).standard_normal((5, 3)) f = lambda x: pd.DataFrame( x, index=list("ABCDE"), columns=["jim", "joe", "jolie"] )
df = f(vals)
tm.assert_frame_equal(df / np.array(other), f(vals / other)) tm.assert_frame_equal(np.array(other) * df, f(vals * other)) tm.assert_frame_equal(df + np.array(other), f(vals + other)) tm.assert_frame_equal(np.array(other) - df, f(other - vals))
# TODO: This came from series.test.test_operators, needs cleanup def test_operators_frame(self): # rpow does not work with DataFrame ts = Series( np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10), name="ts", ) ts.name = "ts"
df = pd.DataFrame({"A": ts})
tm.assert_series_equal(ts + ts, ts + df["A"], check_names=False) tm.assert_series_equal(ts**ts, ts ** df["A"], check_names=False) tm.assert_series_equal(ts < ts, ts < df["A"], check_names=False) tm.assert_series_equal(ts / ts, ts / df["A"], check_names=False)
# TODO: this came from tests.series.test_analytics, needs cleanup and # de-duplication with test_modulo above def test_modulo2(self): with np.errstate(all="ignore"): # GH#3590, modulo as ints p = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]}) result = p["first"] % p["second"] expected = Series(p["first"].values % p["second"].values, dtype="float64") expected.iloc[0:3] = np.nan tm.assert_series_equal(result, expected)
result = p["first"] % 0 expected = Series(np.nan, index=p.index, name="first") tm.assert_series_equal(result, expected)
p = p.astype("float64") result = p["first"] % p["second"] expected = Series(p["first"].values % p["second"].values) tm.assert_series_equal(result, expected)
p = p.astype("float64") result = p["first"] % p["second"] result2 = p["second"] % p["first"] assert not result.equals(result2)
def test_modulo_zero_int(self): # GH#9144 with np.errstate(all="ignore"): s = Series([0, 1])
result = s % 0 expected = Series([np.nan, np.nan]) tm.assert_series_equal(result, expected)
result = 0 % s expected = Series([np.nan, 0.0]) tm.assert_series_equal(result, expected)
class TestAdditionSubtraction: # __add__, __sub__, __radd__, __rsub__, __iadd__, __isub__ # for non-timestamp/timedelta/period dtypes
@pytest.mark.parametrize( "first, second, expected", [ ( Series([1, 2, 3], index=list("ABC"), name="x"), Series([2, 2, 2], index=list("ABD"), name="x"), Series([3.0, 4.0, np.nan, np.nan], index=list("ABCD"), name="x"), ), ( Series([1, 2, 3], index=list("ABC"), name="x"), Series([2, 2, 2, 2], index=list("ABCD"), name="x"), Series([3, 4, 5, np.nan], index=list("ABCD"), name="x"), ), ], ) def test_add_series(self, first, second, expected): # GH#1134 tm.assert_series_equal(first + second, expected) tm.assert_series_equal(second + first, expected)
@pytest.mark.parametrize( "first, second, expected", [ ( pd.DataFrame({"x": [1, 2, 3]}, index=list("ABC")), pd.DataFrame({"x": [2, 2, 2]}, index=list("ABD")), pd.DataFrame({"x": [3.0, 4.0, np.nan, np.nan]}, index=list("ABCD")), ), ( pd.DataFrame({"x": [1, 2, 3]}, index=list("ABC")), pd.DataFrame({"x": [2, 2, 2, 2]}, index=list("ABCD")), pd.DataFrame({"x": [3, 4, 5, np.nan]}, index=list("ABCD")), ), ], ) def test_add_frames(self, first, second, expected): # GH#1134 tm.assert_frame_equal(first + second, expected) tm.assert_frame_equal(second + first, expected)
# TODO: This came from series.test.test_operators, needs cleanup def test_series_frame_radd_bug(self, fixed_now_ts): # GH#353 vals = Series([str(i) for i in range(5)]) result = "foo_" + vals expected = vals.map(lambda x: "foo_" + x) tm.assert_series_equal(result, expected)
frame = pd.DataFrame({"vals": vals}) result = "foo_" + frame expected = pd.DataFrame({"vals": vals.map(lambda x: "foo_" + x)}) tm.assert_frame_equal(result, expected)
ts = Series( np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10), name="ts", )
# really raise this time fix_now = fixed_now_ts.to_pydatetime() msg = "|".join( [ "unsupported operand type", # wrong error message, see https://github.com/numpy/numpy/issues/18832 "Concatenation operation", ] ) with pytest.raises(TypeError, match=msg): fix_now + ts
with pytest.raises(TypeError, match=msg): ts + fix_now
# TODO: This came from series.test.test_operators, needs cleanup def test_datetime64_with_index(self): # arithmetic integer ops with an index ser = Series(np.random.default_rng(2).standard_normal(5)) expected = ser - ser.index.to_series() result = ser - ser.index tm.assert_series_equal(result, expected)
# GH#4629 # arithmetic datetime64 ops with an index ser = Series( date_range("20130101", periods=5), index=date_range("20130101", periods=5), ) expected = ser - ser.index.to_series() result = ser - ser.index tm.assert_series_equal(result, expected)
msg = "cannot subtract PeriodArray from DatetimeArray" with pytest.raises(TypeError, match=msg): # GH#18850 result = ser - ser.index.to_period()
df = pd.DataFrame( np.random.default_rng(2).standard_normal((5, 2)), index=date_range("20130101", periods=5), ) df["date"] = pd.Timestamp("20130102") df["expected"] = df["date"] - df.index.to_series() df["result"] = df["date"] - df.index tm.assert_series_equal(df["result"], df["expected"], check_names=False)
# TODO: taken from tests.frame.test_operators, needs cleanup def test_frame_operators(self, float_frame): frame = float_frame
garbage = np.random.default_rng(2).random(4) colSeries = Series(garbage, index=np.array(frame.columns))
idSum = frame + frame seriesSum = frame + colSeries
for col, series in idSum.items(): for idx, val in series.items(): origVal = frame[col][idx] * 2 if not np.isnan(val): assert val == origVal else: assert np.isnan(origVal)
for col, series in seriesSum.items(): for idx, val in series.items(): origVal = frame[col][idx] + colSeries[col] if not np.isnan(val): assert val == origVal else: assert np.isnan(origVal)
def test_frame_operators_col_align(self, float_frame): frame2 = pd.DataFrame(float_frame, columns=["D", "C", "B", "A"]) added = frame2 + frame2 expected = frame2 * 2 tm.assert_frame_equal(added, expected)
def test_frame_operators_none_to_nan(self): df = pd.DataFrame({"a": ["a", None, "b"]}) tm.assert_frame_equal(df + df, pd.DataFrame({"a": ["aa", np.nan, "bb"]}))
@pytest.mark.parametrize("dtype", ("float", "int64")) def test_frame_operators_empty_like(self, dtype): # Test for issue #10181 frames = [ pd.DataFrame(dtype=dtype), pd.DataFrame(columns=["A"], dtype=dtype), pd.DataFrame(index=[0], dtype=dtype), ] for df in frames: assert (df + df).equals(df) tm.assert_frame_equal(df + df, df)
@pytest.mark.parametrize( "func", [lambda x: x * 2, lambda x: x[::2], lambda x: 5], ids=["multiply", "slice", "constant"], ) def test_series_operators_arithmetic(self, all_arithmetic_functions, func): op = all_arithmetic_functions series = Series( np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10), name="ts", ) other = func(series) compare_op(series, other, op)
@pytest.mark.parametrize( "func", [lambda x: x + 1, lambda x: 5], ids=["add", "constant"] ) def test_series_operators_compare(self, comparison_op, func): op = comparison_op series = Series( np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10), name="ts", ) other = func(series) compare_op(series, other, op)
@pytest.mark.parametrize( "func", [lambda x: x * 2, lambda x: x[::2], lambda x: 5], ids=["multiply", "slice", "constant"], ) def test_divmod(self, func): series = Series( np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10), name="ts", ) other = func(series) results = divmod(series, other) if isinstance(other, abc.Iterable) and len(series) != len(other): # if the lengths don't match, this is the test where we use # `tser[::2]`. Pad every other value in `other_np` with nan. other_np = [] for n in other: other_np.append(n) other_np.append(np.nan) else: other_np = other other_np = np.asarray(other_np) with np.errstate(all="ignore"): expecteds = divmod(series.values, np.asarray(other_np))
for result, expected in zip(results, expecteds): # check the values, name, and index separately tm.assert_almost_equal(np.asarray(result), expected)
assert result.name == series.name tm.assert_index_equal(result.index, series.index._with_freq(None))
def test_series_divmod_zero(self): # Check that divmod uses pandas convention for division by zero, # which does not match numpy. # pandas convention has # 1/0 == np.inf # -1/0 == -np.inf # 1/-0.0 == -np.inf # -1/-0.0 == np.inf tser = Series( np.arange(1, 11, dtype=np.float64), index=date_range("2020-01-01", periods=10), name="ts", ) other = tser * 0
result = divmod(tser, other) exp1 = Series([np.inf] * len(tser), index=tser.index, name="ts") exp2 = Series([np.nan] * len(tser), index=tser.index, name="ts") tm.assert_series_equal(result[0], exp1) tm.assert_series_equal(result[1], exp2)
class TestUFuncCompat: # TODO: add more dtypes @pytest.mark.parametrize("holder", [Index, RangeIndex, Series]) @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64]) def test_ufunc_compat(self, holder, dtype): box = Series if holder is Series else Index
if holder is RangeIndex: if dtype != np.int64: pytest.skip(f"dtype {dtype} not relevant for RangeIndex") idx = RangeIndex(0, 5, name="foo") else: idx = holder(np.arange(5, dtype=dtype), name="foo") result = np.sin(idx) expected = box(np.sin(np.arange(5, dtype=dtype)), name="foo") tm.assert_equal(result, expected)
# TODO: add more dtypes @pytest.mark.parametrize("holder", [Index, Series]) @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64]) def test_ufunc_coercions(self, holder, dtype): idx = holder([1, 2, 3, 4, 5], dtype=dtype, name="x") box = Series if holder is Series else Index
result = np.sqrt(idx) assert result.dtype == "f8" and isinstance(result, box) exp = Index(np.sqrt(np.array([1, 2, 3, 4, 5], dtype=np.float64)), name="x") exp = tm.box_expected(exp, box) tm.assert_equal(result, exp)
result = np.divide(idx, 2.0) assert result.dtype == "f8" and isinstance(result, box) exp = Index([0.5, 1.0, 1.5, 2.0, 2.5], dtype=np.float64, name="x") exp = tm.box_expected(exp, box) tm.assert_equal(result, exp)
# _evaluate_numeric_binop result = idx + 2.0 assert result.dtype == "f8" and isinstance(result, box) exp = Index([3.0, 4.0, 5.0, 6.0, 7.0], dtype=np.float64, name="x") exp = tm.box_expected(exp, box) tm.assert_equal(result, exp)
result = idx - 2.0 assert result.dtype == "f8" and isinstance(result, box) exp = Index([-1.0, 0.0, 1.0, 2.0, 3.0], dtype=np.float64, name="x") exp = tm.box_expected(exp, box) tm.assert_equal(result, exp)
result = idx * 1.0 assert result.dtype == "f8" and isinstance(result, box) exp = Index([1.0, 2.0, 3.0, 4.0, 5.0], dtype=np.float64, name="x") exp = tm.box_expected(exp, box) tm.assert_equal(result, exp)
result = idx / 2.0 assert result.dtype == "f8" and isinstance(result, box) exp = Index([0.5, 1.0, 1.5, 2.0, 2.5], dtype=np.float64, name="x") exp = tm.box_expected(exp, box) tm.assert_equal(result, exp)
# TODO: add more dtypes @pytest.mark.parametrize("holder", [Index, Series]) @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64]) def test_ufunc_multiple_return_values(self, holder, dtype): obj = holder([1, 2, 3], dtype=dtype, name="x") box = Series if holder is Series else Index
result = np.modf(obj) assert isinstance(result, tuple) exp1 = Index([0.0, 0.0, 0.0], dtype=np.float64, name="x") exp2 = Index([1.0, 2.0, 3.0], dtype=np.float64, name="x") tm.assert_equal(result[0], tm.box_expected(exp1, box)) tm.assert_equal(result[1], tm.box_expected(exp2, box))
def test_ufunc_at(self): s = Series([0, 1, 2], index=[1, 2, 3], name="x") np.add.at(s, [0, 2], 10) expected = Series([10, 1, 12], index=[1, 2, 3], name="x") tm.assert_series_equal(s, expected)
class TestObjectDtypeEquivalence: # Tests that arithmetic operations match operations executed elementwise
@pytest.mark.parametrize("dtype", [None, object]) def test_numarr_with_dtype_add_nan(self, dtype, box_with_array): box = box_with_array ser = Series([1, 2, 3], dtype=dtype) expected = Series([np.nan, np.nan, np.nan], dtype=dtype)
ser = tm.box_expected(ser, box) expected = tm.box_expected(expected, box)
result = np.nan + ser tm.assert_equal(result, expected)
result = ser + np.nan tm.assert_equal(result, expected)
@pytest.mark.parametrize("dtype", [None, object]) def test_numarr_with_dtype_add_int(self, dtype, box_with_array): box = box_with_array ser = Series([1, 2, 3], dtype=dtype) expected = Series([2, 3, 4], dtype=dtype)
ser = tm.box_expected(ser, box) expected = tm.box_expected(expected, box)
result = 1 + ser tm.assert_equal(result, expected)
result = ser + 1 tm.assert_equal(result, expected)
# TODO: moved from tests.series.test_operators; needs cleanup @pytest.mark.parametrize( "op", [operator.add, operator.sub, operator.mul, operator.truediv, operator.floordiv], ) def test_operators_reverse_object(self, op): # GH#56 arr = Series( np.random.default_rng(2).standard_normal(10), index=np.arange(10), dtype=object, )
result = op(1.0, arr) expected = op(1.0, arr.astype(float)) tm.assert_series_equal(result.astype(float), expected)
class TestNumericArithmeticUnsorted: # Tests in this class have been moved from type-specific test modules # but not yet sorted, parametrized, and de-duplicated @pytest.mark.parametrize( "op", [ operator.add, operator.sub, operator.mul, operator.floordiv, operator.truediv, ], ) @pytest.mark.parametrize( "idx1", [ RangeIndex(0, 10, 1), RangeIndex(0, 20, 2), RangeIndex(-10, 10, 2), RangeIndex(5, -5, -1), ], ) @pytest.mark.parametrize( "idx2", [ RangeIndex(0, 10, 1), RangeIndex(0, 20, 2), RangeIndex(-10, 10, 2), RangeIndex(5, -5, -1), ], ) def test_binops_index(self, op, idx1, idx2): idx1 = idx1._rename("foo") idx2 = idx2._rename("bar") result = op(idx1, idx2) expected = op(Index(idx1.to_numpy()), Index(idx2.to_numpy())) tm.assert_index_equal(result, expected, exact="equiv")
@pytest.mark.parametrize( "op", [ operator.add, operator.sub, operator.mul, operator.floordiv, operator.truediv, ], ) @pytest.mark.parametrize( "idx", [ RangeIndex(0, 10, 1), RangeIndex(0, 20, 2), RangeIndex(-10, 10, 2), RangeIndex(5, -5, -1), ], ) @pytest.mark.parametrize("scalar", [-1, 1, 2]) def test_binops_index_scalar(self, op, idx, scalar): result = op(idx, scalar) expected = op(Index(idx.to_numpy()), scalar) tm.assert_index_equal(result, expected, exact="equiv")
@pytest.mark.parametrize("idx1", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)]) @pytest.mark.parametrize("idx2", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)]) def test_binops_index_pow(self, idx1, idx2): # numpy does not allow powers of negative integers so test separately # https://github.com/numpy/numpy/pull/8127 idx1 = idx1._rename("foo") idx2 = idx2._rename("bar") result = pow(idx1, idx2) expected = pow(Index(idx1.to_numpy()), Index(idx2.to_numpy())) tm.assert_index_equal(result, expected, exact="equiv")
@pytest.mark.parametrize("idx", [RangeIndex(0, 10, 1), RangeIndex(0, 20, 2)]) @pytest.mark.parametrize("scalar", [1, 2]) def test_binops_index_scalar_pow(self, idx, scalar): # numpy does not allow powers of negative integers so test separately # https://github.com/numpy/numpy/pull/8127 result = pow(idx, scalar) expected = pow(Index(idx.to_numpy()), scalar) tm.assert_index_equal(result, expected, exact="equiv")
# TODO: divmod? @pytest.mark.parametrize( "op", [ operator.add, operator.sub, operator.mul, operator.floordiv, operator.truediv, operator.pow, operator.mod, ], ) def test_arithmetic_with_frame_or_series(self, op): # check that we return NotImplemented when operating with Series # or DataFrame index = RangeIndex(5) other = Series(np.random.default_rng(2).standard_normal(5))
expected = op(Series(index), other) result = op(index, other) tm.assert_series_equal(result, expected)
other = pd.DataFrame(np.random.default_rng(2).standard_normal((2, 5))) expected = op(pd.DataFrame([index, index]), other) result = op(index, other) tm.assert_frame_equal(result, expected)
def test_numeric_compat2(self): # validate that we are handling the RangeIndex overrides to numeric ops # and returning RangeIndex where possible
idx = RangeIndex(0, 10, 2)
result = idx * 2 expected = RangeIndex(0, 20, 4) tm.assert_index_equal(result, expected, exact=True)
result = idx + 2 expected = RangeIndex(2, 12, 2) tm.assert_index_equal(result, expected, exact=True)
result = idx - 2 expected = RangeIndex(-2, 8, 2) tm.assert_index_equal(result, expected, exact=True)
result = idx / 2 expected = RangeIndex(0, 5, 1).astype("float64") tm.assert_index_equal(result, expected, exact=True)
result = idx / 4 expected = RangeIndex(0, 10, 2) / 4 tm.assert_index_equal(result, expected, exact=True)
result = idx // 1 expected = idx tm.assert_index_equal(result, expected, exact=True)
# __mul__ result = idx * idx expected = Index(idx.values * idx.values) tm.assert_index_equal(result, expected, exact=True)
# __pow__ idx = RangeIndex(0, 1000, 2) result = idx**2 expected = Index(idx._values) ** 2 tm.assert_index_equal(Index(result.values), expected, exact=True)
@pytest.mark.parametrize( "idx, div, expected", [ # TODO: add more dtypes (RangeIndex(0, 1000, 2), 2, RangeIndex(0, 500, 1)), (RangeIndex(-99, -201, -3), -3, RangeIndex(33, 67, 1)), ( RangeIndex(0, 1000, 1), 2, Index(RangeIndex(0, 1000, 1)._values) // 2, ), ( RangeIndex(0, 100, 1), 2.0, Index(RangeIndex(0, 100, 1)._values) // 2.0, ), (RangeIndex(0), 50, RangeIndex(0)), (RangeIndex(2, 4, 2), 3, RangeIndex(0, 1, 1)), (RangeIndex(-5, -10, -6), 4, RangeIndex(-2, -1, 1)), (RangeIndex(-100, -200, 3), 2, RangeIndex(0)), ], ) def test_numeric_compat2_floordiv(self, idx, div, expected): # __floordiv__ tm.assert_index_equal(idx // div, expected, exact=True)
@pytest.mark.parametrize("dtype", [np.int64, np.float64]) @pytest.mark.parametrize("delta", [1, 0, -1]) def test_addsub_arithmetic(self, dtype, delta): # GH#8142 delta = dtype(delta) index = Index([10, 11, 12], dtype=dtype) result = index + delta expected = Index(index.values + delta, dtype=dtype) tm.assert_index_equal(result, expected)
# this subtraction used to fail result = index - delta expected = Index(index.values - delta, dtype=dtype) tm.assert_index_equal(result, expected)
tm.assert_index_equal(index + index, 2 * index) tm.assert_index_equal(index - index, 0 * index) assert not (index - index).empty
def test_pow_nan_with_zero(self, box_with_array): left = Index([np.nan, np.nan, np.nan]) right = Index([0, 0, 0]) expected = Index([1.0, 1.0, 1.0])
left = tm.box_expected(left, box_with_array) right = tm.box_expected(right, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = left**right tm.assert_equal(result, expected)
def test_fill_value_inf_masking(): # GH #27464 make sure we mask 0/1 with Inf and not NaN df = pd.DataFrame({"A": [0, 1, 2], "B": [1.1, None, 1.1]})
other = pd.DataFrame({"A": [1.1, 1.2, 1.3]}, index=[0, 2, 3])
result = df.rfloordiv(other, fill_value=1)
expected = pd.DataFrame( {"A": [np.inf, 1.0, 0.0, 1.0], "B": [0.0, np.nan, 0.0, np.nan]} ) tm.assert_frame_equal(result, expected)
def test_dataframe_div_silenced(): # GH#26793 pdf1 = pd.DataFrame( { "A": np.arange(10), "B": [np.nan, 1, 2, 3, 4] * 2, "C": [np.nan] * 10, "D": np.arange(10), }, index=list("abcdefghij"), columns=list("ABCD"), ) pdf2 = pd.DataFrame( np.random.default_rng(2).standard_normal((10, 4)), index=list("abcdefghjk"), columns=list("ABCX"), ) with tm.assert_produces_warning(None): pdf1.div(pdf2, fill_value=0)
@pytest.mark.parametrize( "data, expected_data", [([0, 1, 2], [0, 2, 4])],)def test_integer_array_add_list_like( box_pandas_1d_array, box_1d_array, data, expected_data): # GH22606 Verify operators with IntegerArray and list-likes arr = array(data, dtype="Int64") container = box_pandas_1d_array(arr) left = container + box_1d_array(data) right = box_1d_array(data) + container
if Series in [box_1d_array, box_pandas_1d_array]: cls = Series elif Index in [box_1d_array, box_pandas_1d_array]: cls = Index else: cls = array
expected = cls(expected_data, dtype="Int64")
tm.assert_equal(left, expected) tm.assert_equal(right, expected)
def test_sub_multiindex_swapped_levels(): # GH 9952 df = pd.DataFrame( {"a": np.random.default_rng(2).standard_normal(6)}, index=pd.MultiIndex.from_product( [["a", "b"], [0, 1, 2]], names=["levA", "levB"] ), ) df2 = df.copy() df2.index = df2.index.swaplevel(0, 1) result = df - df2 expected = pd.DataFrame([0.0] * 6, columns=["a"], index=df.index) tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("power", [1, 2, 5])@pytest.mark.parametrize("string_size", [0, 1, 2, 5])def test_empty_str_comparison(power, string_size): # GH 37348 a = np.array(range(10**power)) right = pd.DataFrame(a, dtype=np.int64) left = " " * string_size
result = right == left expected = pd.DataFrame(np.zeros(right.shape, dtype=bool)) tm.assert_frame_equal(result, expected)
def test_series_add_sub_with_UInt64(): # GH 22023 series1 = Series([1, 2, 3]) series2 = Series([2, 1, 3], dtype="UInt64")
result = series1 + series2 expected = Series([3, 3, 6], dtype="Float64") tm.assert_series_equal(result, expected)
result = series1 - series2 expected = Series([-1, 1, 0], dtype="Float64") tm.assert_series_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420# Arithmetic tests for DataFrame/Series/Index/Array classes that should# behave identically.# Specifically for object dtypeimport datetimefrom decimal import Decimalimport operator
import numpy as npimport pytest
from pandas._config import using_pyarrow_string_dtype
import pandas.util._test_decorators as td
import pandas as pdfrom pandas import ( Series, Timestamp, option_context,)import pandas._testing as tmfrom pandas.core import ops
# ------------------------------------------------------------------# Comparisons
class TestObjectComparisons: def test_comparison_object_numeric_nas(self, comparison_op): ser = Series(np.random.default_rng(2).standard_normal(10), dtype=object) shifted = ser.shift(2)
func = comparison_op
result = func(ser, shifted) expected = func(ser.astype(float), shifted.astype(float)) tm.assert_series_equal(result, expected)
@pytest.mark.parametrize( "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))] ) def test_object_comparisons(self, infer_string): with option_context("future.infer_string", infer_string): ser = Series(["a", "b", np.nan, "c", "a"])
result = ser == "a" expected = Series([True, False, False, False, True]) tm.assert_series_equal(result, expected)
result = ser < "a" expected = Series([False, False, False, False, False]) tm.assert_series_equal(result, expected)
result = ser != "a" expected = -(ser == "a") tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", [None, object]) def test_more_na_comparisons(self, dtype): left = Series(["a", np.nan, "c"], dtype=dtype) right = Series(["a", np.nan, "d"], dtype=dtype)
result = left == right expected = Series([True, False, False]) tm.assert_series_equal(result, expected)
result = left != right expected = Series([False, True, True]) tm.assert_series_equal(result, expected)
result = left == np.nan expected = Series([False, False, False]) tm.assert_series_equal(result, expected)
result = left != np.nan expected = Series([True, True, True]) tm.assert_series_equal(result, expected)
# ------------------------------------------------------------------# Arithmetic
class TestArithmetic: def test_add_period_to_array_of_offset(self): # GH#50162 per = pd.Period("2012-1-1", freq="D") pi = pd.period_range("2012-1-1", periods=10, freq="D") idx = per - pi
expected = pd.Index([x + per for x in idx], dtype=object) result = idx + per tm.assert_index_equal(result, expected)
result = per + idx tm.assert_index_equal(result, expected)
# TODO: parametrize def test_pow_ops_object(self): # GH#22922 # pow is weird with masking & 1, so testing here a = Series([1, np.nan, 1, np.nan], dtype=object) b = Series([1, np.nan, np.nan, 1], dtype=object) result = a**b expected = Series(a.values**b.values, dtype=object) tm.assert_series_equal(result, expected)
result = b**a expected = Series(b.values**a.values, dtype=object)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("op", [operator.add, ops.radd]) @pytest.mark.parametrize("other", ["category", "Int64"]) def test_add_extension_scalar(self, other, box_with_array, op): # GH#22378 # Check that scalars satisfying is_extension_array_dtype(obj) # do not incorrectly try to dispatch to an ExtensionArray operation
arr = Series(["a", "b", "c"]) expected = Series([op(x, other) for x in arr])
arr = tm.box_expected(arr, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = op(arr, other) tm.assert_equal(result, expected)
def test_objarr_add_str(self, box_with_array): ser = Series(["x", np.nan, "x"]) expected = Series(["xa", np.nan, "xa"])
ser = tm.box_expected(ser, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = ser + "a" tm.assert_equal(result, expected)
def test_objarr_radd_str(self, box_with_array): ser = Series(["x", np.nan, "x"]) expected = Series(["ax", np.nan, "ax"])
ser = tm.box_expected(ser, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = "a" + ser tm.assert_equal(result, expected)
@pytest.mark.parametrize( "data", [ [1, 2, 3], [1.1, 2.2, 3.3], [Timestamp("2011-01-01"), Timestamp("2011-01-02"), pd.NaT], ["x", "y", 1], ], ) @pytest.mark.parametrize("dtype", [None, object]) def test_objarr_radd_str_invalid(self, dtype, data, box_with_array): ser = Series(data, dtype=dtype)
ser = tm.box_expected(ser, box_with_array) msg = "|".join( [ "can only concatenate str", "did not contain a loop with signature matching types", "unsupported operand type", "must be str", ] ) with pytest.raises(TypeError, match=msg): "foo_" + ser
@pytest.mark.parametrize("op", [operator.add, ops.radd, operator.sub, ops.rsub]) def test_objarr_add_invalid(self, op, box_with_array): # invalid ops box = box_with_array
obj_ser = Series(list("abc"), dtype=object, name="objects")
obj_ser = tm.box_expected(obj_ser, box) msg = "|".join( [ "can only concatenate str", "unsupported operand type", "must be str", "has no kernel", ] ) with pytest.raises(Exception, match=msg): op(obj_ser, 1) with pytest.raises(Exception, match=msg): op(obj_ser, np.array(1, dtype=np.int64))
# TODO: Moved from tests.series.test_operators; needs cleanup def test_operators_na_handling(self): ser = Series(["foo", "bar", "baz", np.nan]) result = "prefix_" + ser expected = Series(["prefix_foo", "prefix_bar", "prefix_baz", np.nan]) tm.assert_series_equal(result, expected)
result = ser + "_suffix" expected = Series(["foo_suffix", "bar_suffix", "baz_suffix", np.nan]) tm.assert_series_equal(result, expected)
# TODO: parametrize over box @pytest.mark.parametrize("dtype", [None, object]) def test_series_with_dtype_radd_timedelta(self, dtype): # note this test is _not_ aimed at timedelta64-dtyped Series # as of 2.0 we retain object dtype when ser.dtype == object ser = Series( [pd.Timedelta("1 days"), pd.Timedelta("2 days"), pd.Timedelta("3 days")], dtype=dtype, ) expected = Series( [pd.Timedelta("4 days"), pd.Timedelta("5 days"), pd.Timedelta("6 days")], dtype=dtype, )
result = pd.Timedelta("3 days") + ser tm.assert_series_equal(result, expected)
result = ser + pd.Timedelta("3 days") tm.assert_series_equal(result, expected)
# TODO: cleanup & parametrize over box def test_mixed_timezone_series_ops_object(self): # GH#13043 ser = Series( [ Timestamp("2015-01-01", tz="US/Eastern"), Timestamp("2015-01-01", tz="Asia/Tokyo"), ], name="xxx", ) assert ser.dtype == object
exp = Series( [ Timestamp("2015-01-02", tz="US/Eastern"), Timestamp("2015-01-02", tz="Asia/Tokyo"), ], name="xxx", ) tm.assert_series_equal(ser + pd.Timedelta("1 days"), exp) tm.assert_series_equal(pd.Timedelta("1 days") + ser, exp)
# object series & object series ser2 = Series( [ Timestamp("2015-01-03", tz="US/Eastern"), Timestamp("2015-01-05", tz="Asia/Tokyo"), ], name="xxx", ) assert ser2.dtype == object exp = Series( [pd.Timedelta("2 days"), pd.Timedelta("4 days")], name="xxx", dtype=object ) tm.assert_series_equal(ser2 - ser, exp) tm.assert_series_equal(ser - ser2, -exp)
ser = Series( [pd.Timedelta("01:00:00"), pd.Timedelta("02:00:00")], name="xxx", dtype=object, ) assert ser.dtype == object
exp = Series( [pd.Timedelta("01:30:00"), pd.Timedelta("02:30:00")], name="xxx", dtype=object, ) tm.assert_series_equal(ser + pd.Timedelta("00:30:00"), exp) tm.assert_series_equal(pd.Timedelta("00:30:00") + ser, exp)
# TODO: cleanup & parametrize over box def test_iadd_preserves_name(self): # GH#17067, GH#19723 __iadd__ and __isub__ should preserve index name ser = Series([1, 2, 3]) ser.index.name = "foo"
ser.index += 1 assert ser.index.name == "foo"
ser.index -= 1 assert ser.index.name == "foo"
def test_add_string(self): # from bug report index = pd.Index(["a", "b", "c"]) index2 = index + "foo"
assert "a" not in index2 assert "afoo" in index2
def test_iadd_string(self): index = pd.Index(["a", "b", "c"]) # doesn't fail test unless there is a check before `+=` assert "a" in index
index += "_x" assert "a_x" in index
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="add doesn't work") def test_add(self): index = pd.Index([str(i) for i in range(10)]) expected = pd.Index(index.values * 2) tm.assert_index_equal(index + index, expected) tm.assert_index_equal(index + index.tolist(), expected) tm.assert_index_equal(index.tolist() + index, expected)
# test add and radd index = pd.Index(list("abc")) expected = pd.Index(["a1", "b1", "c1"]) tm.assert_index_equal(index + "1", expected) expected = pd.Index(["1a", "1b", "1c"]) tm.assert_index_equal("1" + index, expected)
def test_sub_fail(self, using_infer_string): index = pd.Index([str(i) for i in range(10)])
if using_infer_string: import pyarrow as pa
err = pa.lib.ArrowNotImplementedError msg = "has no kernel" else: err = TypeError msg = "unsupported operand type|Cannot broadcast" with pytest.raises(err, match=msg): index - "a" with pytest.raises(err, match=msg): index - index with pytest.raises(err, match=msg): index - index.tolist() with pytest.raises(err, match=msg): index.tolist() - index
def test_sub_object(self): # GH#19369 index = pd.Index([Decimal(1), Decimal(2)]) expected = pd.Index([Decimal(0), Decimal(1)])
result = index - Decimal(1) tm.assert_index_equal(result, expected)
result = index - pd.Index([Decimal(1), Decimal(1)]) tm.assert_index_equal(result, expected)
msg = "unsupported operand type" with pytest.raises(TypeError, match=msg): index - "foo"
with pytest.raises(TypeError, match=msg): index - np.array([2, "foo"], dtype=object)
def test_rsub_object(self, fixed_now_ts): # GH#19369 index = pd.Index([Decimal(1), Decimal(2)]) expected = pd.Index([Decimal(1), Decimal(0)])
result = Decimal(2) - index tm.assert_index_equal(result, expected)
result = np.array([Decimal(2), Decimal(2)]) - index tm.assert_index_equal(result, expected)
msg = "unsupported operand type" with pytest.raises(TypeError, match=msg): "foo" - index
with pytest.raises(TypeError, match=msg): np.array([True, fixed_now_ts]) - index
class MyIndex(pd.Index): # Simple index subclass that tracks ops calls.
_calls: int
@classmethod def _simple_new(cls, values, name=None, dtype=None): result = object.__new__(cls) result._data = values result._name = name result._calls = 0 result._reset_identity()
return result
def __add__(self, other): self._calls += 1 return self._simple_new(self._data)
def __radd__(self, other): return self.__add__(other)
@pytest.mark.parametrize( "other", [ [datetime.timedelta(1), datetime.timedelta(2)], [datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 2)], [pd.Period("2000"), pd.Period("2001")], ["a", "b"], ], ids=["timedelta", "datetime", "period", "object"],)def test_index_ops_defer_to_unknown_subclasses(other): # https://github.com/pandas-dev/pandas/issues/31109 values = np.array( [datetime.date(2000, 1, 1), datetime.date(2000, 1, 2)], dtype=object ) a = MyIndex._simple_new(values) other = pd.Index(other) result = other + a assert isinstance(result, MyIndex) assert a._calls == 11234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675# Arithmetic tests for DataFrame/Series/Index/Array classes that should# behave identically.# Specifically for Period dtypeimport operator
import numpy as npimport pytest
from pandas._libs.tslibs import ( IncompatibleFrequency, Period, Timestamp, to_offset,)from pandas.errors import PerformanceWarning
import pandas as pdfrom pandas import ( PeriodIndex, Series, Timedelta, TimedeltaIndex, period_range,)import pandas._testing as tmfrom pandas.core import opsfrom pandas.core.arrays import TimedeltaArrayfrom pandas.tests.arithmetic.common import ( assert_invalid_addsub_type, assert_invalid_comparison, get_upcast_box,)
_common_mismatch = [ pd.offsets.YearBegin(2), pd.offsets.MonthBegin(1), pd.offsets.Minute(),]
@pytest.fixture( params=[ Timedelta(minutes=30).to_pytimedelta(), np.timedelta64(30, "s"), Timedelta(seconds=30), ] + _common_mismatch)def not_hourly(request): """ Several timedelta-like and DateOffset instances that are _not_ compatible with Hourly frequencies. """ return request.param
@pytest.fixture( params=[ np.timedelta64(365, "D"), Timedelta(days=365).to_pytimedelta(), Timedelta(days=365), ] + _common_mismatch)def mismatched_freq(request): """ Several timedelta-like and DateOffset instances that are _not_ compatible with Monthly or Annual frequencies. """ return request.param
# ------------------------------------------------------------------# Comparisons
class TestPeriodArrayLikeComparisons: # Comparison tests for PeriodDtype vectors fully parametrized over # DataFrame/Series/PeriodIndex/PeriodArray. Ideally all comparison # tests will eventually end up here.
@pytest.mark.parametrize("other", ["2017", Period("2017", freq="D")]) def test_eq_scalar(self, other, box_with_array): idx = PeriodIndex(["2017", "2017", "2018"], freq="D") idx = tm.box_expected(idx, box_with_array) xbox = get_upcast_box(idx, other, True)
expected = np.array([True, True, False]) expected = tm.box_expected(expected, xbox)
result = idx == other
tm.assert_equal(result, expected)
def test_compare_zerodim(self, box_with_array): # GH#26689 make sure we unbox zero-dimensional arrays
pi = period_range("2000", periods=4) other = np.array(pi.to_numpy()[0])
pi = tm.box_expected(pi, box_with_array) xbox = get_upcast_box(pi, other, True)
result = pi <= other expected = np.array([True, False, False, False]) expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected)
@pytest.mark.parametrize( "scalar", [ "foo", Timestamp("2021-01-01"), Timedelta(days=4), 9, 9.5, 2000, # specifically don't consider 2000 to match Period("2000", "D") False, None, ], ) def test_compare_invalid_scalar(self, box_with_array, scalar): # GH#28980 # comparison with scalar that cannot be interpreted as a Period pi = period_range("2000", periods=4) parr = tm.box_expected(pi, box_with_array) assert_invalid_comparison(parr, scalar, box_with_array)
@pytest.mark.parametrize( "other", [ pd.date_range("2000", periods=4).array, pd.timedelta_range("1D", periods=4).array, np.arange(4), np.arange(4).astype(np.float64), list(range(4)), # match Period semantics by not treating integers as Periods [2000, 2001, 2002, 2003], np.arange(2000, 2004), np.arange(2000, 2004).astype(object), pd.Index([2000, 2001, 2002, 2003]), ], ) def test_compare_invalid_listlike(self, box_with_array, other): pi = period_range("2000", periods=4) parr = tm.box_expected(pi, box_with_array) assert_invalid_comparison(parr, other, box_with_array)
@pytest.mark.parametrize("other_box", [list, np.array, lambda x: x.astype(object)]) def test_compare_object_dtype(self, box_with_array, other_box): pi = period_range("2000", periods=5) parr = tm.box_expected(pi, box_with_array)
other = other_box(pi) xbox = get_upcast_box(parr, other, True)
expected = np.array([True, True, True, True, True]) expected = tm.box_expected(expected, xbox)
result = parr == other tm.assert_equal(result, expected) result = parr <= other tm.assert_equal(result, expected) result = parr >= other tm.assert_equal(result, expected)
result = parr != other tm.assert_equal(result, ~expected) result = parr < other tm.assert_equal(result, ~expected) result = parr > other tm.assert_equal(result, ~expected)
other = other_box(pi[::-1])
expected = np.array([False, False, True, False, False]) expected = tm.box_expected(expected, xbox) result = parr == other tm.assert_equal(result, expected)
expected = np.array([True, True, True, False, False]) expected = tm.box_expected(expected, xbox) result = parr <= other tm.assert_equal(result, expected)
expected = np.array([False, False, True, True, True]) expected = tm.box_expected(expected, xbox) result = parr >= other tm.assert_equal(result, expected)
expected = np.array([True, True, False, True, True]) expected = tm.box_expected(expected, xbox) result = parr != other tm.assert_equal(result, expected)
expected = np.array([True, True, False, False, False]) expected = tm.box_expected(expected, xbox) result = parr < other tm.assert_equal(result, expected)
expected = np.array([False, False, False, True, True]) expected = tm.box_expected(expected, xbox) result = parr > other tm.assert_equal(result, expected)
class TestPeriodIndexComparisons: # TODO: parameterize over boxes
def test_pi_cmp_period(self): idx = period_range("2007-01", periods=20, freq="M") per = idx[10]
result = idx < per exp = idx.values < idx.values[10] tm.assert_numpy_array_equal(result, exp)
# Tests Period.__richcmp__ against ndarray[object, ndim=2] result = idx.values.reshape(10, 2) < per tm.assert_numpy_array_equal(result, exp.reshape(10, 2))
# Tests Period.__richcmp__ against ndarray[object, ndim=0] result = idx < np.array(per) tm.assert_numpy_array_equal(result, exp)
# TODO: moved from test_datetime64; de-duplicate with version below def test_parr_cmp_period_scalar2(self, box_with_array): pi = period_range("2000-01-01", periods=10, freq="D")
val = pi[3] expected = [x > val for x in pi]
ser = tm.box_expected(pi, box_with_array) xbox = get_upcast_box(ser, val, True)
expected = tm.box_expected(expected, xbox) result = ser > val tm.assert_equal(result, expected)
val = pi[5] result = ser > val expected = [x > val for x in pi] expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected)
@pytest.mark.parametrize("freq", ["M", "2M", "3M"]) def test_parr_cmp_period_scalar(self, freq, box_with_array): # GH#13200 base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq) base = tm.box_expected(base, box_with_array) per = Period("2011-02", freq=freq) xbox = get_upcast_box(base, per, True)
exp = np.array([False, True, False, False]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base == per, exp) tm.assert_equal(per == base, exp)
exp = np.array([True, False, True, True]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base != per, exp) tm.assert_equal(per != base, exp)
exp = np.array([False, False, True, True]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base > per, exp) tm.assert_equal(per < base, exp)
exp = np.array([True, False, False, False]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base < per, exp) tm.assert_equal(per > base, exp)
exp = np.array([False, True, True, True]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base >= per, exp) tm.assert_equal(per <= base, exp)
exp = np.array([True, True, False, False]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base <= per, exp) tm.assert_equal(per >= base, exp)
@pytest.mark.parametrize("freq", ["M", "2M", "3M"]) def test_parr_cmp_pi(self, freq, box_with_array): # GH#13200 base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq) base = tm.box_expected(base, box_with_array)
# TODO: could also box idx? idx = PeriodIndex(["2011-02", "2011-01", "2011-03", "2011-05"], freq=freq)
xbox = get_upcast_box(base, idx, True)
exp = np.array([False, False, True, False]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base == idx, exp)
exp = np.array([True, True, False, True]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base != idx, exp)
exp = np.array([False, True, False, False]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base > idx, exp)
exp = np.array([True, False, False, True]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base < idx, exp)
exp = np.array([False, True, True, False]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base >= idx, exp)
exp = np.array([True, False, True, True]) exp = tm.box_expected(exp, xbox) tm.assert_equal(base <= idx, exp)
@pytest.mark.parametrize("freq", ["M", "2M", "3M"]) def test_parr_cmp_pi_mismatched_freq(self, freq, box_with_array): # GH#13200 # different base freq base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq) base = tm.box_expected(base, box_with_array)
msg = rf"Invalid comparison between dtype=period\[{freq}\] and Period" with pytest.raises(TypeError, match=msg): base <= Period("2011", freq="Y")
with pytest.raises(TypeError, match=msg): Period("2011", freq="Y") >= base
# TODO: Could parametrize over boxes for idx? idx = PeriodIndex(["2011", "2012", "2013", "2014"], freq="Y") rev_msg = r"Invalid comparison between dtype=period\[Y-DEC\] and PeriodArray" idx_msg = rev_msg if box_with_array in [tm.to_array, pd.array] else msg with pytest.raises(TypeError, match=idx_msg): base <= idx
# Different frequency msg = rf"Invalid comparison between dtype=period\[{freq}\] and Period" with pytest.raises(TypeError, match=msg): base <= Period("2011", freq="4M")
with pytest.raises(TypeError, match=msg): Period("2011", freq="4M") >= base
idx = PeriodIndex(["2011", "2012", "2013", "2014"], freq="4M") rev_msg = r"Invalid comparison between dtype=period\[4M\] and PeriodArray" idx_msg = rev_msg if box_with_array in [tm.to_array, pd.array] else msg with pytest.raises(TypeError, match=idx_msg): base <= idx
@pytest.mark.parametrize("freq", ["M", "2M", "3M"]) def test_pi_cmp_nat(self, freq): idx1 = PeriodIndex(["2011-01", "2011-02", "NaT", "2011-05"], freq=freq) per = idx1[1]
result = idx1 > per exp = np.array([False, False, False, True]) tm.assert_numpy_array_equal(result, exp) result = per < idx1 tm.assert_numpy_array_equal(result, exp)
result = idx1 == pd.NaT exp = np.array([False, False, False, False]) tm.assert_numpy_array_equal(result, exp) result = pd.NaT == idx1 tm.assert_numpy_array_equal(result, exp)
result = idx1 != pd.NaT exp = np.array([True, True, True, True]) tm.assert_numpy_array_equal(result, exp) result = pd.NaT != idx1 tm.assert_numpy_array_equal(result, exp)
idx2 = PeriodIndex(["2011-02", "2011-01", "2011-04", "NaT"], freq=freq) result = idx1 < idx2 exp = np.array([True, False, False, False]) tm.assert_numpy_array_equal(result, exp)
result = idx1 == idx2 exp = np.array([False, False, False, False]) tm.assert_numpy_array_equal(result, exp)
result = idx1 != idx2 exp = np.array([True, True, True, True]) tm.assert_numpy_array_equal(result, exp)
result = idx1 == idx1 exp = np.array([True, True, False, True]) tm.assert_numpy_array_equal(result, exp)
result = idx1 != idx1 exp = np.array([False, False, True, False]) tm.assert_numpy_array_equal(result, exp)
@pytest.mark.parametrize("freq", ["M", "2M", "3M"]) def test_pi_cmp_nat_mismatched_freq_raises(self, freq): idx1 = PeriodIndex(["2011-01", "2011-02", "NaT", "2011-05"], freq=freq)
diff = PeriodIndex(["2011-02", "2011-01", "2011-04", "NaT"], freq="4M") msg = rf"Invalid comparison between dtype=period\[{freq}\] and PeriodArray" with pytest.raises(TypeError, match=msg): idx1 > diff
result = idx1 == diff expected = np.array([False, False, False, False], dtype=bool) tm.assert_numpy_array_equal(result, expected)
# TODO: De-duplicate with test_pi_cmp_nat @pytest.mark.parametrize("dtype", [object, None]) def test_comp_nat(self, dtype): left = PeriodIndex([Period("2011-01-01"), pd.NaT, Period("2011-01-03")]) right = PeriodIndex([pd.NaT, pd.NaT, Period("2011-01-03")])
if dtype is not None: left = left.astype(dtype) right = right.astype(dtype)
result = left == right expected = np.array([False, False, True]) tm.assert_numpy_array_equal(result, expected)
result = left != right expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected)
expected = np.array([False, False, False]) tm.assert_numpy_array_equal(left == pd.NaT, expected) tm.assert_numpy_array_equal(pd.NaT == right, expected)
expected = np.array([True, True, True]) tm.assert_numpy_array_equal(left != pd.NaT, expected) tm.assert_numpy_array_equal(pd.NaT != left, expected)
expected = np.array([False, False, False]) tm.assert_numpy_array_equal(left < pd.NaT, expected) tm.assert_numpy_array_equal(pd.NaT > left, expected)
class TestPeriodSeriesComparisons: def test_cmp_series_period_series_mixed_freq(self): # GH#13200 base = Series( [ Period("2011", freq="Y"), Period("2011-02", freq="M"), Period("2013", freq="Y"), Period("2011-04", freq="M"), ] )
ser = Series( [ Period("2012", freq="Y"), Period("2011-01", freq="M"), Period("2013", freq="Y"), Period("2011-05", freq="M"), ] )
exp = Series([False, False, True, False]) tm.assert_series_equal(base == ser, exp)
exp = Series([True, True, False, True]) tm.assert_series_equal(base != ser, exp)
exp = Series([False, True, False, False]) tm.assert_series_equal(base > ser, exp)
exp = Series([True, False, False, True]) tm.assert_series_equal(base < ser, exp)
exp = Series([False, True, True, False]) tm.assert_series_equal(base >= ser, exp)
exp = Series([True, False, True, True]) tm.assert_series_equal(base <= ser, exp)
class TestPeriodIndexSeriesComparisonConsistency: """Test PeriodIndex and Period Series Ops consistency"""
# TODO: needs parametrization+de-duplication
def _check(self, values, func, expected): # Test PeriodIndex and Period Series Ops consistency
idx = PeriodIndex(values) result = func(idx)
# check that we don't pass an unwanted type to tm.assert_equal assert isinstance(expected, (pd.Index, np.ndarray)) tm.assert_equal(result, expected)
s = Series(values) result = func(s)
exp = Series(expected, name=values.name) tm.assert_series_equal(result, exp)
def test_pi_comp_period(self): idx = PeriodIndex( ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx" ) per = idx[2]
f = lambda x: x == per exp = np.array([False, False, True, False], dtype=np.bool_) self._check(idx, f, exp) f = lambda x: per == x self._check(idx, f, exp)
f = lambda x: x != per exp = np.array([True, True, False, True], dtype=np.bool_) self._check(idx, f, exp) f = lambda x: per != x self._check(idx, f, exp)
f = lambda x: per >= x exp = np.array([True, True, True, False], dtype=np.bool_) self._check(idx, f, exp)
f = lambda x: x > per exp = np.array([False, False, False, True], dtype=np.bool_) self._check(idx, f, exp)
f = lambda x: per >= x exp = np.array([True, True, True, False], dtype=np.bool_) self._check(idx, f, exp)
def test_pi_comp_period_nat(self): idx = PeriodIndex( ["2011-01", "NaT", "2011-03", "2011-04"], freq="M", name="idx" ) per = idx[2]
f = lambda x: x == per exp = np.array([False, False, True, False], dtype=np.bool_) self._check(idx, f, exp) f = lambda x: per == x self._check(idx, f, exp)
f = lambda x: x == pd.NaT exp = np.array([False, False, False, False], dtype=np.bool_) self._check(idx, f, exp) f = lambda x: pd.NaT == x self._check(idx, f, exp)
f = lambda x: x != per exp = np.array([True, True, False, True], dtype=np.bool_) self._check(idx, f, exp) f = lambda x: per != x self._check(idx, f, exp)
f = lambda x: x != pd.NaT exp = np.array([True, True, True, True], dtype=np.bool_) self._check(idx, f, exp) f = lambda x: pd.NaT != x self._check(idx, f, exp)
f = lambda x: per >= x exp = np.array([True, False, True, False], dtype=np.bool_) self._check(idx, f, exp)
f = lambda x: x < per exp = np.array([True, False, False, False], dtype=np.bool_) self._check(idx, f, exp)
f = lambda x: x > pd.NaT exp = np.array([False, False, False, False], dtype=np.bool_) self._check(idx, f, exp)
f = lambda x: pd.NaT >= x exp = np.array([False, False, False, False], dtype=np.bool_) self._check(idx, f, exp)
# ------------------------------------------------------------------# Arithmetic
class TestPeriodFrameArithmetic: def test_ops_frame_period(self): # GH#13043 df = pd.DataFrame( { "A": [Period("2015-01", freq="M"), Period("2015-02", freq="M")], "B": [Period("2014-01", freq="M"), Period("2014-02", freq="M")], } ) assert df["A"].dtype == "Period[M]" assert df["B"].dtype == "Period[M]"
p = Period("2015-03", freq="M") off = p.freq # dtype will be object because of original dtype exp = pd.DataFrame( { "A": np.array([2 * off, 1 * off], dtype=object), "B": np.array([14 * off, 13 * off], dtype=object), } ) tm.assert_frame_equal(p - df, exp) tm.assert_frame_equal(df - p, -1 * exp)
df2 = pd.DataFrame( { "A": [Period("2015-05", freq="M"), Period("2015-06", freq="M")], "B": [Period("2015-05", freq="M"), Period("2015-06", freq="M")], } ) assert df2["A"].dtype == "Period[M]" assert df2["B"].dtype == "Period[M]"
exp = pd.DataFrame( { "A": np.array([4 * off, 4 * off], dtype=object), "B": np.array([16 * off, 16 * off], dtype=object), } ) tm.assert_frame_equal(df2 - df, exp) tm.assert_frame_equal(df - df2, -1 * exp)
class TestPeriodIndexArithmetic: # --------------------------------------------------------------- # __add__/__sub__ with PeriodIndex # PeriodIndex + other is defined for integers and timedelta-like others # PeriodIndex - other is defined for integers, timedelta-like others, # and PeriodIndex (with matching freq)
def test_parr_add_iadd_parr_raises(self, box_with_array): rng = period_range("1/1/2000", freq="D", periods=5) other = period_range("1/6/2000", freq="D", periods=5) # TODO: parametrize over boxes for other?
rng = tm.box_expected(rng, box_with_array) # An earlier implementation of PeriodIndex addition performed # a set operation (union). This has since been changed to # raise a TypeError. See GH#14164 and GH#13077 for historical # reference. msg = r"unsupported operand type\(s\) for \+: .* and .*" with pytest.raises(TypeError, match=msg): rng + other
with pytest.raises(TypeError, match=msg): rng += other
def test_pi_sub_isub_pi(self): # GH#20049 # For historical reference see GH#14164, GH#13077. # PeriodIndex subtraction originally performed set difference, # then changed to raise TypeError before being implemented in GH#20049 rng = period_range("1/1/2000", freq="D", periods=5) other = period_range("1/6/2000", freq="D", periods=5)
off = rng.freq expected = pd.Index([-5 * off] * 5) result = rng - other tm.assert_index_equal(result, expected)
rng -= other tm.assert_index_equal(rng, expected)
def test_pi_sub_pi_with_nat(self): rng = period_range("1/1/2000", freq="D", periods=5) other = rng[1:].insert(0, pd.NaT) assert other[1:].equals(rng[1:])
result = rng - other off = rng.freq expected = pd.Index([pd.NaT, 0 * off, 0 * off, 0 * off, 0 * off]) tm.assert_index_equal(result, expected)
def test_parr_sub_pi_mismatched_freq(self, box_with_array, box_with_array2): rng = period_range("1/1/2000", freq="D", periods=5) other = period_range("1/6/2000", freq="h", periods=5)
rng = tm.box_expected(rng, box_with_array) other = tm.box_expected(other, box_with_array2) msg = r"Input has different freq=[hD] from PeriodArray\(freq=[Dh]\)" with pytest.raises(IncompatibleFrequency, match=msg): rng - other
@pytest.mark.parametrize("n", [1, 2, 3, 4]) def test_sub_n_gt_1_ticks(self, tick_classes, n): # GH 23878 p1_d = "19910905" p2_d = "19920406" p1 = PeriodIndex([p1_d], freq=tick_classes(n)) p2 = PeriodIndex([p2_d], freq=tick_classes(n))
expected = PeriodIndex([p2_d], freq=p2.freq.base) - PeriodIndex( [p1_d], freq=p1.freq.base )
tm.assert_index_equal((p2 - p1), expected)
@pytest.mark.parametrize("n", [1, 2, 3, 4]) @pytest.mark.parametrize( "offset, kwd_name", [ (pd.offsets.YearEnd, "month"), (pd.offsets.QuarterEnd, "startingMonth"), (pd.offsets.MonthEnd, None), (pd.offsets.Week, "weekday"), ], ) def test_sub_n_gt_1_offsets(self, offset, kwd_name, n): # GH 23878 kwds = {kwd_name: 3} if kwd_name is not None else {} p1_d = "19910905" p2_d = "19920406" freq = offset(n, normalize=False, **kwds) p1 = PeriodIndex([p1_d], freq=freq) p2 = PeriodIndex([p2_d], freq=freq)
result = p2 - p1 expected = PeriodIndex([p2_d], freq=freq.base) - PeriodIndex( [p1_d], freq=freq.base )
tm.assert_index_equal(result, expected)
# ------------------------------------------------------------- # Invalid Operations
@pytest.mark.parametrize( "other", [ # datetime scalars Timestamp("2016-01-01"), Timestamp("2016-01-01").to_pydatetime(), Timestamp("2016-01-01").to_datetime64(), # datetime-like arrays pd.date_range("2016-01-01", periods=3, freq="h"), pd.date_range("2016-01-01", periods=3, tz="Europe/Brussels"), pd.date_range("2016-01-01", periods=3, freq="s")._data, pd.date_range("2016-01-01", periods=3, tz="Asia/Tokyo")._data, # Miscellaneous invalid types 3.14, np.array([2.0, 3.0, 4.0]), ], ) def test_parr_add_sub_invalid(self, other, box_with_array): # GH#23215 rng = period_range("1/1/2000", freq="D", periods=3) rng = tm.box_expected(rng, box_with_array)
msg = "|".join( [ r"(:?cannot add PeriodArray and .*)", r"(:?cannot subtract .* from (:?a\s)?.*)", r"(:?unsupported operand type\(s\) for \+: .* and .*)", r"unsupported operand type\(s\) for [+-]: .* and .*", ] ) assert_invalid_addsub_type(rng, other, msg) with pytest.raises(TypeError, match=msg): rng + other with pytest.raises(TypeError, match=msg): other + rng with pytest.raises(TypeError, match=msg): rng - other with pytest.raises(TypeError, match=msg): other - rng
# ----------------------------------------------------------------- # __add__/__sub__ with ndarray[datetime64] and ndarray[timedelta64]
def test_pi_add_sub_td64_array_non_tick_raises(self): rng = period_range("1/1/2000", freq="Q", periods=3) tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) tdarr = tdi.values
msg = r"Cannot add or subtract timedelta64\[ns\] dtype from period\[Q-DEC\]" with pytest.raises(TypeError, match=msg): rng + tdarr with pytest.raises(TypeError, match=msg): tdarr + rng
with pytest.raises(TypeError, match=msg): rng - tdarr msg = r"cannot subtract PeriodArray from TimedeltaArray" with pytest.raises(TypeError, match=msg): tdarr - rng
def test_pi_add_sub_td64_array_tick(self): # PeriodIndex + Timedelta-like is allowed only with # tick-like frequencies rng = period_range("1/1/2000", freq="90D", periods=3) tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) tdarr = tdi.values
expected = period_range("12/31/1999", freq="90D", periods=3) result = rng + tdi tm.assert_index_equal(result, expected) result = rng + tdarr tm.assert_index_equal(result, expected) result = tdi + rng tm.assert_index_equal(result, expected) result = tdarr + rng tm.assert_index_equal(result, expected)
expected = period_range("1/2/2000", freq="90D", periods=3)
result = rng - tdi tm.assert_index_equal(result, expected) result = rng - tdarr tm.assert_index_equal(result, expected)
msg = r"cannot subtract .* from .*" with pytest.raises(TypeError, match=msg): tdarr - rng
with pytest.raises(TypeError, match=msg): tdi - rng
@pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "h"]) @pytest.mark.parametrize("tdi_freq", [None, "h"]) def test_parr_sub_td64array(self, box_with_array, tdi_freq, pi_freq): box = box_with_array xbox = box if box not in [pd.array, tm.to_array] else pd.Index
tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq) dti = Timestamp("2018-03-07 17:16:40") + tdi pi = dti.to_period(pi_freq)
# TODO: parametrize over box for pi? td64obj = tm.box_expected(tdi, box)
if pi_freq == "h": result = pi - td64obj expected = (pi.to_timestamp("s") - tdi).to_period(pi_freq) expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected)
# Subtract from scalar result = pi[0] - td64obj expected = (pi[0].to_timestamp("s") - tdi).to_period(pi_freq) expected = tm.box_expected(expected, box) tm.assert_equal(result, expected)
elif pi_freq == "D": # Tick, but non-compatible msg = ( "Cannot add/subtract timedelta-like from PeriodArray that is " "not an integer multiple of the PeriodArray's freq." ) with pytest.raises(IncompatibleFrequency, match=msg): pi - td64obj
with pytest.raises(IncompatibleFrequency, match=msg): pi[0] - td64obj
else: # With non-Tick freq, we could not add timedelta64 array regardless # of what its resolution is msg = "Cannot add or subtract timedelta64" with pytest.raises(TypeError, match=msg): pi - td64obj with pytest.raises(TypeError, match=msg): pi[0] - td64obj
# ----------------------------------------------------------------- # operations with array/Index of DateOffset objects
@pytest.mark.parametrize("box", [np.array, pd.Index]) def test_pi_add_offset_array(self, box): # GH#18849 pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")]) offs = box( [ pd.offsets.QuarterEnd(n=1, startingMonth=12), pd.offsets.QuarterEnd(n=-2, startingMonth=12), ] ) expected = PeriodIndex([Period("2015Q2"), Period("2015Q4")]).astype(object)
with tm.assert_produces_warning(PerformanceWarning): res = pi + offs tm.assert_index_equal(res, expected)
with tm.assert_produces_warning(PerformanceWarning): res2 = offs + pi tm.assert_index_equal(res2, expected)
unanchored = np.array([pd.offsets.Hour(n=1), pd.offsets.Minute(n=-2)]) # addition/subtraction ops with incompatible offsets should issue # a PerformanceWarning and _then_ raise a TypeError. msg = r"Input cannot be converted to Period\(freq=Q-DEC\)" with pytest.raises(IncompatibleFrequency, match=msg): with tm.assert_produces_warning(PerformanceWarning): pi + unanchored with pytest.raises(IncompatibleFrequency, match=msg): with tm.assert_produces_warning(PerformanceWarning): unanchored + pi
@pytest.mark.parametrize("box", [np.array, pd.Index]) def test_pi_sub_offset_array(self, box): # GH#18824 pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")]) other = box( [ pd.offsets.QuarterEnd(n=1, startingMonth=12), pd.offsets.QuarterEnd(n=-2, startingMonth=12), ] )
expected = PeriodIndex([pi[n] - other[n] for n in range(len(pi))]) expected = expected.astype(object)
with tm.assert_produces_warning(PerformanceWarning): res = pi - other tm.assert_index_equal(res, expected)
anchored = box([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])
# addition/subtraction ops with anchored offsets should issue # a PerformanceWarning and _then_ raise a TypeError. msg = r"Input has different freq=-1M from Period\(freq=Q-DEC\)" with pytest.raises(IncompatibleFrequency, match=msg): with tm.assert_produces_warning(PerformanceWarning): pi - anchored with pytest.raises(IncompatibleFrequency, match=msg): with tm.assert_produces_warning(PerformanceWarning): anchored - pi
def test_pi_add_iadd_int(self, one): # Variants of `one` for #19012 rng = period_range("2000-01-01 09:00", freq="h", periods=10) result = rng + one expected = period_range("2000-01-01 10:00", freq="h", periods=10) tm.assert_index_equal(result, expected) rng += one tm.assert_index_equal(rng, expected)
def test_pi_sub_isub_int(self, one): """ PeriodIndex.__sub__ and __isub__ with several representations of the integer 1, e.g. int, np.int64, np.uint8, ... """ rng = period_range("2000-01-01 09:00", freq="h", periods=10) result = rng - one expected = period_range("2000-01-01 08:00", freq="h", periods=10) tm.assert_index_equal(result, expected) rng -= one tm.assert_index_equal(rng, expected)
@pytest.mark.parametrize("five", [5, np.array(5, dtype=np.int64)]) def test_pi_sub_intlike(self, five): rng = period_range("2007-01", periods=50)
result = rng - five exp = rng + (-five) tm.assert_index_equal(result, exp)
def test_pi_add_sub_int_array_freqn_gt1(self): # GH#47209 test adding array of ints when freq.n > 1 matches # scalar behavior pi = period_range("2016-01-01", periods=10, freq="2D") arr = np.arange(10) result = pi + arr expected = pd.Index([x + y for x, y in zip(pi, arr)]) tm.assert_index_equal(result, expected)
result = pi - arr expected = pd.Index([x - y for x, y in zip(pi, arr)]) tm.assert_index_equal(result, expected)
def test_pi_sub_isub_offset(self): # offset # DateOffset rng = period_range("2014", "2024", freq="Y") result = rng - pd.offsets.YearEnd(5) expected = period_range("2009", "2019", freq="Y") tm.assert_index_equal(result, expected) rng -= pd.offsets.YearEnd(5) tm.assert_index_equal(rng, expected)
rng = period_range("2014-01", "2016-12", freq="M") result = rng - pd.offsets.MonthEnd(5) expected = period_range("2013-08", "2016-07", freq="M") tm.assert_index_equal(result, expected)
rng -= pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected)
@pytest.mark.parametrize("transpose", [True, False]) def test_pi_add_offset_n_gt1(self, box_with_array, transpose): # GH#23215 # add offset to PeriodIndex with freq.n > 1
per = Period("2016-01", freq="2M") pi = PeriodIndex([per])
expected = PeriodIndex(["2016-03"], freq="2M")
pi = tm.box_expected(pi, box_with_array, transpose=transpose) expected = tm.box_expected(expected, box_with_array, transpose=transpose)
result = pi + per.freq tm.assert_equal(result, expected)
result = per.freq + pi tm.assert_equal(result, expected)
def test_pi_add_offset_n_gt1_not_divisible(self, box_with_array): # GH#23215 # PeriodIndex with freq.n > 1 add offset with offset.n % freq.n != 0 pi = PeriodIndex(["2016-01"], freq="2M") expected = PeriodIndex(["2016-04"], freq="2M")
pi = tm.box_expected(pi, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = pi + to_offset("3ME") tm.assert_equal(result, expected)
result = to_offset("3ME") + pi tm.assert_equal(result, expected)
# --------------------------------------------------------------- # __add__/__sub__ with integer arrays
@pytest.mark.parametrize("int_holder", [np.array, pd.Index]) @pytest.mark.parametrize("op", [operator.add, ops.radd]) def test_pi_add_intarray(self, int_holder, op): # GH#19959 pi = PeriodIndex([Period("2015Q1"), Period("NaT")]) other = int_holder([4, -1])
result = op(pi, other) expected = PeriodIndex([Period("2016Q1"), Period("NaT")]) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("int_holder", [np.array, pd.Index]) def test_pi_sub_intarray(self, int_holder): # GH#19959 pi = PeriodIndex([Period("2015Q1"), Period("NaT")]) other = int_holder([4, -1])
result = pi - other expected = PeriodIndex([Period("2014Q1"), Period("NaT")]) tm.assert_index_equal(result, expected)
msg = r"bad operand type for unary -: 'PeriodArray'" with pytest.raises(TypeError, match=msg): other - pi
# --------------------------------------------------------------- # Timedelta-like (timedelta, timedelta64, Timedelta, Tick) # TODO: Some of these are misnomers because of non-Tick DateOffsets
def test_parr_add_timedeltalike_minute_gt1(self, three_days, box_with_array): # GH#23031 adding a time-delta-like offset to a PeriodArray that has # minute frequency with n != 1. A more general case is tested below # in test_pi_add_timedeltalike_tick_gt1, but here we write out the # expected result more explicitly. other = three_days rng = period_range("2014-05-01", periods=3, freq="2D") rng = tm.box_expected(rng, box_with_array)
expected = PeriodIndex(["2014-05-04", "2014-05-06", "2014-05-08"], freq="2D") expected = tm.box_expected(expected, box_with_array)
result = rng + other tm.assert_equal(result, expected)
result = other + rng tm.assert_equal(result, expected)
# subtraction expected = PeriodIndex(["2014-04-28", "2014-04-30", "2014-05-02"], freq="2D") expected = tm.box_expected(expected, box_with_array) result = rng - other tm.assert_equal(result, expected)
msg = "|".join( [ r"bad operand type for unary -: 'PeriodArray'", r"cannot subtract PeriodArray from timedelta64\[[hD]\]", ] ) with pytest.raises(TypeError, match=msg): other - rng
@pytest.mark.parametrize("freqstr", ["5ns", "5us", "5ms", "5s", "5min", "5h", "5d"]) def test_parr_add_timedeltalike_tick_gt1(self, three_days, freqstr, box_with_array): # GH#23031 adding a time-delta-like offset to a PeriodArray that has # tick-like frequency with n != 1 other = three_days rng = period_range("2014-05-01", periods=6, freq=freqstr) first = rng[0] rng = tm.box_expected(rng, box_with_array)
expected = period_range(first + other, periods=6, freq=freqstr) expected = tm.box_expected(expected, box_with_array)
result = rng + other tm.assert_equal(result, expected)
result = other + rng tm.assert_equal(result, expected)
# subtraction expected = period_range(first - other, periods=6, freq=freqstr) expected = tm.box_expected(expected, box_with_array) result = rng - other tm.assert_equal(result, expected) msg = "|".join( [ r"bad operand type for unary -: 'PeriodArray'", r"cannot subtract PeriodArray from timedelta64\[[hD]\]", ] ) with pytest.raises(TypeError, match=msg): other - rng
def test_pi_add_iadd_timedeltalike_daily(self, three_days): # Tick other = three_days rng = period_range("2014-05-01", "2014-05-15", freq="D") expected = period_range("2014-05-04", "2014-05-18", freq="D")
result = rng + other tm.assert_index_equal(result, expected)
rng += other tm.assert_index_equal(rng, expected)
def test_pi_sub_isub_timedeltalike_daily(self, three_days): # Tick-like 3 Days other = three_days rng = period_range("2014-05-01", "2014-05-15", freq="D") expected = period_range("2014-04-28", "2014-05-12", freq="D")
result = rng - other tm.assert_index_equal(result, expected)
rng -= other tm.assert_index_equal(rng, expected)
def test_parr_add_sub_timedeltalike_freq_mismatch_daily( self, not_daily, box_with_array ): other = not_daily rng = period_range("2014-05-01", "2014-05-15", freq="D") rng = tm.box_expected(rng, box_with_array)
msg = "|".join( [ # non-timedelta-like DateOffset "Input has different freq(=.+)? from Period.*?\\(freq=D\\)", # timedelta/td64/Timedelta but not a multiple of 24H "Cannot add/subtract timedelta-like from PeriodArray that is " "not an integer multiple of the PeriodArray's freq.", ] ) with pytest.raises(IncompatibleFrequency, match=msg): rng + other with pytest.raises(IncompatibleFrequency, match=msg): rng += other with pytest.raises(IncompatibleFrequency, match=msg): rng - other with pytest.raises(IncompatibleFrequency, match=msg): rng -= other
def test_pi_add_iadd_timedeltalike_hourly(self, two_hours): other = two_hours rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="h") expected = period_range("2014-01-01 12:00", "2014-01-05 12:00", freq="h")
result = rng + other tm.assert_index_equal(result, expected)
rng += other tm.assert_index_equal(rng, expected)
def test_parr_add_timedeltalike_mismatched_freq_hourly( self, not_hourly, box_with_array ): other = not_hourly rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="h") rng = tm.box_expected(rng, box_with_array) msg = "|".join( [ # non-timedelta-like DateOffset "Input has different freq(=.+)? from Period.*?\\(freq=h\\)", # timedelta/td64/Timedelta but not a multiple of 24H "Cannot add/subtract timedelta-like from PeriodArray that is " "not an integer multiple of the PeriodArray's freq.", ] )
with pytest.raises(IncompatibleFrequency, match=msg): rng + other
with pytest.raises(IncompatibleFrequency, match=msg): rng += other
def test_pi_sub_isub_timedeltalike_hourly(self, two_hours): other = two_hours rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="h") expected = period_range("2014-01-01 08:00", "2014-01-05 08:00", freq="h")
result = rng - other tm.assert_index_equal(result, expected)
rng -= other tm.assert_index_equal(rng, expected)
def test_add_iadd_timedeltalike_annual(self): # offset # DateOffset rng = period_range("2014", "2024", freq="Y") result = rng + pd.offsets.YearEnd(5) expected = period_range("2019", "2029", freq="Y") tm.assert_index_equal(result, expected) rng += pd.offsets.YearEnd(5) tm.assert_index_equal(rng, expected)
def test_pi_add_sub_timedeltalike_freq_mismatch_annual(self, mismatched_freq): other = mismatched_freq rng = period_range("2014", "2024", freq="Y") msg = "Input has different freq(=.+)? from Period.*?\\(freq=Y-DEC\\)" with pytest.raises(IncompatibleFrequency, match=msg): rng + other with pytest.raises(IncompatibleFrequency, match=msg): rng += other with pytest.raises(IncompatibleFrequency, match=msg): rng - other with pytest.raises(IncompatibleFrequency, match=msg): rng -= other
def test_pi_add_iadd_timedeltalike_M(self): rng = period_range("2014-01", "2016-12", freq="M") expected = period_range("2014-06", "2017-05", freq="M")
result = rng + pd.offsets.MonthEnd(5) tm.assert_index_equal(result, expected)
rng += pd.offsets.MonthEnd(5) tm.assert_index_equal(rng, expected)
def test_pi_add_sub_timedeltalike_freq_mismatch_monthly(self, mismatched_freq): other = mismatched_freq rng = period_range("2014-01", "2016-12", freq="M") msg = "Input has different freq(=.+)? from Period.*?\\(freq=M\\)" with pytest.raises(IncompatibleFrequency, match=msg): rng + other with pytest.raises(IncompatibleFrequency, match=msg): rng += other with pytest.raises(IncompatibleFrequency, match=msg): rng - other with pytest.raises(IncompatibleFrequency, match=msg): rng -= other
@pytest.mark.parametrize("transpose", [True, False]) def test_parr_add_sub_td64_nat(self, box_with_array, transpose): # GH#23320 special handling for timedelta64("NaT") pi = period_range("1994-04-01", periods=9, freq="19D") other = np.timedelta64("NaT") expected = PeriodIndex(["NaT"] * 9, freq="19D")
obj = tm.box_expected(pi, box_with_array, transpose=transpose) expected = tm.box_expected(expected, box_with_array, transpose=transpose)
result = obj + other tm.assert_equal(result, expected) result = other + obj tm.assert_equal(result, expected) result = obj - other tm.assert_equal(result, expected) msg = r"cannot subtract .* from .*" with pytest.raises(TypeError, match=msg): other - obj
@pytest.mark.parametrize( "other", [ np.array(["NaT"] * 9, dtype="m8[ns]"), TimedeltaArray._from_sequence(["NaT"] * 9, dtype="m8[ns]"), ], ) def test_parr_add_sub_tdt64_nat_array(self, box_with_array, other): pi = period_range("1994-04-01", periods=9, freq="19D") expected = PeriodIndex(["NaT"] * 9, freq="19D")
obj = tm.box_expected(pi, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = obj + other tm.assert_equal(result, expected) result = other + obj tm.assert_equal(result, expected) result = obj - other tm.assert_equal(result, expected) msg = r"cannot subtract .* from .*" with pytest.raises(TypeError, match=msg): other - obj
# some but not *all* NaT other = other.copy() other[0] = np.timedelta64(0, "ns") expected = PeriodIndex([pi[0]] + ["NaT"] * 8, freq="19D") expected = tm.box_expected(expected, box_with_array)
result = obj + other tm.assert_equal(result, expected) result = other + obj tm.assert_equal(result, expected) result = obj - other tm.assert_equal(result, expected) with pytest.raises(TypeError, match=msg): other - obj
# --------------------------------------------------------------- # Unsorted
def test_parr_add_sub_index(self): # Check that PeriodArray defers to Index on arithmetic ops pi = period_range("2000-12-31", periods=3) parr = pi.array
result = parr - pi expected = pi - pi tm.assert_index_equal(result, expected)
def test_parr_add_sub_object_array(self): pi = period_range("2000-12-31", periods=3, freq="D") parr = pi.array
other = np.array([Timedelta(days=1), pd.offsets.Day(2), 3])
with tm.assert_produces_warning(PerformanceWarning): result = parr + other
expected = PeriodIndex( ["2001-01-01", "2001-01-03", "2001-01-05"], freq="D" )._data.astype(object) tm.assert_equal(result, expected)
with tm.assert_produces_warning(PerformanceWarning): result = parr - other
expected = PeriodIndex(["2000-12-30"] * 3, freq="D")._data.astype(object) tm.assert_equal(result, expected)
def test_period_add_timestamp_raises(self, box_with_array): # GH#17983 ts = Timestamp("2017") per = Period("2017", freq="M")
arr = pd.Index([per], dtype="Period[M]") arr = tm.box_expected(arr, box_with_array)
msg = "cannot add PeriodArray and Timestamp" with pytest.raises(TypeError, match=msg): arr + ts with pytest.raises(TypeError, match=msg): ts + arr msg = "cannot add PeriodArray and DatetimeArray" with pytest.raises(TypeError, match=msg): arr + Series([ts]) with pytest.raises(TypeError, match=msg): Series([ts]) + arr with pytest.raises(TypeError, match=msg): arr + pd.Index([ts]) with pytest.raises(TypeError, match=msg): pd.Index([ts]) + arr
if box_with_array is pd.DataFrame: msg = "cannot add PeriodArray and DatetimeArray" else: msg = r"unsupported operand type\(s\) for \+: 'Period' and 'DatetimeArray" with pytest.raises(TypeError, match=msg): arr + pd.DataFrame([ts]) if box_with_array is pd.DataFrame: msg = "cannot add PeriodArray and DatetimeArray" else: msg = r"unsupported operand type\(s\) for \+: 'DatetimeArray' and 'Period'" with pytest.raises(TypeError, match=msg): pd.DataFrame([ts]) + arr
class TestPeriodSeriesArithmetic: def test_parr_add_timedeltalike_scalar(self, three_days, box_with_array): # GH#13043 ser = Series( [Period("2015-01-01", freq="D"), Period("2015-01-02", freq="D")], name="xxx", ) assert ser.dtype == "Period[D]"
expected = Series( [Period("2015-01-04", freq="D"), Period("2015-01-05", freq="D")], name="xxx", )
obj = tm.box_expected(ser, box_with_array) if box_with_array is pd.DataFrame: assert (obj.dtypes == "Period[D]").all()
expected = tm.box_expected(expected, box_with_array)
result = obj + three_days tm.assert_equal(result, expected)
result = three_days + obj tm.assert_equal(result, expected)
def test_ops_series_period(self): # GH#13043 ser = Series( [Period("2015-01-01", freq="D"), Period("2015-01-02", freq="D")], name="xxx", ) assert ser.dtype == "Period[D]"
per = Period("2015-01-10", freq="D") off = per.freq # dtype will be object because of original dtype expected = Series([9 * off, 8 * off], name="xxx", dtype=object) tm.assert_series_equal(per - ser, expected) tm.assert_series_equal(ser - per, -1 * expected)
s2 = Series( [Period("2015-01-05", freq="D"), Period("2015-01-04", freq="D")], name="xxx", ) assert s2.dtype == "Period[D]"
expected = Series([4 * off, 2 * off], name="xxx", dtype=object) tm.assert_series_equal(s2 - ser, expected) tm.assert_series_equal(ser - s2, -1 * expected)
class TestPeriodIndexSeriesMethods: """Test PeriodIndex and Period Series Ops consistency"""
def _check(self, values, func, expected): idx = PeriodIndex(values) result = func(idx) tm.assert_equal(result, expected)
ser = Series(values) result = func(ser)
exp = Series(expected, name=values.name) tm.assert_series_equal(result, exp)
def test_pi_ops(self): idx = PeriodIndex( ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx" )
expected = PeriodIndex( ["2011-03", "2011-04", "2011-05", "2011-06"], freq="M", name="idx" )
self._check(idx, lambda x: x + 2, expected) self._check(idx, lambda x: 2 + x, expected)
self._check(idx + 2, lambda x: x - 2, idx)
result = idx - Period("2011-01", freq="M") off = idx.freq exp = pd.Index([0 * off, 1 * off, 2 * off, 3 * off], name="idx") tm.assert_index_equal(result, exp)
result = Period("2011-01", freq="M") - idx exp = pd.Index([0 * off, -1 * off, -2 * off, -3 * off], name="idx") tm.assert_index_equal(result, exp)
@pytest.mark.parametrize("ng", ["str", 1.5]) @pytest.mark.parametrize( "func", [ lambda obj, ng: obj + ng, lambda obj, ng: ng + obj, lambda obj, ng: obj - ng, lambda obj, ng: ng - obj, lambda obj, ng: np.add(obj, ng), lambda obj, ng: np.add(ng, obj), lambda obj, ng: np.subtract(obj, ng), lambda obj, ng: np.subtract(ng, obj), ], ) def test_parr_ops_errors(self, ng, func, box_with_array): idx = PeriodIndex( ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx" ) obj = tm.box_expected(idx, box_with_array) msg = "|".join( [ r"unsupported operand type\(s\)", "can only concatenate", r"must be str", "object to str implicitly", ] )
with pytest.raises(TypeError, match=msg): func(obj, ng)
def test_pi_ops_nat(self): idx = PeriodIndex( ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx" ) expected = PeriodIndex( ["2011-03", "2011-04", "NaT", "2011-06"], freq="M", name="idx" )
self._check(idx, lambda x: x + 2, expected) self._check(idx, lambda x: 2 + x, expected) self._check(idx, lambda x: np.add(x, 2), expected)
self._check(idx + 2, lambda x: x - 2, idx) self._check(idx + 2, lambda x: np.subtract(x, 2), idx)
# freq with mult idx = PeriodIndex( ["2011-01", "2011-02", "NaT", "2011-04"], freq="2M", name="idx" ) expected = PeriodIndex( ["2011-07", "2011-08", "NaT", "2011-10"], freq="2M", name="idx" )
self._check(idx, lambda x: x + 3, expected) self._check(idx, lambda x: 3 + x, expected) self._check(idx, lambda x: np.add(x, 3), expected)
self._check(idx + 3, lambda x: x - 3, idx) self._check(idx + 3, lambda x: np.subtract(x, 3), idx)
def test_pi_ops_array_int(self): idx = PeriodIndex( ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx" ) f = lambda x: x + np.array([1, 2, 3, 4]) exp = PeriodIndex( ["2011-02", "2011-04", "NaT", "2011-08"], freq="M", name="idx" ) self._check(idx, f, exp)
f = lambda x: np.add(x, np.array([4, -1, 1, 2])) exp = PeriodIndex( ["2011-05", "2011-01", "NaT", "2011-06"], freq="M", name="idx" ) self._check(idx, f, exp)
f = lambda x: x - np.array([1, 2, 3, 4]) exp = PeriodIndex( ["2010-12", "2010-12", "NaT", "2010-12"], freq="M", name="idx" ) self._check(idx, f, exp)
f = lambda x: np.subtract(x, np.array([3, 2, 3, -2])) exp = PeriodIndex( ["2010-10", "2010-12", "NaT", "2011-06"], freq="M", name="idx" ) self._check(idx, f, exp)
def test_pi_ops_offset(self): idx = PeriodIndex( ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01"], freq="D", name="idx", ) f = lambda x: x + pd.offsets.Day() exp = PeriodIndex( ["2011-01-02", "2011-02-02", "2011-03-02", "2011-04-02"], freq="D", name="idx", ) self._check(idx, f, exp)
f = lambda x: x + pd.offsets.Day(2) exp = PeriodIndex( ["2011-01-03", "2011-02-03", "2011-03-03", "2011-04-03"], freq="D", name="idx", ) self._check(idx, f, exp)
f = lambda x: x - pd.offsets.Day(2) exp = PeriodIndex( ["2010-12-30", "2011-01-30", "2011-02-27", "2011-03-30"], freq="D", name="idx", ) self._check(idx, f, exp)
def test_pi_offset_errors(self): idx = PeriodIndex( ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01"], freq="D", name="idx", ) ser = Series(idx)
msg = ( "Cannot add/subtract timedelta-like from PeriodArray that is not " "an integer multiple of the PeriodArray's freq" ) for obj in [idx, ser]: with pytest.raises(IncompatibleFrequency, match=msg): obj + pd.offsets.Hour(2)
with pytest.raises(IncompatibleFrequency, match=msg): pd.offsets.Hour(2) + obj
with pytest.raises(IncompatibleFrequency, match=msg): obj - pd.offsets.Hour(2)
def test_pi_sub_period(self): # GH#13071 idx = PeriodIndex( ["2011-01", "2011-02", "2011-03", "2011-04"], freq="M", name="idx" )
result = idx - Period("2012-01", freq="M") off = idx.freq exp = pd.Index([-12 * off, -11 * off, -10 * off, -9 * off], name="idx") tm.assert_index_equal(result, exp)
result = np.subtract(idx, Period("2012-01", freq="M")) tm.assert_index_equal(result, exp)
result = Period("2012-01", freq="M") - idx exp = pd.Index([12 * off, 11 * off, 10 * off, 9 * off], name="idx") tm.assert_index_equal(result, exp)
result = np.subtract(Period("2012-01", freq="M"), idx) tm.assert_index_equal(result, exp)
exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx") result = idx - Period("NaT", freq="M") tm.assert_index_equal(result, exp) assert result.freq == exp.freq
result = Period("NaT", freq="M") - idx tm.assert_index_equal(result, exp) assert result.freq == exp.freq
def test_pi_sub_pdnat(self): # GH#13071, GH#19389 idx = PeriodIndex( ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx" ) exp = TimedeltaIndex([pd.NaT] * 4, name="idx") tm.assert_index_equal(pd.NaT - idx, exp) tm.assert_index_equal(idx - pd.NaT, exp)
def test_pi_sub_period_nat(self): # GH#13071 idx = PeriodIndex( ["2011-01", "NaT", "2011-03", "2011-04"], freq="M", name="idx" )
result = idx - Period("2012-01", freq="M") off = idx.freq exp = pd.Index([-12 * off, pd.NaT, -10 * off, -9 * off], name="idx") tm.assert_index_equal(result, exp)
result = Period("2012-01", freq="M") - idx exp = pd.Index([12 * off, pd.NaT, 10 * off, 9 * off], name="idx") tm.assert_index_equal(result, exp)
exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx") tm.assert_index_equal(idx - Period("NaT", freq="M"), exp) tm.assert_index_equal(Period("NaT", freq="M") - idx, exp)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179# Arithmetic tests for DataFrame/Series/Index/Array classes that should# behave identically.from datetime import ( datetime, timedelta,)
import numpy as npimport pytest
from pandas.errors import ( OutOfBoundsDatetime, PerformanceWarning,)
import pandas as pdfrom pandas import ( DataFrame, DatetimeIndex, Index, NaT, Series, Timedelta, TimedeltaIndex, Timestamp, offsets, timedelta_range,)import pandas._testing as tmfrom pandas.core.arrays import NumpyExtensionArrayfrom pandas.tests.arithmetic.common import ( assert_invalid_addsub_type, assert_invalid_comparison, get_upcast_box,)
def assert_dtype(obj, expected_dtype): """ Helper to check the dtype for a Series, Index, or single-column DataFrame. """ dtype = tm.get_dtype(obj)
assert dtype == expected_dtype
def get_expected_name(box, names): if box is DataFrame: # Since we are operating with a DataFrame and a non-DataFrame, # the non-DataFrame is cast to Series and its name ignored. exname = names[0] elif box in [tm.to_array, pd.array]: exname = names[1] else: exname = names[2] return exname
# ------------------------------------------------------------------# Timedelta64[ns] dtype Comparisons
class TestTimedelta64ArrayLikeComparisons: # Comparison tests for timedelta64[ns] vectors fully parametrized over # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all comparison # tests will eventually end up here.
def test_compare_timedelta64_zerodim(self, box_with_array): # GH#26689 should unbox when comparing with zerodim array box = box_with_array xbox = box_with_array if box_with_array not in [Index, pd.array] else np.ndarray
tdi = timedelta_range("2h", periods=4) other = np.array(tdi.to_numpy()[0])
tdi = tm.box_expected(tdi, box) res = tdi <= other expected = np.array([True, False, False, False]) expected = tm.box_expected(expected, xbox) tm.assert_equal(res, expected)
@pytest.mark.parametrize( "td_scalar", [ timedelta(days=1), Timedelta(days=1), Timedelta(days=1).to_timedelta64(), offsets.Hour(24), ], ) def test_compare_timedeltalike_scalar(self, box_with_array, td_scalar): # regression test for GH#5963 box = box_with_array xbox = box if box not in [Index, pd.array] else np.ndarray
ser = Series([timedelta(days=1), timedelta(days=2)]) ser = tm.box_expected(ser, box) actual = ser > td_scalar expected = Series([False, True]) expected = tm.box_expected(expected, xbox) tm.assert_equal(actual, expected)
@pytest.mark.parametrize( "invalid", [ 345600000000000, "a", Timestamp("2021-01-01"), Timestamp("2021-01-01").now("UTC"), Timestamp("2021-01-01").now().to_datetime64(), Timestamp("2021-01-01").now().to_pydatetime(), Timestamp("2021-01-01").date(), np.array(4), # zero-dim mismatched dtype ], ) def test_td64_comparisons_invalid(self, box_with_array, invalid): # GH#13624 for str box = box_with_array
rng = timedelta_range("1 days", periods=10) obj = tm.box_expected(rng, box)
assert_invalid_comparison(obj, invalid, box)
@pytest.mark.parametrize( "other", [ list(range(10)), np.arange(10), np.arange(10).astype(np.float32), np.arange(10).astype(object), pd.date_range("1970-01-01", periods=10, tz="UTC").array, np.array(pd.date_range("1970-01-01", periods=10)), list(pd.date_range("1970-01-01", periods=10)), pd.date_range("1970-01-01", periods=10).astype(object), pd.period_range("1971-01-01", freq="D", periods=10).array, pd.period_range("1971-01-01", freq="D", periods=10).astype(object), ], ) def test_td64arr_cmp_arraylike_invalid(self, other, box_with_array): # We don't parametrize this over box_with_array because listlike # other plays poorly with assert_invalid_comparison reversed checks
rng = timedelta_range("1 days", periods=10)._data rng = tm.box_expected(rng, box_with_array) assert_invalid_comparison(rng, other, box_with_array)
def test_td64arr_cmp_mixed_invalid(self): rng = timedelta_range("1 days", periods=5)._data other = np.array([0, 1, 2, rng[3], Timestamp("2021-01-01")])
result = rng == other expected = np.array([False, False, False, True, False]) tm.assert_numpy_array_equal(result, expected)
result = rng != other tm.assert_numpy_array_equal(result, ~expected)
msg = "Invalid comparison between|Cannot compare type|not supported between" with pytest.raises(TypeError, match=msg): rng < other with pytest.raises(TypeError, match=msg): rng > other with pytest.raises(TypeError, match=msg): rng <= other with pytest.raises(TypeError, match=msg): rng >= other
class TestTimedelta64ArrayComparisons: # TODO: All of these need to be parametrized over box
@pytest.mark.parametrize("dtype", [None, object]) def test_comp_nat(self, dtype): left = TimedeltaIndex([Timedelta("1 days"), NaT, Timedelta("3 days")]) right = TimedeltaIndex([NaT, NaT, Timedelta("3 days")])
lhs, rhs = left, right if dtype is object: lhs, rhs = left.astype(object), right.astype(object)
result = rhs == lhs expected = np.array([False, False, True]) tm.assert_numpy_array_equal(result, expected)
result = rhs != lhs expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected)
expected = np.array([False, False, False]) tm.assert_numpy_array_equal(lhs == NaT, expected) tm.assert_numpy_array_equal(NaT == rhs, expected)
expected = np.array([True, True, True]) tm.assert_numpy_array_equal(lhs != NaT, expected) tm.assert_numpy_array_equal(NaT != lhs, expected)
expected = np.array([False, False, False]) tm.assert_numpy_array_equal(lhs < NaT, expected) tm.assert_numpy_array_equal(NaT > lhs, expected)
@pytest.mark.parametrize( "idx2", [ TimedeltaIndex( ["2 day", "2 day", NaT, NaT, "1 day 00:00:02", "5 days 00:00:03"] ), np.array( [ np.timedelta64(2, "D"), np.timedelta64(2, "D"), np.timedelta64("nat"), np.timedelta64("nat"), np.timedelta64(1, "D") + np.timedelta64(2, "s"), np.timedelta64(5, "D") + np.timedelta64(3, "s"), ] ), ], ) def test_comparisons_nat(self, idx2): idx1 = TimedeltaIndex( [ "1 day", NaT, "1 day 00:00:01", NaT, "1 day 00:00:01", "5 day 00:00:03", ] ) # Check pd.NaT is handles as the same as np.nan result = idx1 < idx2 expected = np.array([True, False, False, False, True, False]) tm.assert_numpy_array_equal(result, expected)
result = idx2 > idx1 expected = np.array([True, False, False, False, True, False]) tm.assert_numpy_array_equal(result, expected)
result = idx1 <= idx2 expected = np.array([True, False, False, False, True, True]) tm.assert_numpy_array_equal(result, expected)
result = idx2 >= idx1 expected = np.array([True, False, False, False, True, True]) tm.assert_numpy_array_equal(result, expected)
result = idx1 == idx2 expected = np.array([False, False, False, False, False, True]) tm.assert_numpy_array_equal(result, expected)
result = idx1 != idx2 expected = np.array([True, True, True, True, True, False]) tm.assert_numpy_array_equal(result, expected)
# TODO: better name def test_comparisons_coverage(self): rng = timedelta_range("1 days", periods=10)
result = rng < rng[3] expected = np.array([True, True, True] + [False] * 7) tm.assert_numpy_array_equal(result, expected)
result = rng == list(rng) exp = rng == rng tm.assert_numpy_array_equal(result, exp)
# ------------------------------------------------------------------# Timedelta64[ns] dtype Arithmetic Operations
class TestTimedelta64ArithmeticUnsorted: # Tests moved from type-specific test files but not # yet sorted/parametrized/de-duplicated
def test_ufunc_coercions(self): # normal ops are also tested in tseries/test_timedeltas.py idx = TimedeltaIndex(["2h", "4h", "6h", "8h", "10h"], freq="2h", name="x")
for result in [idx * 2, np.multiply(idx, 2)]: assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(["4h", "8h", "12h", "16h", "20h"], freq="4h", name="x") tm.assert_index_equal(result, exp) assert result.freq == "4h"
for result in [idx / 2, np.divide(idx, 2)]: assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(["1h", "2h", "3h", "4h", "5h"], freq="h", name="x") tm.assert_index_equal(result, exp) assert result.freq == "h"
for result in [-idx, np.negative(idx)]: assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex( ["-2h", "-4h", "-6h", "-8h", "-10h"], freq="-2h", name="x" ) tm.assert_index_equal(result, exp) assert result.freq == "-2h"
idx = TimedeltaIndex(["-2h", "-1h", "0h", "1h", "2h"], freq="h", name="x") for result in [abs(idx), np.absolute(idx)]: assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(["2h", "1h", "0h", "1h", "2h"], freq=None, name="x") tm.assert_index_equal(result, exp) assert result.freq is None
def test_subtraction_ops(self): # with datetimes/timedelta and tdi/dti tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo") dti = pd.date_range("20130101", periods=3, name="bar") td = Timedelta("1 days") dt = Timestamp("20130101")
msg = "cannot subtract a datelike from a TimedeltaArray" with pytest.raises(TypeError, match=msg): tdi - dt with pytest.raises(TypeError, match=msg): tdi - dti
msg = r"unsupported operand type\(s\) for -" with pytest.raises(TypeError, match=msg): td - dt
msg = "(bad|unsupported) operand type for unary" with pytest.raises(TypeError, match=msg): td - dti
result = dt - dti expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"], name="bar") tm.assert_index_equal(result, expected)
result = dti - dt expected = TimedeltaIndex(["0 days", "1 days", "2 days"], name="bar") tm.assert_index_equal(result, expected)
result = tdi - td expected = TimedeltaIndex(["0 days", NaT, "1 days"], name="foo") tm.assert_index_equal(result, expected)
result = td - tdi expected = TimedeltaIndex(["0 days", NaT, "-1 days"], name="foo") tm.assert_index_equal(result, expected)
result = dti - td expected = DatetimeIndex( ["20121231", "20130101", "20130102"], dtype="M8[ns]", freq="D", name="bar" ) tm.assert_index_equal(result, expected)
result = dt - tdi expected = DatetimeIndex( ["20121231", NaT, "20121230"], dtype="M8[ns]", name="foo" ) tm.assert_index_equal(result, expected)
def test_subtraction_ops_with_tz(self, box_with_array): # check that dt/dti subtraction ops with tz are validated dti = pd.date_range("20130101", periods=3) dti = tm.box_expected(dti, box_with_array) ts = Timestamp("20130101") dt = ts.to_pydatetime() dti_tz = pd.date_range("20130101", periods=3).tz_localize("US/Eastern") dti_tz = tm.box_expected(dti_tz, box_with_array) ts_tz = Timestamp("20130101").tz_localize("US/Eastern") ts_tz2 = Timestamp("20130101").tz_localize("CET") dt_tz = ts_tz.to_pydatetime() td = Timedelta("1 days")
def _check(result, expected): assert result == expected assert isinstance(result, Timedelta)
# scalars result = ts - ts expected = Timedelta("0 days") _check(result, expected)
result = dt_tz - ts_tz expected = Timedelta("0 days") _check(result, expected)
result = ts_tz - dt_tz expected = Timedelta("0 days") _check(result, expected)
# tz mismatches msg = "Cannot subtract tz-naive and tz-aware datetime-like objects." with pytest.raises(TypeError, match=msg): dt_tz - ts msg = "can't subtract offset-naive and offset-aware datetimes" with pytest.raises(TypeError, match=msg): dt_tz - dt msg = "can't subtract offset-naive and offset-aware datetimes" with pytest.raises(TypeError, match=msg): dt - dt_tz msg = "Cannot subtract tz-naive and tz-aware datetime-like objects." with pytest.raises(TypeError, match=msg): ts - dt_tz with pytest.raises(TypeError, match=msg): ts_tz2 - ts with pytest.raises(TypeError, match=msg): ts_tz2 - dt
msg = "Cannot subtract tz-naive and tz-aware" # with dti with pytest.raises(TypeError, match=msg): dti - ts_tz with pytest.raises(TypeError, match=msg): dti_tz - ts
result = dti_tz - dt_tz expected = TimedeltaIndex(["0 days", "1 days", "2 days"]) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
result = dt_tz - dti_tz expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"]) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
result = dti_tz - ts_tz expected = TimedeltaIndex(["0 days", "1 days", "2 days"]) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
result = ts_tz - dti_tz expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"]) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
result = td - td expected = Timedelta("0 days") _check(result, expected)
result = dti_tz - td expected = DatetimeIndex( ["20121231", "20130101", "20130102"], tz="US/Eastern" ).as_unit("ns") expected = tm.box_expected(expected, box_with_array) tm.assert_equal(result, expected)
def test_dti_tdi_numeric_ops(self): # These are normally union/diff set-like ops tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo") dti = pd.date_range("20130101", periods=3, name="bar")
result = tdi - tdi expected = TimedeltaIndex(["0 days", NaT, "0 days"], name="foo") tm.assert_index_equal(result, expected)
result = tdi + tdi expected = TimedeltaIndex(["2 days", NaT, "4 days"], name="foo") tm.assert_index_equal(result, expected)
result = dti - tdi # name will be reset expected = DatetimeIndex(["20121231", NaT, "20130101"], dtype="M8[ns]") tm.assert_index_equal(result, expected)
def test_addition_ops(self): # with datetimes/timedelta and tdi/dti tdi = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo") dti = pd.date_range("20130101", periods=3, name="bar") td = Timedelta("1 days") dt = Timestamp("20130101")
result = tdi + dt expected = DatetimeIndex( ["20130102", NaT, "20130103"], dtype="M8[ns]", name="foo" ) tm.assert_index_equal(result, expected)
result = dt + tdi expected = DatetimeIndex( ["20130102", NaT, "20130103"], dtype="M8[ns]", name="foo" ) tm.assert_index_equal(result, expected)
result = td + tdi expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo") tm.assert_index_equal(result, expected)
result = tdi + td expected = TimedeltaIndex(["2 days", NaT, "3 days"], name="foo") tm.assert_index_equal(result, expected)
# unequal length msg = "cannot add indices of unequal length" with pytest.raises(ValueError, match=msg): tdi + dti[0:1] with pytest.raises(ValueError, match=msg): tdi[0:1] + dti
# random indexes msg = "Addition/subtraction of integers and integer-arrays" with pytest.raises(TypeError, match=msg): tdi + Index([1, 2, 3], dtype=np.int64)
# this is a union! # FIXME: don't leave commented-out # pytest.raises(TypeError, lambda : Index([1,2,3]) + tdi)
result = tdi + dti # name will be reset expected = DatetimeIndex(["20130102", NaT, "20130105"], dtype="M8[ns]") tm.assert_index_equal(result, expected)
result = dti + tdi # name will be reset expected = DatetimeIndex(["20130102", NaT, "20130105"], dtype="M8[ns]") tm.assert_index_equal(result, expected)
result = dt + td expected = Timestamp("20130102") assert result == expected
result = td + dt expected = Timestamp("20130102") assert result == expected
# TODO: Needs more informative name, probably split up into # more targeted tests @pytest.mark.parametrize("freq", ["D", "B"]) def test_timedelta(self, freq): index = pd.date_range("1/1/2000", periods=50, freq=freq)
shifted = index + timedelta(1) back = shifted + timedelta(-1) back = back._with_freq("infer") tm.assert_index_equal(index, back)
if freq == "D": expected = pd.tseries.offsets.Day(1) assert index.freq == expected assert shifted.freq == expected assert back.freq == expected else: # freq == 'B' assert index.freq == pd.tseries.offsets.BusinessDay(1) assert shifted.freq is None assert back.freq == pd.tseries.offsets.BusinessDay(1)
result = index - timedelta(1) expected = index + timedelta(-1) tm.assert_index_equal(result, expected)
def test_timedelta_tick_arithmetic(self): # GH#4134, buggy with timedeltas rng = pd.date_range("2013", "2014") s = Series(rng) result1 = rng - offsets.Hour(1) result2 = DatetimeIndex(s - np.timedelta64(100000000)) result3 = rng - np.timedelta64(100000000) result4 = DatetimeIndex(s - offsets.Hour(1))
assert result1.freq == rng.freq result1 = result1._with_freq(None) tm.assert_index_equal(result1, result4)
assert result3.freq == rng.freq result3 = result3._with_freq(None) tm.assert_index_equal(result2, result3)
def test_tda_add_sub_index(self): # Check that TimedeltaArray defers to Index on arithmetic ops tdi = TimedeltaIndex(["1 days", NaT, "2 days"]) tda = tdi.array
dti = pd.date_range("1999-12-31", periods=3, freq="D")
result = tda + dti expected = tdi + dti tm.assert_index_equal(result, expected)
result = tda + tdi expected = tdi + tdi tm.assert_index_equal(result, expected)
result = tda - tdi expected = tdi - tdi tm.assert_index_equal(result, expected)
def test_tda_add_dt64_object_array(self, box_with_array, tz_naive_fixture): # Result should be cast back to DatetimeArray box = box_with_array
dti = pd.date_range("2016-01-01", periods=3, tz=tz_naive_fixture) dti = dti._with_freq(None) tdi = dti - dti
obj = tm.box_expected(tdi, box) other = tm.box_expected(dti, box)
with tm.assert_produces_warning(PerformanceWarning): result = obj + other.astype(object) tm.assert_equal(result, other.astype(object))
# ------------------------------------------------------------- # Binary operations TimedeltaIndex and timedelta-like
def test_tdi_iadd_timedeltalike(self, two_hours, box_with_array): # only test adding/sub offsets as + is now numeric rng = timedelta_range("1 days", "10 days") expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D")
rng = tm.box_expected(rng, box_with_array) expected = tm.box_expected(expected, box_with_array)
orig_rng = rng rng += two_hours tm.assert_equal(rng, expected) if box_with_array is not Index: # Check that operation is actually inplace tm.assert_equal(orig_rng, expected)
def test_tdi_isub_timedeltalike(self, two_hours, box_with_array): # only test adding/sub offsets as - is now numeric rng = timedelta_range("1 days", "10 days") expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00")
rng = tm.box_expected(rng, box_with_array) expected = tm.box_expected(expected, box_with_array)
orig_rng = rng rng -= two_hours tm.assert_equal(rng, expected) if box_with_array is not Index: # Check that operation is actually inplace tm.assert_equal(orig_rng, expected)
# -------------------------------------------------------------
def test_tdi_ops_attributes(self): rng = timedelta_range("2 days", periods=5, freq="2D", name="x")
result = rng + 1 * rng.freq exp = timedelta_range("4 days", periods=5, freq="2D", name="x") tm.assert_index_equal(result, exp) assert result.freq == "2D"
result = rng - 2 * rng.freq exp = timedelta_range("-2 days", periods=5, freq="2D", name="x") tm.assert_index_equal(result, exp) assert result.freq == "2D"
result = rng * 2 exp = timedelta_range("4 days", periods=5, freq="4D", name="x") tm.assert_index_equal(result, exp) assert result.freq == "4D"
result = rng / 2 exp = timedelta_range("1 days", periods=5, freq="D", name="x") tm.assert_index_equal(result, exp) assert result.freq == "D"
result = -rng exp = timedelta_range("-2 days", periods=5, freq="-2D", name="x") tm.assert_index_equal(result, exp) assert result.freq == "-2D"
rng = timedelta_range("-2 days", periods=5, freq="D", name="x")
result = abs(rng) exp = TimedeltaIndex( ["2 days", "1 days", "0 days", "1 days", "2 days"], name="x" ) tm.assert_index_equal(result, exp) assert result.freq is None
class TestAddSubNaTMasking: # TODO: parametrize over boxes
@pytest.mark.parametrize("str_ts", ["1950-01-01", "1980-01-01"]) def test_tdarr_add_timestamp_nat_masking(self, box_with_array, str_ts): # GH#17991 checking for overflow-masking with NaT tdinat = pd.to_timedelta(["24658 days 11:15:00", "NaT"]) tdobj = tm.box_expected(tdinat, box_with_array)
ts = Timestamp(str_ts) ts_variants = [ ts, ts.to_pydatetime(), ts.to_datetime64().astype("datetime64[ns]"), ts.to_datetime64().astype("datetime64[D]"), ]
for variant in ts_variants: res = tdobj + variant if box_with_array is DataFrame: assert res.iloc[1, 1] is NaT else: assert res[1] is NaT
def test_tdi_add_overflow(self): # See GH#14068 # preliminary test scalar analogue of vectorized tests below # TODO: Make raised error message more informative and test with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"): pd.to_timedelta(106580, "D") + Timestamp("2000") with pytest.raises(OutOfBoundsDatetime, match="10155196800000000000"): Timestamp("2000") + pd.to_timedelta(106580, "D")
_NaT = NaT._value + 1 msg = "Overflow in int64 addition" with pytest.raises(OverflowError, match=msg): pd.to_timedelta([106580], "D") + Timestamp("2000") with pytest.raises(OverflowError, match=msg): Timestamp("2000") + pd.to_timedelta([106580], "D") with pytest.raises(OverflowError, match=msg): pd.to_timedelta([_NaT]) - Timedelta("1 days") with pytest.raises(OverflowError, match=msg): pd.to_timedelta(["5 days", _NaT]) - Timedelta("1 days") with pytest.raises(OverflowError, match=msg): ( pd.to_timedelta([_NaT, "5 days", "1 hours"]) - pd.to_timedelta(["7 seconds", _NaT, "4 hours"]) )
# These should not overflow! exp = TimedeltaIndex([NaT]) result = pd.to_timedelta([NaT]) - Timedelta("1 days") tm.assert_index_equal(result, exp)
exp = TimedeltaIndex(["4 days", NaT]) result = pd.to_timedelta(["5 days", NaT]) - Timedelta("1 days") tm.assert_index_equal(result, exp)
exp = TimedeltaIndex([NaT, NaT, "5 hours"]) result = pd.to_timedelta([NaT, "5 days", "1 hours"]) + pd.to_timedelta( ["7 seconds", NaT, "4 hours"] ) tm.assert_index_equal(result, exp)
class TestTimedeltaArraylikeAddSubOps: # Tests for timedelta64[ns] __add__, __sub__, __radd__, __rsub__
def test_sub_nat_retain_unit(self): ser = pd.to_timedelta(Series(["00:00:01"])).astype("m8[s]")
result = ser - NaT expected = Series([NaT], dtype="m8[s]") tm.assert_series_equal(result, expected)
# TODO: moved from tests.indexes.timedeltas.test_arithmetic; needs # parametrization+de-duplication def test_timedelta_ops_with_missing_values(self): # setup s1 = pd.to_timedelta(Series(["00:00:01"])) s2 = pd.to_timedelta(Series(["00:00:02"]))
sn = pd.to_timedelta(Series([NaT], dtype="m8[ns]"))
df1 = DataFrame(["00:00:01"]).apply(pd.to_timedelta) df2 = DataFrame(["00:00:02"]).apply(pd.to_timedelta)
dfn = DataFrame([NaT._value]).apply(pd.to_timedelta)
scalar1 = pd.to_timedelta("00:00:01") scalar2 = pd.to_timedelta("00:00:02") timedelta_NaT = pd.to_timedelta("NaT")
actual = scalar1 + scalar1 assert actual == scalar2 actual = scalar2 - scalar1 assert actual == scalar1
actual = s1 + s1 tm.assert_series_equal(actual, s2) actual = s2 - s1 tm.assert_series_equal(actual, s1)
actual = s1 + scalar1 tm.assert_series_equal(actual, s2) actual = scalar1 + s1 tm.assert_series_equal(actual, s2) actual = s2 - scalar1 tm.assert_series_equal(actual, s1) actual = -scalar1 + s2 tm.assert_series_equal(actual, s1)
actual = s1 + timedelta_NaT tm.assert_series_equal(actual, sn) actual = timedelta_NaT + s1 tm.assert_series_equal(actual, sn) actual = s1 - timedelta_NaT tm.assert_series_equal(actual, sn) actual = -timedelta_NaT + s1 tm.assert_series_equal(actual, sn)
msg = "unsupported operand type" with pytest.raises(TypeError, match=msg): s1 + np.nan with pytest.raises(TypeError, match=msg): np.nan + s1 with pytest.raises(TypeError, match=msg): s1 - np.nan with pytest.raises(TypeError, match=msg): -np.nan + s1
actual = s1 + NaT tm.assert_series_equal(actual, sn) actual = s2 - NaT tm.assert_series_equal(actual, sn)
actual = s1 + df1 tm.assert_frame_equal(actual, df2) actual = s2 - df1 tm.assert_frame_equal(actual, df1) actual = df1 + s1 tm.assert_frame_equal(actual, df2) actual = df2 - s1 tm.assert_frame_equal(actual, df1)
actual = df1 + df1 tm.assert_frame_equal(actual, df2) actual = df2 - df1 tm.assert_frame_equal(actual, df1)
actual = df1 + scalar1 tm.assert_frame_equal(actual, df2) actual = df2 - scalar1 tm.assert_frame_equal(actual, df1)
actual = df1 + timedelta_NaT tm.assert_frame_equal(actual, dfn) actual = df1 - timedelta_NaT tm.assert_frame_equal(actual, dfn)
msg = "cannot subtract a datelike from|unsupported operand type" with pytest.raises(TypeError, match=msg): df1 + np.nan with pytest.raises(TypeError, match=msg): df1 - np.nan
actual = df1 + NaT # NaT is datetime, not timedelta tm.assert_frame_equal(actual, dfn) actual = df1 - NaT tm.assert_frame_equal(actual, dfn)
# TODO: moved from tests.series.test_operators, needs splitting, cleanup, # de-duplication, box-parametrization... def test_operators_timedelta64(self): # series ops v1 = pd.date_range("2012-1-1", periods=3, freq="D") v2 = pd.date_range("2012-1-2", periods=3, freq="D") rs = Series(v2) - Series(v1) xp = Series(1e9 * 3600 * 24, rs.index).astype("int64").astype("timedelta64[ns]") tm.assert_series_equal(rs, xp) assert rs.dtype == "timedelta64[ns]"
df = DataFrame({"A": v1}) td = Series([timedelta(days=i) for i in range(3)]) assert td.dtype == "timedelta64[ns]"
# series on the rhs result = df["A"] - df["A"].shift() assert result.dtype == "timedelta64[ns]"
result = df["A"] + td assert result.dtype == "M8[ns]"
# scalar Timestamp on rhs maxa = df["A"].max() assert isinstance(maxa, Timestamp)
resultb = df["A"] - df["A"].max() assert resultb.dtype == "timedelta64[ns]"
# timestamp on lhs result = resultb + df["A"] values = [Timestamp("20111230"), Timestamp("20120101"), Timestamp("20120103")] expected = Series(values, dtype="M8[ns]", name="A") tm.assert_series_equal(result, expected)
# datetimes on rhs result = df["A"] - datetime(2001, 1, 1) expected = Series([timedelta(days=4017 + i) for i in range(3)], name="A") tm.assert_series_equal(result, expected) assert result.dtype == "m8[ns]"
d = datetime(2001, 1, 1, 3, 4) resulta = df["A"] - d assert resulta.dtype == "m8[ns]"
# roundtrip resultb = resulta + d tm.assert_series_equal(df["A"], resultb)
# timedeltas on rhs td = timedelta(days=1) resulta = df["A"] + td resultb = resulta - td tm.assert_series_equal(resultb, df["A"]) assert resultb.dtype == "M8[ns]"
# roundtrip td = timedelta(minutes=5, seconds=3) resulta = df["A"] + td resultb = resulta - td tm.assert_series_equal(df["A"], resultb) assert resultb.dtype == "M8[ns]"
# inplace value = rs[2] + np.timedelta64(timedelta(minutes=5, seconds=1)) rs[2] += np.timedelta64(timedelta(minutes=5, seconds=1)) assert rs[2] == value
def test_timedelta64_ops_nat(self): # GH 11349 timedelta_series = Series([NaT, Timedelta("1s")]) nat_series_dtype_timedelta = Series([NaT, NaT], dtype="timedelta64[ns]") single_nat_dtype_timedelta = Series([NaT], dtype="timedelta64[ns]")
# subtraction tm.assert_series_equal(timedelta_series - NaT, nat_series_dtype_timedelta) tm.assert_series_equal(-NaT + timedelta_series, nat_series_dtype_timedelta)
tm.assert_series_equal( timedelta_series - single_nat_dtype_timedelta, nat_series_dtype_timedelta ) tm.assert_series_equal( -single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta )
# addition tm.assert_series_equal( nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta ) tm.assert_series_equal( NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta )
tm.assert_series_equal( nat_series_dtype_timedelta + single_nat_dtype_timedelta, nat_series_dtype_timedelta, ) tm.assert_series_equal( single_nat_dtype_timedelta + nat_series_dtype_timedelta, nat_series_dtype_timedelta, )
tm.assert_series_equal(timedelta_series + NaT, nat_series_dtype_timedelta) tm.assert_series_equal(NaT + timedelta_series, nat_series_dtype_timedelta)
tm.assert_series_equal( timedelta_series + single_nat_dtype_timedelta, nat_series_dtype_timedelta ) tm.assert_series_equal( single_nat_dtype_timedelta + timedelta_series, nat_series_dtype_timedelta )
tm.assert_series_equal( nat_series_dtype_timedelta + NaT, nat_series_dtype_timedelta ) tm.assert_series_equal( NaT + nat_series_dtype_timedelta, nat_series_dtype_timedelta )
tm.assert_series_equal( nat_series_dtype_timedelta + single_nat_dtype_timedelta, nat_series_dtype_timedelta, ) tm.assert_series_equal( single_nat_dtype_timedelta + nat_series_dtype_timedelta, nat_series_dtype_timedelta, )
# multiplication tm.assert_series_equal( nat_series_dtype_timedelta * 1.0, nat_series_dtype_timedelta ) tm.assert_series_equal( 1.0 * nat_series_dtype_timedelta, nat_series_dtype_timedelta )
tm.assert_series_equal(timedelta_series * 1, timedelta_series) tm.assert_series_equal(1 * timedelta_series, timedelta_series)
tm.assert_series_equal(timedelta_series * 1.5, Series([NaT, Timedelta("1.5s")])) tm.assert_series_equal(1.5 * timedelta_series, Series([NaT, Timedelta("1.5s")]))
tm.assert_series_equal(timedelta_series * np.nan, nat_series_dtype_timedelta) tm.assert_series_equal(np.nan * timedelta_series, nat_series_dtype_timedelta)
# division tm.assert_series_equal(timedelta_series / 2, Series([NaT, Timedelta("0.5s")])) tm.assert_series_equal(timedelta_series / 2.0, Series([NaT, Timedelta("0.5s")])) tm.assert_series_equal(timedelta_series / np.nan, nat_series_dtype_timedelta)
# ------------------------------------------------------------- # Binary operations td64 arraylike and datetime-like
@pytest.mark.parametrize("cls", [Timestamp, datetime, np.datetime64]) def test_td64arr_add_sub_datetimelike_scalar( self, cls, box_with_array, tz_naive_fixture ): # GH#11925, GH#29558, GH#23215 tz = tz_naive_fixture
dt_scalar = Timestamp("2012-01-01", tz=tz) if cls is datetime: ts = dt_scalar.to_pydatetime() elif cls is np.datetime64: if tz_naive_fixture is not None: pytest.skip(f"{cls} doesn support {tz_naive_fixture}") ts = dt_scalar.to_datetime64() else: ts = dt_scalar
tdi = timedelta_range("1 day", periods=3) expected = pd.date_range("2012-01-02", periods=3, tz=tz)
tdarr = tm.box_expected(tdi, box_with_array) expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(ts + tdarr, expected) tm.assert_equal(tdarr + ts, expected)
expected2 = pd.date_range("2011-12-31", periods=3, freq="-1D", tz=tz) expected2 = tm.box_expected(expected2, box_with_array)
tm.assert_equal(ts - tdarr, expected2) tm.assert_equal(ts + (-tdarr), expected2)
msg = "cannot subtract a datelike" with pytest.raises(TypeError, match=msg): tdarr - ts
def test_td64arr_add_datetime64_nat(self, box_with_array): # GH#23215 other = np.datetime64("NaT")
tdi = timedelta_range("1 day", periods=3) expected = DatetimeIndex(["NaT", "NaT", "NaT"], dtype="M8[ns]")
tdser = tm.box_expected(tdi, box_with_array) expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(tdser + other, expected) tm.assert_equal(other + tdser, expected)
def test_td64arr_sub_dt64_array(self, box_with_array): dti = pd.date_range("2016-01-01", periods=3) tdi = TimedeltaIndex(["-1 Day"] * 3) dtarr = dti.values expected = DatetimeIndex(dtarr) - tdi
tdi = tm.box_expected(tdi, box_with_array) expected = tm.box_expected(expected, box_with_array)
msg = "cannot subtract a datelike from" with pytest.raises(TypeError, match=msg): tdi - dtarr
# TimedeltaIndex.__rsub__ result = dtarr - tdi tm.assert_equal(result, expected)
def test_td64arr_add_dt64_array(self, box_with_array): dti = pd.date_range("2016-01-01", periods=3) tdi = TimedeltaIndex(["-1 Day"] * 3) dtarr = dti.values expected = DatetimeIndex(dtarr) + tdi
tdi = tm.box_expected(tdi, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = tdi + dtarr tm.assert_equal(result, expected) result = dtarr + tdi tm.assert_equal(result, expected)
# ------------------------------------------------------------------ # Invalid __add__/__sub__ operations
@pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "h"]) @pytest.mark.parametrize("tdi_freq", [None, "h"]) def test_td64arr_sub_periodlike( self, box_with_array, box_with_array2, tdi_freq, pi_freq ): # GH#20049 subtracting PeriodIndex should raise TypeError tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq) dti = Timestamp("2018-03-07 17:16:40") + tdi pi = dti.to_period(pi_freq) per = pi[0]
tdi = tm.box_expected(tdi, box_with_array) pi = tm.box_expected(pi, box_with_array2) msg = "cannot subtract|unsupported operand type" with pytest.raises(TypeError, match=msg): tdi - pi
# GH#13078 subtraction of Period scalar not supported with pytest.raises(TypeError, match=msg): tdi - per
@pytest.mark.parametrize( "other", [ # GH#12624 for str case "a", # GH#19123 1, 1.5, np.array(2), ], ) def test_td64arr_addsub_numeric_scalar_invalid(self, box_with_array, other): # vector-like others are tested in test_td64arr_add_sub_numeric_arr_invalid tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") tdarr = tm.box_expected(tdser, box_with_array)
assert_invalid_addsub_type(tdarr, other)
@pytest.mark.parametrize( "vec", [ np.array([1, 2, 3]), Index([1, 2, 3]), Series([1, 2, 3]), DataFrame([[1, 2, 3]]), ], ids=lambda x: type(x).__name__, ) def test_td64arr_addsub_numeric_arr_invalid( self, box_with_array, vec, any_real_numpy_dtype ): tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") tdarr = tm.box_expected(tdser, box_with_array)
vector = vec.astype(any_real_numpy_dtype) assert_invalid_addsub_type(tdarr, vector)
def test_td64arr_add_sub_int(self, box_with_array, one): # Variants of `one` for #19012, deprecated GH#22535 rng = timedelta_range("1 days 09:00:00", freq="h", periods=10) tdarr = tm.box_expected(rng, box_with_array)
msg = "Addition/subtraction of integers" assert_invalid_addsub_type(tdarr, one, msg)
# TODO: get inplace ops into assert_invalid_addsub_type with pytest.raises(TypeError, match=msg): tdarr += one with pytest.raises(TypeError, match=msg): tdarr -= one
def test_td64arr_add_sub_integer_array(self, box_with_array): # GH#19959, deprecated GH#22535 # GH#22696 for DataFrame case, check that we don't dispatch to numpy # implementation, which treats int64 as m8[ns] box = box_with_array xbox = np.ndarray if box is pd.array else box
rng = timedelta_range("1 days 09:00:00", freq="h", periods=3) tdarr = tm.box_expected(rng, box) other = tm.box_expected([4, 3, 2], xbox)
msg = "Addition/subtraction of integers and integer-arrays" assert_invalid_addsub_type(tdarr, other, msg)
def test_td64arr_addsub_integer_array_no_freq(self, box_with_array): # GH#19959 box = box_with_array xbox = np.ndarray if box is pd.array else box
tdi = TimedeltaIndex(["1 Day", "NaT", "3 Hours"]) tdarr = tm.box_expected(tdi, box) other = tm.box_expected([14, -1, 16], xbox)
msg = "Addition/subtraction of integers" assert_invalid_addsub_type(tdarr, other, msg)
# ------------------------------------------------------------------ # Operations with timedelta-like others
def test_td64arr_add_sub_td64_array(self, box_with_array): box = box_with_array dti = pd.date_range("2016-01-01", periods=3) tdi = dti - dti.shift(1) tdarr = tdi.values
expected = 2 * tdi tdi = tm.box_expected(tdi, box) expected = tm.box_expected(expected, box)
result = tdi + tdarr tm.assert_equal(result, expected) result = tdarr + tdi tm.assert_equal(result, expected)
expected_sub = 0 * tdi result = tdi - tdarr tm.assert_equal(result, expected_sub) result = tdarr - tdi tm.assert_equal(result, expected_sub)
def test_td64arr_add_sub_tdi(self, box_with_array, names): # GH#17250 make sure result dtype is correct # GH#19043 make sure names are propagated correctly box = box_with_array exname = get_expected_name(box, names)
tdi = TimedeltaIndex(["0 days", "1 day"], name=names[1]) tdi = np.array(tdi) if box in [tm.to_array, pd.array] else tdi ser = Series([Timedelta(hours=3), Timedelta(hours=4)], name=names[0]) expected = Series([Timedelta(hours=3), Timedelta(days=1, hours=4)], name=exname)
ser = tm.box_expected(ser, box) expected = tm.box_expected(expected, box)
result = tdi + ser tm.assert_equal(result, expected) assert_dtype(result, "timedelta64[ns]")
result = ser + tdi tm.assert_equal(result, expected) assert_dtype(result, "timedelta64[ns]")
expected = Series( [Timedelta(hours=-3), Timedelta(days=1, hours=-4)], name=exname ) expected = tm.box_expected(expected, box)
result = tdi - ser tm.assert_equal(result, expected) assert_dtype(result, "timedelta64[ns]")
result = ser - tdi tm.assert_equal(result, -expected) assert_dtype(result, "timedelta64[ns]")
@pytest.mark.parametrize("tdnat", [np.timedelta64("NaT"), NaT]) def test_td64arr_add_sub_td64_nat(self, box_with_array, tdnat): # GH#18808, GH#23320 special handling for timedelta64("NaT") box = box_with_array tdi = TimedeltaIndex([NaT, Timedelta("1s")]) expected = TimedeltaIndex(["NaT"] * 2)
obj = tm.box_expected(tdi, box) expected = tm.box_expected(expected, box)
result = obj + tdnat tm.assert_equal(result, expected) result = tdnat + obj tm.assert_equal(result, expected) result = obj - tdnat tm.assert_equal(result, expected) result = tdnat - obj tm.assert_equal(result, expected)
def test_td64arr_add_timedeltalike(self, two_hours, box_with_array): # only test adding/sub offsets as + is now numeric # GH#10699 for Tick cases box = box_with_array rng = timedelta_range("1 days", "10 days") expected = timedelta_range("1 days 02:00:00", "10 days 02:00:00", freq="D") rng = tm.box_expected(rng, box) expected = tm.box_expected(expected, box)
result = rng + two_hours tm.assert_equal(result, expected)
result = two_hours + rng tm.assert_equal(result, expected)
def test_td64arr_sub_timedeltalike(self, two_hours, box_with_array): # only test adding/sub offsets as - is now numeric # GH#10699 for Tick cases box = box_with_array rng = timedelta_range("1 days", "10 days") expected = timedelta_range("0 days 22:00:00", "9 days 22:00:00")
rng = tm.box_expected(rng, box) expected = tm.box_expected(expected, box)
result = rng - two_hours tm.assert_equal(result, expected)
result = two_hours - rng tm.assert_equal(result, -expected)
# ------------------------------------------------------------------ # __add__/__sub__ with DateOffsets and arrays of DateOffsets
def test_td64arr_add_sub_offset_index(self, names, box_with_array): # GH#18849, GH#19744 box = box_with_array exname = get_expected_name(box, names)
tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0]) other = Index([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1]) other = np.array(other) if box in [tm.to_array, pd.array] else other
expected = TimedeltaIndex( [tdi[n] + other[n] for n in range(len(tdi))], freq="infer", name=exname ) expected_sub = TimedeltaIndex( [tdi[n] - other[n] for n in range(len(tdi))], freq="infer", name=exname )
tdi = tm.box_expected(tdi, box) expected = tm.box_expected(expected, box).astype(object, copy=False) expected_sub = tm.box_expected(expected_sub, box).astype(object, copy=False)
with tm.assert_produces_warning(PerformanceWarning): res = tdi + other tm.assert_equal(res, expected)
with tm.assert_produces_warning(PerformanceWarning): res2 = other + tdi tm.assert_equal(res2, expected)
with tm.assert_produces_warning(PerformanceWarning): res_sub = tdi - other tm.assert_equal(res_sub, expected_sub)
def test_td64arr_add_sub_offset_array(self, box_with_array): # GH#18849, GH#18824 box = box_with_array tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"]) other = np.array([offsets.Hour(n=1), offsets.Minute(n=-2)])
expected = TimedeltaIndex( [tdi[n] + other[n] for n in range(len(tdi))], freq="infer" ) expected_sub = TimedeltaIndex( [tdi[n] - other[n] for n in range(len(tdi))], freq="infer" )
tdi = tm.box_expected(tdi, box) expected = tm.box_expected(expected, box).astype(object)
with tm.assert_produces_warning(PerformanceWarning): res = tdi + other tm.assert_equal(res, expected)
with tm.assert_produces_warning(PerformanceWarning): res2 = other + tdi tm.assert_equal(res2, expected)
expected_sub = tm.box_expected(expected_sub, box_with_array).astype(object) with tm.assert_produces_warning(PerformanceWarning): res_sub = tdi - other tm.assert_equal(res_sub, expected_sub)
def test_td64arr_with_offset_series(self, names, box_with_array): # GH#18849 box = box_with_array box2 = Series if box in [Index, tm.to_array, pd.array] else box exname = get_expected_name(box, names)
tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0]) other = Series([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1])
expected_add = Series( [tdi[n] + other[n] for n in range(len(tdi))], name=exname, dtype=object ) obj = tm.box_expected(tdi, box) expected_add = tm.box_expected(expected_add, box2).astype(object)
with tm.assert_produces_warning(PerformanceWarning): res = obj + other tm.assert_equal(res, expected_add)
with tm.assert_produces_warning(PerformanceWarning): res2 = other + obj tm.assert_equal(res2, expected_add)
expected_sub = Series( [tdi[n] - other[n] for n in range(len(tdi))], name=exname, dtype=object ) expected_sub = tm.box_expected(expected_sub, box2).astype(object)
with tm.assert_produces_warning(PerformanceWarning): res3 = obj - other tm.assert_equal(res3, expected_sub)
@pytest.mark.parametrize("obox", [np.array, Index, Series]) def test_td64arr_addsub_anchored_offset_arraylike(self, obox, box_with_array): # GH#18824 tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"]) tdi = tm.box_expected(tdi, box_with_array)
anchored = obox([offsets.MonthEnd(), offsets.Day(n=2)])
# addition/subtraction ops with anchored offsets should issue # a PerformanceWarning and _then_ raise a TypeError. msg = "has incorrect type|cannot add the type MonthEnd" with pytest.raises(TypeError, match=msg): with tm.assert_produces_warning(PerformanceWarning): tdi + anchored with pytest.raises(TypeError, match=msg): with tm.assert_produces_warning(PerformanceWarning): anchored + tdi with pytest.raises(TypeError, match=msg): with tm.assert_produces_warning(PerformanceWarning): tdi - anchored with pytest.raises(TypeError, match=msg): with tm.assert_produces_warning(PerformanceWarning): anchored - tdi
# ------------------------------------------------------------------ # Unsorted
def test_td64arr_add_sub_object_array(self, box_with_array): box = box_with_array xbox = np.ndarray if box is pd.array else box
tdi = timedelta_range("1 day", periods=3, freq="D") tdarr = tm.box_expected(tdi, box)
other = np.array([Timedelta(days=1), offsets.Day(2), Timestamp("2000-01-04")])
with tm.assert_produces_warning(PerformanceWarning): result = tdarr + other
expected = Index( [Timedelta(days=2), Timedelta(days=4), Timestamp("2000-01-07")] ) expected = tm.box_expected(expected, xbox).astype(object) tm.assert_equal(result, expected)
msg = "unsupported operand type|cannot subtract a datelike" with pytest.raises(TypeError, match=msg): with tm.assert_produces_warning(PerformanceWarning): tdarr - other
with tm.assert_produces_warning(PerformanceWarning): result = other - tdarr
expected = Index([Timedelta(0), Timedelta(0), Timestamp("2000-01-01")]) expected = tm.box_expected(expected, xbox).astype(object) tm.assert_equal(result, expected)
class TestTimedeltaArraylikeMulDivOps: # Tests for timedelta64[ns] # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__
# ------------------------------------------------------------------ # Multiplication # organized with scalar others first, then array-like
def test_td64arr_mul_int(self, box_with_array): idx = TimedeltaIndex(np.arange(5, dtype="int64")) idx = tm.box_expected(idx, box_with_array)
result = idx * 1 tm.assert_equal(result, idx)
result = 1 * idx tm.assert_equal(result, idx)
def test_td64arr_mul_tdlike_scalar_raises(self, two_hours, box_with_array): rng = timedelta_range("1 days", "10 days", name="foo") rng = tm.box_expected(rng, box_with_array) msg = "|".join( [ "argument must be an integer", "cannot use operands with types dtype", "Cannot multiply with", ] ) with pytest.raises(TypeError, match=msg): rng * two_hours
def test_tdi_mul_int_array_zerodim(self, box_with_array): rng5 = np.arange(5, dtype="int64") idx = TimedeltaIndex(rng5) expected = TimedeltaIndex(rng5 * 5)
idx = tm.box_expected(idx, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = idx * np.array(5, dtype="int64") tm.assert_equal(result, expected)
def test_tdi_mul_int_array(self, box_with_array): rng5 = np.arange(5, dtype="int64") idx = TimedeltaIndex(rng5) expected = TimedeltaIndex(rng5**2)
idx = tm.box_expected(idx, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = idx * rng5 tm.assert_equal(result, expected)
def test_tdi_mul_int_series(self, box_with_array): box = box_with_array xbox = Series if box in [Index, tm.to_array, pd.array] else box
idx = TimedeltaIndex(np.arange(5, dtype="int64")) expected = TimedeltaIndex(np.arange(5, dtype="int64") ** 2)
idx = tm.box_expected(idx, box) expected = tm.box_expected(expected, xbox)
result = idx * Series(np.arange(5, dtype="int64")) tm.assert_equal(result, expected)
def test_tdi_mul_float_series(self, box_with_array): box = box_with_array xbox = Series if box in [Index, tm.to_array, pd.array] else box
idx = TimedeltaIndex(np.arange(5, dtype="int64")) idx = tm.box_expected(idx, box)
rng5f = np.arange(5, dtype="float64") expected = TimedeltaIndex(rng5f * (rng5f + 1.0)) expected = tm.box_expected(expected, xbox)
result = idx * Series(rng5f + 1.0) tm.assert_equal(result, expected)
# TODO: Put Series/DataFrame in others? @pytest.mark.parametrize( "other", [ np.arange(1, 11), Index(np.arange(1, 11), np.int64), Index(range(1, 11), np.uint64), Index(range(1, 11), np.float64), pd.RangeIndex(1, 11), ], ids=lambda x: type(x).__name__, ) def test_tdi_rmul_arraylike(self, other, box_with_array): box = box_with_array
tdi = TimedeltaIndex(["1 Day"] * 10) expected = timedelta_range("1 days", "10 days")._with_freq(None)
tdi = tm.box_expected(tdi, box) xbox = get_upcast_box(tdi, other)
expected = tm.box_expected(expected, xbox)
result = other * tdi tm.assert_equal(result, expected) commute = tdi * other tm.assert_equal(commute, expected)
# ------------------------------------------------------------------ # __div__, __rdiv__
def test_td64arr_div_nat_invalid(self, box_with_array): # don't allow division by NaT (maybe could in the future) rng = timedelta_range("1 days", "10 days", name="foo") rng = tm.box_expected(rng, box_with_array)
with pytest.raises(TypeError, match="unsupported operand type"): rng / NaT with pytest.raises(TypeError, match="Cannot divide NaTType by"): NaT / rng
dt64nat = np.datetime64("NaT", "ns") msg = "|".join( [ # 'divide' on npdev as of 2021-12-18 "ufunc '(true_divide|divide)' cannot use operands", "cannot perform __r?truediv__", "Cannot divide datetime64 by TimedeltaArray", ] ) with pytest.raises(TypeError, match=msg): rng / dt64nat with pytest.raises(TypeError, match=msg): dt64nat / rng
def test_td64arr_div_td64nat(self, box_with_array): # GH#23829 box = box_with_array xbox = np.ndarray if box is pd.array else box
rng = timedelta_range("1 days", "10 days") rng = tm.box_expected(rng, box)
other = np.timedelta64("NaT")
expected = np.array([np.nan] * 10) expected = tm.box_expected(expected, xbox)
result = rng / other tm.assert_equal(result, expected)
result = other / rng tm.assert_equal(result, expected)
def test_td64arr_div_int(self, box_with_array): idx = TimedeltaIndex(np.arange(5, dtype="int64")) idx = tm.box_expected(idx, box_with_array)
result = idx / 1 tm.assert_equal(result, idx)
with pytest.raises(TypeError, match="Cannot divide"): # GH#23829 1 / idx
def test_td64arr_div_tdlike_scalar(self, two_hours, box_with_array): # GH#20088, GH#22163 ensure DataFrame returns correct dtype box = box_with_array xbox = np.ndarray if box is pd.array else box
rng = timedelta_range("1 days", "10 days", name="foo") expected = Index((np.arange(10) + 1) * 12, dtype=np.float64, name="foo")
rng = tm.box_expected(rng, box) expected = tm.box_expected(expected, xbox)
result = rng / two_hours tm.assert_equal(result, expected)
result = two_hours / rng expected = 1 / expected tm.assert_equal(result, expected)
@pytest.mark.parametrize("m", [1, 3, 10]) @pytest.mark.parametrize("unit", ["D", "h", "m", "s", "ms", "us", "ns"]) def test_td64arr_div_td64_scalar(self, m, unit, box_with_array): box = box_with_array xbox = np.ndarray if box is pd.array else box
ser = Series([Timedelta(days=59)] * 3) ser[2] = np.nan flat = ser ser = tm.box_expected(ser, box)
# op expected = Series([x / np.timedelta64(m, unit) for x in flat]) expected = tm.box_expected(expected, xbox) result = ser / np.timedelta64(m, unit) tm.assert_equal(result, expected)
# reverse op expected = Series([Timedelta(np.timedelta64(m, unit)) / x for x in flat]) expected = tm.box_expected(expected, xbox) result = np.timedelta64(m, unit) / ser tm.assert_equal(result, expected)
def test_td64arr_div_tdlike_scalar_with_nat(self, two_hours, box_with_array): box = box_with_array xbox = np.ndarray if box is pd.array else box
rng = TimedeltaIndex(["1 days", NaT, "2 days"], name="foo") expected = Index([12, np.nan, 24], dtype=np.float64, name="foo")
rng = tm.box_expected(rng, box) expected = tm.box_expected(expected, xbox)
result = rng / two_hours tm.assert_equal(result, expected)
result = two_hours / rng expected = 1 / expected tm.assert_equal(result, expected)
def test_td64arr_div_td64_ndarray(self, box_with_array): # GH#22631 box = box_with_array xbox = np.ndarray if box is pd.array else box
rng = TimedeltaIndex(["1 days", NaT, "2 days"]) expected = Index([12, np.nan, 24], dtype=np.float64)
rng = tm.box_expected(rng, box) expected = tm.box_expected(expected, xbox)
other = np.array([2, 4, 2], dtype="m8[h]") result = rng / other tm.assert_equal(result, expected)
result = rng / tm.box_expected(other, box) tm.assert_equal(result, expected)
result = rng / other.astype(object) tm.assert_equal(result, expected.astype(object))
result = rng / list(other) tm.assert_equal(result, expected)
# reversed op expected = 1 / expected result = other / rng tm.assert_equal(result, expected)
result = tm.box_expected(other, box) / rng tm.assert_equal(result, expected)
result = other.astype(object) / rng tm.assert_equal(result, expected)
result = list(other) / rng tm.assert_equal(result, expected)
def test_tdarr_div_length_mismatch(self, box_with_array): rng = TimedeltaIndex(["1 days", NaT, "2 days"]) mismatched = [1, 2, 3, 4]
rng = tm.box_expected(rng, box_with_array) msg = "Cannot divide vectors|Unable to coerce to Series" for obj in [mismatched, mismatched[:2]]: # one shorter, one longer for other in [obj, np.array(obj), Index(obj)]: with pytest.raises(ValueError, match=msg): rng / other with pytest.raises(ValueError, match=msg): other / rng
def test_td64_div_object_mixed_result(self, box_with_array): # Case where we having a NaT in the result inseat of timedelta64("NaT") # is misleading orig = timedelta_range("1 Day", periods=3).insert(1, NaT) tdi = tm.box_expected(orig, box_with_array, transpose=False)
other = np.array([orig[0], 1.5, 2.0, orig[2]], dtype=object) other = tm.box_expected(other, box_with_array, transpose=False)
res = tdi / other
expected = Index([1.0, np.timedelta64("NaT", "ns"), orig[0], 1.5], dtype=object) expected = tm.box_expected(expected, box_with_array, transpose=False) if isinstance(expected, NumpyExtensionArray): expected = expected.to_numpy() tm.assert_equal(res, expected) if box_with_array is DataFrame: # We have a np.timedelta64(NaT), not pd.NaT assert isinstance(res.iloc[1, 0], np.timedelta64)
res = tdi // other
expected = Index([1, np.timedelta64("NaT", "ns"), orig[0], 1], dtype=object) expected = tm.box_expected(expected, box_with_array, transpose=False) if isinstance(expected, NumpyExtensionArray): expected = expected.to_numpy() tm.assert_equal(res, expected) if box_with_array is DataFrame: # We have a np.timedelta64(NaT), not pd.NaT assert isinstance(res.iloc[1, 0], np.timedelta64)
# ------------------------------------------------------------------ # __floordiv__, __rfloordiv__
def test_td64arr_floordiv_td64arr_with_nat( self, box_with_array, using_array_manager ): # GH#35529 box = box_with_array xbox = np.ndarray if box is pd.array else box
left = Series([1000, 222330, 30], dtype="timedelta64[ns]") right = Series([1000, 222330, None], dtype="timedelta64[ns]")
left = tm.box_expected(left, box) right = tm.box_expected(right, box)
expected = np.array([1.0, 1.0, np.nan], dtype=np.float64) expected = tm.box_expected(expected, xbox) if box is DataFrame and using_array_manager: # INFO(ArrayManager) floordiv returns integer, and ArrayManager # performs ops column-wise and thus preserves int64 dtype for # columns without missing values expected[[0, 1]] = expected[[0, 1]].astype("int64")
with tm.maybe_produces_warning( RuntimeWarning, box is pd.array, check_stacklevel=False ): result = left // right
tm.assert_equal(result, expected)
# case that goes through __rfloordiv__ with arraylike with tm.maybe_produces_warning( RuntimeWarning, box is pd.array, check_stacklevel=False ): result = np.asarray(left) // right tm.assert_equal(result, expected)
@pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning") def test_td64arr_floordiv_tdscalar(self, box_with_array, scalar_td): # GH#18831, GH#19125 box = box_with_array xbox = np.ndarray if box is pd.array else box td = Timedelta("5m3s") # i.e. (scalar_td - 1sec) / 2
td1 = Series([td, td, NaT], dtype="m8[ns]") td1 = tm.box_expected(td1, box, transpose=False)
expected = Series([0, 0, np.nan]) expected = tm.box_expected(expected, xbox, transpose=False)
result = td1 // scalar_td tm.assert_equal(result, expected)
# Reversed op expected = Series([2, 2, np.nan]) expected = tm.box_expected(expected, xbox, transpose=False)
result = scalar_td // td1 tm.assert_equal(result, expected)
# same thing buts let's be explicit about calling __rfloordiv__ result = td1.__rfloordiv__(scalar_td) tm.assert_equal(result, expected)
def test_td64arr_floordiv_int(self, box_with_array): idx = TimedeltaIndex(np.arange(5, dtype="int64")) idx = tm.box_expected(idx, box_with_array) result = idx // 1 tm.assert_equal(result, idx)
pattern = "floor_divide cannot use operands|Cannot divide int by Timedelta*" with pytest.raises(TypeError, match=pattern): 1 // idx
# ------------------------------------------------------------------ # mod, divmod # TODO: operations with timedelta-like arrays, numeric arrays, # reversed ops
def test_td64arr_mod_tdscalar(self, box_with_array, three_days): tdi = timedelta_range("1 Day", "9 days") tdarr = tm.box_expected(tdi, box_with_array)
expected = TimedeltaIndex(["1 Day", "2 Days", "0 Days"] * 3) expected = tm.box_expected(expected, box_with_array)
result = tdarr % three_days tm.assert_equal(result, expected)
warn = None if box_with_array is DataFrame and isinstance(three_days, pd.DateOffset): warn = PerformanceWarning # TODO: making expected be object here a result of DataFrame.__divmod__ # being defined in a naive way that does not dispatch to the underlying # array's __divmod__ expected = expected.astype(object)
with tm.assert_produces_warning(warn): result = divmod(tdarr, three_days)
tm.assert_equal(result[1], expected) tm.assert_equal(result[0], tdarr // three_days)
def test_td64arr_mod_int(self, box_with_array): tdi = timedelta_range("1 ns", "10 ns", periods=10) tdarr = tm.box_expected(tdi, box_with_array)
expected = TimedeltaIndex(["1 ns", "0 ns"] * 5) expected = tm.box_expected(expected, box_with_array)
result = tdarr % 2 tm.assert_equal(result, expected)
msg = "Cannot divide int by" with pytest.raises(TypeError, match=msg): 2 % tdarr
result = divmod(tdarr, 2) tm.assert_equal(result[1], expected) tm.assert_equal(result[0], tdarr // 2)
def test_td64arr_rmod_tdscalar(self, box_with_array, three_days): tdi = timedelta_range("1 Day", "9 days") tdarr = tm.box_expected(tdi, box_with_array)
expected = ["0 Days", "1 Day", "0 Days"] + ["3 Days"] * 6 expected = TimedeltaIndex(expected) expected = tm.box_expected(expected, box_with_array)
result = three_days % tdarr tm.assert_equal(result, expected)
result = divmod(three_days, tdarr) tm.assert_equal(result[1], expected) tm.assert_equal(result[0], three_days // tdarr)
# ------------------------------------------------------------------ # Operations with invalid others
def test_td64arr_mul_tdscalar_invalid(self, box_with_array, scalar_td): td1 = Series([timedelta(minutes=5, seconds=3)] * 3) td1.iloc[2] = np.nan
td1 = tm.box_expected(td1, box_with_array)
# check that we are getting a TypeError # with 'operate' (from core/ops.py) for the ops that are not # defined pattern = "operate|unsupported|cannot|not supported" with pytest.raises(TypeError, match=pattern): td1 * scalar_td with pytest.raises(TypeError, match=pattern): scalar_td * td1
def test_td64arr_mul_too_short_raises(self, box_with_array): idx = TimedeltaIndex(np.arange(5, dtype="int64")) idx = tm.box_expected(idx, box_with_array) msg = "|".join( [ "cannot use operands with types dtype", "Cannot multiply with unequal lengths", "Unable to coerce to Series", ] ) with pytest.raises(TypeError, match=msg): # length check before dtype check idx * idx[:3] with pytest.raises(ValueError, match=msg): idx * np.array([1, 2])
def test_td64arr_mul_td64arr_raises(self, box_with_array): idx = TimedeltaIndex(np.arange(5, dtype="int64")) idx = tm.box_expected(idx, box_with_array) msg = "cannot use operands with types dtype" with pytest.raises(TypeError, match=msg): idx * idx
# ------------------------------------------------------------------ # Operations with numeric others
def test_td64arr_mul_numeric_scalar(self, box_with_array, one): # GH#4521 # divide/multiply by integers tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") expected = Series(["-59 Days", "-59 Days", "NaT"], dtype="timedelta64[ns]")
tdser = tm.box_expected(tdser, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = tdser * (-one) tm.assert_equal(result, expected) result = (-one) * tdser tm.assert_equal(result, expected)
expected = Series(["118 Days", "118 Days", "NaT"], dtype="timedelta64[ns]") expected = tm.box_expected(expected, box_with_array)
result = tdser * (2 * one) tm.assert_equal(result, expected) result = (2 * one) * tdser tm.assert_equal(result, expected)
@pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)]) def test_td64arr_div_numeric_scalar(self, box_with_array, two): # GH#4521 # divide/multiply by integers tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]")
tdser = tm.box_expected(tdser, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = tdser / two tm.assert_equal(result, expected)
with pytest.raises(TypeError, match="Cannot divide"): two / tdser
@pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)]) def test_td64arr_floordiv_numeric_scalar(self, box_with_array, two): tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]")
tdser = tm.box_expected(tdser, box_with_array) expected = tm.box_expected(expected, box_with_array)
result = tdser // two tm.assert_equal(result, expected)
with pytest.raises(TypeError, match="Cannot divide"): two // tdser
@pytest.mark.parametrize( "vector", [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])], ids=lambda x: type(x).__name__, ) def test_td64arr_rmul_numeric_array( self, box_with_array, vector, any_real_numpy_dtype, ): # GH#4521 # divide/multiply by integers
tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") vector = vector.astype(any_real_numpy_dtype)
expected = Series(["1180 Days", "1770 Days", "NaT"], dtype="timedelta64[ns]")
tdser = tm.box_expected(tdser, box_with_array) xbox = get_upcast_box(tdser, vector)
expected = tm.box_expected(expected, xbox)
result = tdser * vector tm.assert_equal(result, expected)
result = vector * tdser tm.assert_equal(result, expected)
@pytest.mark.parametrize( "vector", [np.array([20, 30, 40]), Index([20, 30, 40]), Series([20, 30, 40])], ids=lambda x: type(x).__name__, ) def test_td64arr_div_numeric_array( self, box_with_array, vector, any_real_numpy_dtype ): # GH#4521 # divide/multiply by integers
tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") vector = vector.astype(any_real_numpy_dtype)
expected = Series(["2.95D", "1D 23h 12m", "NaT"], dtype="timedelta64[ns]")
tdser = tm.box_expected(tdser, box_with_array) xbox = get_upcast_box(tdser, vector) expected = tm.box_expected(expected, xbox)
result = tdser / vector tm.assert_equal(result, expected)
pattern = "|".join( [ "true_divide'? cannot use operands", "cannot perform __div__", "cannot perform __truediv__", "unsupported operand", "Cannot divide", "ufunc 'divide' cannot use operands with types", ] ) with pytest.raises(TypeError, match=pattern): vector / tdser
result = tdser / vector.astype(object) if box_with_array is DataFrame: expected = [tdser.iloc[0, n] / vector[n] for n in range(len(vector))] expected = tm.box_expected(expected, xbox).astype(object) # We specifically expect timedelta64("NaT") here, not pd.NA msg = "The 'downcast' keyword in fillna" with tm.assert_produces_warning(FutureWarning, match=msg): expected[2] = expected[2].fillna( np.timedelta64("NaT", "ns"), downcast=False ) else: expected = [tdser[n] / vector[n] for n in range(len(tdser))] expected = [ x if x is not NaT else np.timedelta64("NaT", "ns") for x in expected ] if xbox is tm.to_array: expected = tm.to_array(expected).astype(object) else: expected = xbox(expected, dtype=object)
tm.assert_equal(result, expected)
with pytest.raises(TypeError, match=pattern): vector.astype(object) / tdser
def test_td64arr_mul_int_series(self, box_with_array, names): # GH#19042 test for correct name attachment box = box_with_array exname = get_expected_name(box, names)
tdi = TimedeltaIndex( ["0days", "1day", "2days", "3days", "4days"], name=names[0] ) # TODO: Should we be parametrizing over types for `ser` too? ser = Series([0, 1, 2, 3, 4], dtype=np.int64, name=names[1])
expected = Series( ["0days", "1day", "4days", "9days", "16days"], dtype="timedelta64[ns]", name=exname, )
tdi = tm.box_expected(tdi, box) xbox = get_upcast_box(tdi, ser)
expected = tm.box_expected(expected, xbox)
result = ser * tdi tm.assert_equal(result, expected)
result = tdi * ser tm.assert_equal(result, expected)
# TODO: Should we be parametrizing over types for `ser` too? def test_float_series_rdiv_td64arr(self, box_with_array, names): # GH#19042 test for correct name attachment box = box_with_array tdi = TimedeltaIndex( ["0days", "1day", "2days", "3days", "4days"], name=names[0] ) ser = Series([1.5, 3, 4.5, 6, 7.5], dtype=np.float64, name=names[1])
xname = names[2] if box not in [tm.to_array, pd.array] else names[1] expected = Series( [tdi[n] / ser[n] for n in range(len(ser))], dtype="timedelta64[ns]", name=xname, )
tdi = tm.box_expected(tdi, box) xbox = get_upcast_box(tdi, ser) expected = tm.box_expected(expected, xbox)
result = ser.__rtruediv__(tdi) if box is DataFrame: assert result is NotImplemented else: tm.assert_equal(result, expected)
def test_td64arr_all_nat_div_object_dtype_numeric(self, box_with_array): # GH#39750 make sure we infer the result as td64 tdi = TimedeltaIndex([NaT, NaT])
left = tm.box_expected(tdi, box_with_array) right = np.array([2, 2.0], dtype=object)
tdnat = np.timedelta64("NaT", "ns") expected = Index([tdnat] * 2, dtype=object) if box_with_array is not Index: expected = tm.box_expected(expected, box_with_array).astype(object) if box_with_array in [Series, DataFrame]: msg = "The 'downcast' keyword in fillna is deprecated" with tm.assert_produces_warning(FutureWarning, match=msg): expected = expected.fillna(tdnat, downcast=False) # GH#18463
result = left / right tm.assert_equal(result, expected)
result = left // right tm.assert_equal(result, expected)
class TestTimedelta64ArrayLikeArithmetic: # Arithmetic tests for timedelta64[ns] vectors fully parametrized over # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all arithmetic # tests will eventually end up here.
def test_td64arr_pow_invalid(self, scalar_td, box_with_array): td1 = Series([timedelta(minutes=5, seconds=3)] * 3) td1.iloc[2] = np.nan
td1 = tm.box_expected(td1, box_with_array)
# check that we are getting a TypeError # with 'operate' (from core/ops.py) for the ops that are not # defined pattern = "operate|unsupported|cannot|not supported" with pytest.raises(TypeError, match=pattern): scalar_td**td1
with pytest.raises(TypeError, match=pattern): td1**scalar_td
def test_add_timestamp_to_timedelta(): # GH: 35897 timestamp = Timestamp("2021-01-01") result = timestamp + timedelta_range("0s", "1s", periods=31) expected = DatetimeIndex( [ timestamp + ( pd.to_timedelta("0.033333333s") * i + pd.to_timedelta("0.000000001s") * divmod(i, 3)[0] ) for i in range(31) ] ) tm.assert_index_equal(result, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437import pytest
from pandas._config import config as cffrom pandas._config.config import OptionError
import pandas as pdimport pandas._testing as tm
class TestConfig: @pytest.fixture(autouse=True) def clean_config(self, monkeypatch): with monkeypatch.context() as m: m.setattr(cf, "_global_config", {}) m.setattr(cf, "options", cf.DictWrapper(cf._global_config)) m.setattr(cf, "_deprecated_options", {}) m.setattr(cf, "_registered_options", {})
# Our test fixture in conftest.py sets "chained_assignment" # to "raise" only after all test methods have been setup. # However, after this setup, there is no longer any # "chained_assignment" option, so re-register it. cf.register_option("chained_assignment", "raise") yield
def test_api(self): # the pandas object exposes the user API assert hasattr(pd, "get_option") assert hasattr(pd, "set_option") assert hasattr(pd, "reset_option") assert hasattr(pd, "describe_option")
def test_is_one_of_factory(self): v = cf.is_one_of_factory([None, 12])
v(12) v(None) msg = r"Value must be one of None\|12" with pytest.raises(ValueError, match=msg): v(1.1)
def test_register_option(self): cf.register_option("a", 1, "doc")
# can't register an already registered option msg = "Option 'a' has already been registered" with pytest.raises(OptionError, match=msg): cf.register_option("a", 1, "doc")
# can't register an already registered option msg = "Path prefix to option 'a' is already an option" with pytest.raises(OptionError, match=msg): cf.register_option("a.b.c.d1", 1, "doc") with pytest.raises(OptionError, match=msg): cf.register_option("a.b.c.d2", 1, "doc")
# no python keywords msg = "for is a python keyword" with pytest.raises(ValueError, match=msg): cf.register_option("for", 0) with pytest.raises(ValueError, match=msg): cf.register_option("a.for.b", 0) # must be valid identifier (ensure attribute access works) msg = "oh my goddess! is not a valid identifier" with pytest.raises(ValueError, match=msg): cf.register_option("Oh my Goddess!", 0)
# we can register options several levels deep # without predefining the intermediate steps # and we can define differently named options # in the same namespace cf.register_option("k.b.c.d1", 1, "doc") cf.register_option("k.b.c.d2", 1, "doc")
def test_describe_option(self): cf.register_option("a", 1, "doc") cf.register_option("b", 1, "doc2") cf.deprecate_option("b")
cf.register_option("c.d.e1", 1, "doc3") cf.register_option("c.d.e2", 1, "doc4") cf.register_option("f", 1) cf.register_option("g.h", 1) cf.register_option("k", 2) cf.deprecate_option("g.h", rkey="k") cf.register_option("l", "foo")
# non-existent keys raise KeyError msg = r"No such keys\(s\)" with pytest.raises(OptionError, match=msg): cf.describe_option("no.such.key")
# we can get the description for any key we registered assert "doc" in cf.describe_option("a", _print_desc=False) assert "doc2" in cf.describe_option("b", _print_desc=False) assert "precated" in cf.describe_option("b", _print_desc=False) assert "doc3" in cf.describe_option("c.d.e1", _print_desc=False) assert "doc4" in cf.describe_option("c.d.e2", _print_desc=False)
# if no doc is specified we get a default message # saying "description not available" assert "available" in cf.describe_option("f", _print_desc=False) assert "available" in cf.describe_option("g.h", _print_desc=False) assert "precated" in cf.describe_option("g.h", _print_desc=False) assert "k" in cf.describe_option("g.h", _print_desc=False)
# default is reported assert "foo" in cf.describe_option("l", _print_desc=False) # current value is reported assert "bar" not in cf.describe_option("l", _print_desc=False) cf.set_option("l", "bar") assert "bar" in cf.describe_option("l", _print_desc=False)
def test_case_insensitive(self): cf.register_option("KanBAN", 1, "doc")
assert "doc" in cf.describe_option("kanbaN", _print_desc=False) assert cf.get_option("kanBaN") == 1 cf.set_option("KanBan", 2) assert cf.get_option("kAnBaN") == 2
# gets of non-existent keys fail msg = r"No such keys\(s\): 'no_such_option'" with pytest.raises(OptionError, match=msg): cf.get_option("no_such_option") cf.deprecate_option("KanBan")
assert cf._is_deprecated("kAnBaN")
def test_get_option(self): cf.register_option("a", 1, "doc") cf.register_option("b.c", "hullo", "doc2") cf.register_option("b.b", None, "doc2")
# gets of existing keys succeed assert cf.get_option("a") == 1 assert cf.get_option("b.c") == "hullo" assert cf.get_option("b.b") is None
# gets of non-existent keys fail msg = r"No such keys\(s\): 'no_such_option'" with pytest.raises(OptionError, match=msg): cf.get_option("no_such_option")
def test_set_option(self): cf.register_option("a", 1, "doc") cf.register_option("b.c", "hullo", "doc2") cf.register_option("b.b", None, "doc2")
assert cf.get_option("a") == 1 assert cf.get_option("b.c") == "hullo" assert cf.get_option("b.b") is None
cf.set_option("a", 2) cf.set_option("b.c", "wurld") cf.set_option("b.b", 1.1)
assert cf.get_option("a") == 2 assert cf.get_option("b.c") == "wurld" assert cf.get_option("b.b") == 1.1
msg = r"No such keys\(s\): 'no.such.key'" with pytest.raises(OptionError, match=msg): cf.set_option("no.such.key", None)
def test_set_option_empty_args(self): msg = "Must provide an even number of non-keyword arguments" with pytest.raises(ValueError, match=msg): cf.set_option()
def test_set_option_uneven_args(self): msg = "Must provide an even number of non-keyword arguments" with pytest.raises(ValueError, match=msg): cf.set_option("a.b", 2, "b.c")
def test_set_option_invalid_single_argument_type(self): msg = "Must provide an even number of non-keyword arguments" with pytest.raises(ValueError, match=msg): cf.set_option(2)
def test_set_option_multiple(self): cf.register_option("a", 1, "doc") cf.register_option("b.c", "hullo", "doc2") cf.register_option("b.b", None, "doc2")
assert cf.get_option("a") == 1 assert cf.get_option("b.c") == "hullo" assert cf.get_option("b.b") is None
cf.set_option("a", "2", "b.c", None, "b.b", 10.0)
assert cf.get_option("a") == "2" assert cf.get_option("b.c") is None assert cf.get_option("b.b") == 10.0
def test_validation(self): cf.register_option("a", 1, "doc", validator=cf.is_int) cf.register_option("d", 1, "doc", validator=cf.is_nonnegative_int) cf.register_option("b.c", "hullo", "doc2", validator=cf.is_text)
msg = "Value must have type '<class 'int'>'" with pytest.raises(ValueError, match=msg): cf.register_option("a.b.c.d2", "NO", "doc", validator=cf.is_int)
cf.set_option("a", 2) # int is_int cf.set_option("b.c", "wurld") # str is_str cf.set_option("d", 2) cf.set_option("d", None) # non-negative int can be None
# None not is_int with pytest.raises(ValueError, match=msg): cf.set_option("a", None) with pytest.raises(ValueError, match=msg): cf.set_option("a", "ab")
msg = "Value must be a nonnegative integer or None" with pytest.raises(ValueError, match=msg): cf.register_option("a.b.c.d3", "NO", "doc", validator=cf.is_nonnegative_int) with pytest.raises(ValueError, match=msg): cf.register_option("a.b.c.d3", -2, "doc", validator=cf.is_nonnegative_int)
msg = r"Value must be an instance of <class 'str'>\|<class 'bytes'>" with pytest.raises(ValueError, match=msg): cf.set_option("b.c", 1)
validator = cf.is_one_of_factory([None, cf.is_callable]) cf.register_option("b", lambda: None, "doc", validator=validator) # pylint: disable-next=consider-using-f-string cf.set_option("b", "%.1f".format) # Formatter is callable cf.set_option("b", None) # Formatter is none (default) with pytest.raises(ValueError, match="Value must be a callable"): cf.set_option("b", "%.1f")
def test_reset_option(self): cf.register_option("a", 1, "doc", validator=cf.is_int) cf.register_option("b.c", "hullo", "doc2", validator=cf.is_str) assert cf.get_option("a") == 1 assert cf.get_option("b.c") == "hullo"
cf.set_option("a", 2) cf.set_option("b.c", "wurld") assert cf.get_option("a") == 2 assert cf.get_option("b.c") == "wurld"
cf.reset_option("a") assert cf.get_option("a") == 1 assert cf.get_option("b.c") == "wurld" cf.reset_option("b.c") assert cf.get_option("a") == 1 assert cf.get_option("b.c") == "hullo"
def test_reset_option_all(self): cf.register_option("a", 1, "doc", validator=cf.is_int) cf.register_option("b.c", "hullo", "doc2", validator=cf.is_str) assert cf.get_option("a") == 1 assert cf.get_option("b.c") == "hullo"
cf.set_option("a", 2) cf.set_option("b.c", "wurld") assert cf.get_option("a") == 2 assert cf.get_option("b.c") == "wurld"
cf.reset_option("all") assert cf.get_option("a") == 1 assert cf.get_option("b.c") == "hullo"
def test_deprecate_option(self): # we can deprecate non-existent options cf.deprecate_option("foo")
assert cf._is_deprecated("foo") with tm.assert_produces_warning(FutureWarning, match="deprecated"): with pytest.raises(KeyError, match="No such keys.s.: 'foo'"): cf.get_option("foo")
cf.register_option("a", 1, "doc", validator=cf.is_int) cf.register_option("b.c", "hullo", "doc2") cf.register_option("foo", "hullo", "doc2")
cf.deprecate_option("a", removal_ver="nifty_ver") with tm.assert_produces_warning(FutureWarning, match="eprecated.*nifty_ver"): cf.get_option("a")
msg = "Option 'a' has already been defined as deprecated" with pytest.raises(OptionError, match=msg): cf.deprecate_option("a")
cf.deprecate_option("b.c", "zounds!") with tm.assert_produces_warning(FutureWarning, match="zounds!"): cf.get_option("b.c")
# test rerouting keys cf.register_option("d.a", "foo", "doc2") cf.register_option("d.dep", "bar", "doc2") assert cf.get_option("d.a") == "foo" assert cf.get_option("d.dep") == "bar"
cf.deprecate_option("d.dep", rkey="d.a") # reroute d.dep to d.a with tm.assert_produces_warning(FutureWarning, match="eprecated"): assert cf.get_option("d.dep") == "foo"
with tm.assert_produces_warning(FutureWarning, match="eprecated"): cf.set_option("d.dep", "baz") # should overwrite "d.a"
with tm.assert_produces_warning(FutureWarning, match="eprecated"): assert cf.get_option("d.dep") == "baz"
def test_config_prefix(self): with cf.config_prefix("base"): cf.register_option("a", 1, "doc1") cf.register_option("b", 2, "doc2") assert cf.get_option("a") == 1 assert cf.get_option("b") == 2
cf.set_option("a", 3) cf.set_option("b", 4) assert cf.get_option("a") == 3 assert cf.get_option("b") == 4
assert cf.get_option("base.a") == 3 assert cf.get_option("base.b") == 4 assert "doc1" in cf.describe_option("base.a", _print_desc=False) assert "doc2" in cf.describe_option("base.b", _print_desc=False)
cf.reset_option("base.a") cf.reset_option("base.b")
with cf.config_prefix("base"): assert cf.get_option("a") == 1 assert cf.get_option("b") == 2
def test_callback(self): k = [None] v = [None]
def callback(key): k.append(key) v.append(cf.get_option(key))
cf.register_option("d.a", "foo", cb=callback) cf.register_option("d.b", "foo", cb=callback)
del k[-1], v[-1] cf.set_option("d.a", "fooz") assert k[-1] == "d.a" assert v[-1] == "fooz"
del k[-1], v[-1] cf.set_option("d.b", "boo") assert k[-1] == "d.b" assert v[-1] == "boo"
del k[-1], v[-1] cf.reset_option("d.b") assert k[-1] == "d.b"
def test_set_ContextManager(self): def eq(val): assert cf.get_option("a") == val
cf.register_option("a", 0) eq(0) with cf.option_context("a", 15): eq(15) with cf.option_context("a", 25): eq(25) eq(15) eq(0)
cf.set_option("a", 17) eq(17)
# Test that option_context can be used as a decorator too (#34253). @cf.option_context("a", 123) def f(): eq(123)
f()
def test_attribute_access(self): holder = []
def f3(key): holder.append(True)
cf.register_option("a", 0) cf.register_option("c", 0, cb=f3) options = cf.options
assert options.a == 0 with cf.option_context("a", 15): assert options.a == 15
options.a = 500 assert cf.get_option("a") == 500
cf.reset_option("a") assert options.a == cf.get_option("a", 0)
msg = "You can only set the value of existing options" with pytest.raises(OptionError, match=msg): options.b = 1 with pytest.raises(OptionError, match=msg): options.display = 1
# make sure callback kicks when using this form of setting options.c = 1 assert len(holder) == 1
def test_option_context_scope(self): # Ensure that creating a context does not affect the existing # environment as it is supposed to be used with the `with` statement. # See https://github.com/pandas-dev/pandas/issues/8514
original_value = 60 context_value = 10 option_name = "a"
cf.register_option(option_name, original_value)
# Ensure creating contexts didn't affect the current context. ctx = cf.option_context(option_name, context_value) assert cf.get_option(option_name) == original_value
# Ensure the correct value is available inside the context. with ctx: assert cf.get_option(option_name) == context_value
# Ensure the current context is reset assert cf.get_option(option_name) == original_value
def test_dictwrapper_getattr(self): options = cf.options # GH 19789 with pytest.raises(OptionError, match="No such option"): options.bananas assert not hasattr(options, "bananas")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156import codecsimport localeimport os
import pytest
from pandas._config.localization import ( can_set_locale, get_locales, set_locale,)
from pandas.compat import ISMUSL
import pandas as pd
_all_locales = get_locales()_current_locale = locale.setlocale(locale.LC_ALL) # getlocale() is wrong, see GH#46595
# Don't run any of these tests if we have no locales.pytestmark = pytest.mark.skipif(not _all_locales, reason="Need locales")
_skip_if_only_one_locale = pytest.mark.skipif( len(_all_locales) <= 1, reason="Need multiple locales for meaningful test")
def _get_current_locale(lc_var: int = locale.LC_ALL) -> str: # getlocale is not always compliant with setlocale, use setlocale. GH#46595 return locale.setlocale(lc_var)
@pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))def test_can_set_current_locale(lc_var): # Can set the current locale before_locale = _get_current_locale(lc_var) assert can_set_locale(before_locale, lc_var=lc_var) after_locale = _get_current_locale(lc_var) assert before_locale == after_locale
@pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))def test_can_set_locale_valid_set(lc_var): # Can set the default locale. before_locale = _get_current_locale(lc_var) assert can_set_locale("", lc_var=lc_var) after_locale = _get_current_locale(lc_var) assert before_locale == after_locale
@pytest.mark.parametrize( "lc_var", ( locale.LC_ALL, locale.LC_CTYPE, pytest.param( locale.LC_TIME, marks=pytest.mark.skipif( ISMUSL, reason="MUSL allows setting invalid LC_TIME." ), ), ),)def test_can_set_locale_invalid_set(lc_var): # Cannot set an invalid locale. before_locale = _get_current_locale(lc_var) assert not can_set_locale("non-existent_locale", lc_var=lc_var) after_locale = _get_current_locale(lc_var) assert before_locale == after_locale
@pytest.mark.parametrize( "lang,enc", [ ("it_CH", "UTF-8"), ("en_US", "ascii"), ("zh_CN", "GB2312"), ("it_IT", "ISO-8859-1"), ],)@pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))def test_can_set_locale_no_leak(lang, enc, lc_var): # Test that can_set_locale does not leak even when returning False. See GH#46595 before_locale = _get_current_locale(lc_var) can_set_locale((lang, enc), locale.LC_ALL) after_locale = _get_current_locale(lc_var) assert before_locale == after_locale
def test_can_set_locale_invalid_get(monkeypatch): # see GH#22129 # In some cases, an invalid locale can be set, # but a subsequent getlocale() raises a ValueError.
def mock_get_locale(): raise ValueError()
with monkeypatch.context() as m: m.setattr(locale, "getlocale", mock_get_locale) assert not can_set_locale("")
def test_get_locales_at_least_one(): # see GH#9744 assert len(_all_locales) > 0
@_skip_if_only_one_localedef test_get_locales_prefix(): first_locale = _all_locales[0] assert len(get_locales(prefix=first_locale[:2])) > 0
@_skip_if_only_one_locale@pytest.mark.parametrize( "lang,enc", [ ("it_CH", "UTF-8"), ("en_US", "ascii"), ("zh_CN", "GB2312"), ("it_IT", "ISO-8859-1"), ],)def test_set_locale(lang, enc): before_locale = _get_current_locale()
enc = codecs.lookup(enc).name new_locale = lang, enc
if not can_set_locale(new_locale): msg = "unsupported locale setting"
with pytest.raises(locale.Error, match=msg): with set_locale(new_locale): pass else: with set_locale(new_locale) as normalized_locale: new_lang, new_enc = normalized_locale.split(".") new_enc = codecs.lookup(enc).name
normalized_locale = new_lang, new_enc assert normalized_locale == new_locale
# Once we exit the "with" statement, locale should be back to what it was. after_locale = _get_current_locale() assert before_locale == after_locale
def test_encoding_detected(): system_locale = os.environ.get("LC_ALL") system_encoding = system_locale.split(".")[-1] if system_locale else "utf-8"
assert ( codecs.lookup(pd.options.display.encoding).name == codecs.lookup(system_encoding).name )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import pytest
from pandas import ( DatetimeIndex, Series, Timestamp, date_range,)import pandas._testing as tm
pytestmark = pytest.mark.filterwarnings( "ignore:Setting a value on a view:FutureWarning")
@pytest.mark.parametrize( "cons", [ lambda x: DatetimeIndex(x), lambda x: DatetimeIndex(DatetimeIndex(x)), ],)def test_datetimeindex(using_copy_on_write, cons): dt = date_range("2019-12-31", periods=3, freq="D") ser = Series(dt) idx = cons(ser) expected = idx.copy(deep=True) ser.iloc[0] = Timestamp("2020-12-31") if using_copy_on_write: tm.assert_index_equal(idx, expected)
def test_datetimeindex_tz_convert(using_copy_on_write): dt = date_range("2019-12-31", periods=3, freq="D", tz="Europe/Berlin") ser = Series(dt) idx = DatetimeIndex(ser).tz_convert("US/Eastern") expected = idx.copy(deep=True) ser.iloc[0] = Timestamp("2020-12-31", tz="Europe/Berlin") if using_copy_on_write: tm.assert_index_equal(idx, expected)
def test_datetimeindex_tz_localize(using_copy_on_write): dt = date_range("2019-12-31", periods=3, freq="D") ser = Series(dt) idx = DatetimeIndex(ser).tz_localize("Europe/Berlin") expected = idx.copy(deep=True) ser.iloc[0] = Timestamp("2020-12-31") if using_copy_on_write: tm.assert_index_equal(idx, expected)
def test_datetimeindex_isocalendar(using_copy_on_write): dt = date_range("2019-12-31", periods=3, freq="D") ser = Series(dt) df = DatetimeIndex(ser).isocalendar() expected = df.index.copy(deep=True) ser.iloc[0] = Timestamp("2020-12-31") if using_copy_on_write: tm.assert_index_equal(df.index, expected)
def test_index_values(using_copy_on_write): idx = date_range("2019-12-31", periods=3, freq="D") result = idx.values if using_copy_on_write: assert result.flags.writeable is False else: assert result.flags.writeable is Truelib/python3.12/site-packages/pandas/tests/api/__pycache__/test_api.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__init__.pyAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/common.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/conftest.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_array_ops.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_categorical.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_interval.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_numeric.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_object.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/__pycache__/test_period.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/arithmetic/common.pyAdded+155
lib/python3.12/site-packages/pandas/tests/arithmetic/conftest.pyAdded+139
lib/python3.12/site-packages/pandas/tests/arithmetic/test_array_ops.pyAdded+39
lib/python3.12/site-packages/pandas/tests/arithmetic/test_categorical.pyAdded+25
lib/python3.12/site-packages/pandas/tests/arithmetic/test_datetime64.pyAdded+2469
lib/python3.12/site-packages/pandas/tests/arithmetic/test_interval.pyAdded+306
lib/python3.12/site-packages/pandas/tests/arithmetic/test_numeric.pyAdded+1567
lib/python3.12/site-packages/pandas/tests/arithmetic/test_object.pyAdded+420
lib/python3.12/site-packages/pandas/tests/arithmetic/test_period.pyAdded+1675
lib/python3.12/site-packages/pandas/tests/arithmetic/test_timedelta64.pyAdded+2179
lib/python3.12/site-packages/pandas/tests/config/__init__.pyAdded
lib/python3.12/site-packages/pandas/tests/config/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/config/__pycache__/test_config.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/config/__pycache__/test_localization.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/config/test_config.pyAdded+437
lib/python3.12/site-packages/pandas/tests/config/test_localization.pyAdded+156
lib/python3.12/site-packages/pandas/tests/copy_view/__init__.pyAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_array.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_astype.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_chained_assignment_deprecation.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_clip.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_constructors.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_core_functionalities.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_functions.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_indexing.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_internals.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_interp_fillna.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_replace.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_setitem.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_util.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/util.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/index/__init__.pyAdded
lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/test_datetimeindex.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/test_index.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/test_periodindex.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/index/__pycache__/test_timedeltaindex.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/copy_view/index/test_datetimeindex.pyAdded+69