content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
from datetime import datetime\n\nimport pytest\nimport pytz\n\nfrom pandas.errors import NullFrequencyError\n\nimport pandas as pd\nfrom pandas import (\n DatetimeIndex,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\nSTART, END = datetime(2009, 1, 1), datetime(2010, 1, 1)\n\n\nclass TestDatetimeIndexShift:\n # -------------------------------------------------------------\n # DatetimeIndex.shift is used in integer addition\n\n def test_dti_shift_tzaware(self, tz_naive_fixture, unit):\n # GH#9903\n tz = tz_naive_fixture\n idx = DatetimeIndex([], name="xxx", tz=tz).as_unit(unit)\n tm.assert_index_equal(idx.shift(0, freq="h"), idx)\n tm.assert_index_equal(idx.shift(3, freq="h"), idx)\n\n idx = DatetimeIndex(\n ["2011-01-01 10:00", "2011-01-01 11:00", "2011-01-01 12:00"],\n name="xxx",\n tz=tz,\n freq="h",\n ).as_unit(unit)\n tm.assert_index_equal(idx.shift(0, freq="h"), idx)\n exp = DatetimeIndex(\n ["2011-01-01 13:00", "2011-01-01 14:00", "2011-01-01 15:00"],\n name="xxx",\n tz=tz,\n freq="h",\n ).as_unit(unit)\n tm.assert_index_equal(idx.shift(3, freq="h"), exp)\n exp = DatetimeIndex(\n ["2011-01-01 07:00", "2011-01-01 08:00", "2011-01-01 09:00"],\n name="xxx",\n tz=tz,\n freq="h",\n ).as_unit(unit)\n tm.assert_index_equal(idx.shift(-3, freq="h"), exp)\n\n def test_dti_shift_freqs(self, unit):\n # test shift for DatetimeIndex and non DatetimeIndex\n # GH#8083\n drange = date_range("20130101", periods=5, unit=unit)\n result = drange.shift(1)\n expected = DatetimeIndex(\n ["2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05", "2013-01-06"],\n dtype=f"M8[{unit}]",\n freq="D",\n )\n tm.assert_index_equal(result, expected)\n\n result = drange.shift(-1)\n expected = DatetimeIndex(\n ["2012-12-31", "2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04"],\n dtype=f"M8[{unit}]",\n freq="D",\n )\n tm.assert_index_equal(result, expected)\n\n result = drange.shift(3, freq="2D")\n expected = DatetimeIndex(\n ["2013-01-07", "2013-01-08", "2013-01-09", "2013-01-10", "2013-01-11"],\n dtype=f"M8[{unit}]",\n freq="D",\n )\n tm.assert_index_equal(result, expected)\n\n def test_dti_shift_int(self, unit):\n rng = date_range("1/1/2000", periods=20, unit=unit)\n\n result = rng + 5 * rng.freq\n expected = rng.shift(5)\n tm.assert_index_equal(result, expected)\n\n result = rng - 5 * rng.freq\n expected = rng.shift(-5)\n tm.assert_index_equal(result, expected)\n\n def test_dti_shift_no_freq(self, unit):\n # GH#19147\n dti = DatetimeIndex(["2011-01-01 10:00", "2011-01-01"], freq=None).as_unit(unit)\n with pytest.raises(NullFrequencyError, match="Cannot shift with no freq"):\n dti.shift(2)\n\n @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])\n def test_dti_shift_localized(self, tzstr, unit):\n dr = date_range("2011/1/1", "2012/1/1", freq="W-FRI", unit=unit)\n dr_tz = dr.tz_localize(tzstr)\n\n result = dr_tz.shift(1, "10min")\n assert result.tz == dr_tz.tz\n\n def test_dti_shift_across_dst(self, unit):\n # GH 8616\n idx = date_range(\n "2013-11-03", tz="America/Chicago", periods=7, freq="h", unit=unit\n )\n ser = Series(index=idx[:-1], dtype=object)\n result = ser.shift(freq="h")\n expected = Series(index=idx[1:], dtype=object)\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n "shift, result_time",\n [\n [0, "2014-11-14 00:00:00"],\n [-1, "2014-11-13 23:00:00"],\n [1, "2014-11-14 01:00:00"],\n ],\n )\n def test_dti_shift_near_midnight(self, shift, result_time, unit):\n # GH 8616\n dt = datetime(2014, 11, 14, 0)\n dt_est = pytz.timezone("EST").localize(dt)\n idx = DatetimeIndex([dt_est]).as_unit(unit)\n ser = Series(data=[1], index=idx)\n result = ser.shift(shift, freq="h")\n exp_index = DatetimeIndex([result_time], tz="EST").as_unit(unit)\n expected = Series(1, index=exp_index)\n tm.assert_series_equal(result, expected)\n\n def test_shift_periods(self, unit):\n # GH#22458 : argument 'n' was deprecated in favor of 'periods'\n idx = date_range(start=START, end=END, periods=3, unit=unit)\n tm.assert_index_equal(idx.shift(periods=0), idx)\n tm.assert_index_equal(idx.shift(0), idx)\n\n @pytest.mark.parametrize("freq", ["B", "C"])\n def test_shift_bday(self, freq, unit):\n rng = date_range(START, END, freq=freq, unit=unit)\n shifted = rng.shift(5)\n assert shifted[0] == rng[5]\n assert shifted.freq == rng.freq\n\n shifted = rng.shift(-5)\n assert shifted[5] == rng[0]\n assert shifted.freq == rng.freq\n\n shifted = rng.shift(0)\n assert shifted[0] == rng[0]\n assert shifted.freq == rng.freq\n\n def test_shift_bmonth(self, unit):\n rng = date_range(START, END, freq=pd.offsets.BMonthEnd(), unit=unit)\n shifted = rng.shift(1, freq=pd.offsets.BDay())\n assert shifted[0] == rng[0] + pd.offsets.BDay()\n\n rng = date_range(START, END, freq=pd.offsets.BMonthEnd(), unit=unit)\n with tm.assert_produces_warning(pd.errors.PerformanceWarning):\n shifted = rng.shift(1, freq=pd.offsets.CDay())\n assert shifted[0] == rng[0] + pd.offsets.CDay()\n\n def test_shift_empty(self, unit):\n # GH#14811\n dti = date_range(start="2016-10-21", end="2016-10-21", freq="BME", unit=unit)\n result = dti.shift(1)\n tm.assert_index_equal(result, dti)\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_shift.py
test_shift.py
Python
5,933
0.95
0.076923
0.06993
vue-tools
189
2024-03-19T17:53:08.824310
Apache-2.0
true
b7ffb9cbcd67b01d521d35848be949a3
import pytest\n\nfrom pandas import (\n DatetimeIndex,\n date_range,\n)\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize("tz", [None, "Asia/Shanghai", "Europe/Berlin"])\n@pytest.mark.parametrize("name", [None, "my_dti"])\n@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\ndef test_dti_snap(name, tz, unit):\n dti = DatetimeIndex(\n [\n "1/1/2002",\n "1/2/2002",\n "1/3/2002",\n "1/4/2002",\n "1/5/2002",\n "1/6/2002",\n "1/7/2002",\n ],\n name=name,\n tz=tz,\n freq="D",\n )\n dti = dti.as_unit(unit)\n\n result = dti.snap(freq="W-MON")\n expected = date_range("12/31/2001", "1/7/2002", name=name, tz=tz, freq="w-mon")\n expected = expected.repeat([3, 4])\n expected = expected.as_unit(unit)\n tm.assert_index_equal(result, expected)\n assert result.tz == expected.tz\n assert result.freq is None\n assert expected.freq is None\n\n result = dti.snap(freq="B")\n\n expected = date_range("1/1/2002", "1/7/2002", name=name, tz=tz, freq="b")\n expected = expected.repeat([1, 1, 1, 2, 2])\n expected = expected.as_unit(unit)\n tm.assert_index_equal(result, expected)\n assert result.tz == expected.tz\n assert result.freq is None\n assert expected.freq is None\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_snap.py
test_snap.py
Python
1,305
0.85
0.021277
0
python-kit
131
2023-11-14T11:32:35.226975
BSD-3-Clause
true
2db4f9539ab6d06ea500c0c50d587b88
from pandas import (\n DataFrame,\n Index,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestToFrame:\n def test_to_frame_datetime_tz(self):\n # GH#25809\n idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC")\n result = idx.to_frame()\n expected = DataFrame(idx, index=idx)\n tm.assert_frame_equal(result, expected)\n\n def test_to_frame_respects_none_name(self):\n # GH#44212 if we explicitly pass name=None, then that should be respected,\n # not changed to 0\n # GH-45448 this is first deprecated to only change in the future\n idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC")\n result = idx.to_frame(name=None)\n exp_idx = Index([None], dtype=object)\n tm.assert_index_equal(exp_idx, result.columns)\n\n result = idx.rename("foo").to_frame(name=None)\n exp_idx = Index([None], dtype=object)\n tm.assert_index_equal(exp_idx, result.columns)\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_to_frame.py
test_to_frame.py
Python
998
0.95
0.142857
0.166667
awesome-app
322
2024-03-23T18:11:51.856124
GPL-3.0
true
717d57e1fadeef261d522e69a146d731
import numpy as np\n\nfrom pandas import (\n Index,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDateTimeIndexToJulianDate:\n def test_1700(self):\n dr = date_range(start=Timestamp("1710-10-01"), periods=5, freq="D")\n r1 = Index([x.to_julian_date() for x in dr])\n r2 = dr.to_julian_date()\n assert isinstance(r2, Index) and r2.dtype == np.float64\n tm.assert_index_equal(r1, r2)\n\n def test_2000(self):\n dr = date_range(start=Timestamp("2000-02-27"), periods=5, freq="D")\n r1 = Index([x.to_julian_date() for x in dr])\n r2 = dr.to_julian_date()\n assert isinstance(r2, Index) and r2.dtype == np.float64\n tm.assert_index_equal(r1, r2)\n\n def test_hour(self):\n dr = date_range(start=Timestamp("2000-02-27"), periods=5, freq="h")\n r1 = Index([x.to_julian_date() for x in dr])\n r2 = dr.to_julian_date()\n assert isinstance(r2, Index) and r2.dtype == np.float64\n tm.assert_index_equal(r1, r2)\n\n def test_minute(self):\n dr = date_range(start=Timestamp("2000-02-27"), periods=5, freq="min")\n r1 = Index([x.to_julian_date() for x in dr])\n r2 = dr.to_julian_date()\n assert isinstance(r2, Index) and r2.dtype == np.float64\n tm.assert_index_equal(r1, r2)\n\n def test_second(self):\n dr = date_range(start=Timestamp("2000-02-27"), periods=5, freq="s")\n r1 = Index([x.to_julian_date() for x in dr])\n r2 = dr.to_julian_date()\n assert isinstance(r2, Index) and r2.dtype == np.float64\n tm.assert_index_equal(r1, r2)\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_to_julian_date.py
test_to_julian_date.py
Python
1,608
0.85
0.244444
0
node-utils
217
2024-11-12T10:45:47.327876
MIT
true
286e49b011144ac558dc093ac9261cd4
import dateutil.tz\nfrom dateutil.tz import tzlocal\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs.ccalendar import MONTHS\nfrom pandas._libs.tslibs.offsets import MonthEnd\nfrom pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG\n\nfrom pandas import (\n DatetimeIndex,\n Period,\n PeriodIndex,\n Timestamp,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestToPeriod:\n def test_dti_to_period(self):\n dti = date_range(start="1/1/2005", end="12/1/2005", freq="ME")\n pi1 = dti.to_period()\n pi2 = dti.to_period(freq="D")\n pi3 = dti.to_period(freq="3D")\n\n assert pi1[0] == Period("Jan 2005", freq="M")\n assert pi2[0] == Period("1/31/2005", freq="D")\n assert pi3[0] == Period("1/31/2005", freq="3D")\n\n assert pi1[-1] == Period("Nov 2005", freq="M")\n assert pi2[-1] == Period("11/30/2005", freq="D")\n assert pi3[-1], Period("11/30/2005", freq="3D")\n\n tm.assert_index_equal(pi1, period_range("1/1/2005", "11/1/2005", freq="M"))\n tm.assert_index_equal(\n pi2, period_range("1/1/2005", "11/1/2005", freq="M").asfreq("D")\n )\n tm.assert_index_equal(\n pi3, period_range("1/1/2005", "11/1/2005", freq="M").asfreq("3D")\n )\n\n @pytest.mark.parametrize("month", MONTHS)\n def test_to_period_quarterly(self, month):\n # make sure we can make the round trip\n freq = f"Q-{month}"\n rng = period_range("1989Q3", "1991Q3", freq=freq)\n stamps = rng.to_timestamp()\n result = stamps.to_period(freq)\n tm.assert_index_equal(rng, result)\n\n @pytest.mark.parametrize("off", ["BQE", "QS", "BQS"])\n def test_to_period_quarterlyish(self, off):\n rng = date_range("01-Jan-2012", periods=8, freq=off)\n prng = rng.to_period()\n assert prng.freq == "QE-DEC"\n\n @pytest.mark.parametrize("off", ["BYE", "YS", "BYS"])\n def test_to_period_annualish(self, off):\n rng = date_range("01-Jan-2012", periods=8, freq=off)\n prng = rng.to_period()\n assert prng.freq == "YE-DEC"\n\n def test_to_period_monthish(self):\n offsets = ["MS", "BME"]\n for off in offsets:\n rng = date_range("01-Jan-2012", periods=8, freq=off)\n prng = rng.to_period()\n assert prng.freqstr == "M"\n\n rng = date_range("01-Jan-2012", periods=8, freq="ME")\n prng = rng.to_period()\n assert prng.freqstr == "M"\n\n with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):\n date_range("01-Jan-2012", periods=8, freq="EOM")\n\n @pytest.mark.parametrize(\n "freq_offset, freq_period",\n [\n ("2ME", "2M"),\n (MonthEnd(2), MonthEnd(2)),\n ],\n )\n def test_dti_to_period_2monthish(self, freq_offset, freq_period):\n dti = date_range("2020-01-01", periods=3, freq=freq_offset)\n pi = dti.to_period()\n\n tm.assert_index_equal(pi, period_range("2020-01", "2020-05", freq=freq_period))\n\n @pytest.mark.parametrize(\n "freq, freq_depr",\n [\n ("2ME", "2M"),\n ("2QE", "2Q"),\n ("2QE-SEP", "2Q-SEP"),\n ("1YE", "1Y"),\n ("2YE-MAR", "2Y-MAR"),\n ("1YE", "1A"),\n ("2YE-MAR", "2A-MAR"),\n ],\n )\n def test_to_period_frequency_M_Q_Y_A_deprecated(self, freq, freq_depr):\n # GH#9586\n msg = f"'{freq_depr[1:]}' is deprecated and will be removed "\n f"in a future version, please use '{freq[1:]}' instead."\n\n rng = date_range("01-Jan-2012", periods=8, freq=freq)\n prng = rng.to_period()\n with tm.assert_produces_warning(FutureWarning, match=msg):\n assert prng.freq == freq_depr\n\n def test_to_period_infer(self):\n # https://github.com/pandas-dev/pandas/issues/33358\n rng = date_range(\n start="2019-12-22 06:40:00+00:00",\n end="2019-12-22 08:45:00+00:00",\n freq="5min",\n )\n\n with tm.assert_produces_warning(UserWarning):\n pi1 = rng.to_period("5min")\n\n with tm.assert_produces_warning(UserWarning):\n pi2 = rng.to_period()\n\n tm.assert_index_equal(pi1, pi2)\n\n @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\n def test_period_dt64_round_trip(self):\n dti = date_range("1/1/2000", "1/7/2002", freq="B")\n pi = dti.to_period()\n tm.assert_index_equal(pi.to_timestamp(), dti)\n\n dti = date_range("1/1/2000", "1/7/2002", freq="B")\n pi = dti.to_period(freq="h")\n tm.assert_index_equal(pi.to_timestamp(), dti)\n\n def test_to_period_millisecond(self):\n index = DatetimeIndex(\n [\n Timestamp("2007-01-01 10:11:12.123456Z"),\n Timestamp("2007-01-01 10:11:13.789123Z"),\n ]\n )\n\n with tm.assert_produces_warning(UserWarning):\n # warning that timezone info will be lost\n period = index.to_period(freq="ms")\n assert 2 == len(period)\n assert period[0] == Period("2007-01-01 10:11:12.123Z", "ms")\n assert period[1] == Period("2007-01-01 10:11:13.789Z", "ms")\n\n def test_to_period_microsecond(self):\n index = DatetimeIndex(\n [\n Timestamp("2007-01-01 10:11:12.123456Z"),\n Timestamp("2007-01-01 10:11:13.789123Z"),\n ]\n )\n\n with tm.assert_produces_warning(UserWarning):\n # warning that timezone info will be lost\n period = index.to_period(freq="us")\n assert 2 == len(period)\n assert period[0] == Period("2007-01-01 10:11:12.123456Z", "us")\n assert period[1] == Period("2007-01-01 10:11:13.789123Z", "us")\n\n @pytest.mark.parametrize(\n "tz",\n ["US/Eastern", pytz.utc, tzlocal(), "dateutil/US/Eastern", dateutil.tz.tzutc()],\n )\n def test_to_period_tz(self, tz):\n ts = date_range("1/1/2000", "2/1/2000", tz=tz)\n\n with tm.assert_produces_warning(UserWarning):\n # GH#21333 warning that timezone info will be lost\n # filter warning about freq deprecation\n\n result = ts.to_period()[0]\n expected = ts[0].to_period(ts.freq)\n\n assert result == expected\n\n expected = date_range("1/1/2000", "2/1/2000").to_period()\n\n with tm.assert_produces_warning(UserWarning):\n # GH#21333 warning that timezone info will be lost\n result = ts.to_period(ts.freq)\n\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("tz", ["Etc/GMT-1", "Etc/GMT+1"])\n def test_to_period_tz_utc_offset_consistency(self, tz):\n # GH#22905\n ts = date_range("1/1/2000", "2/1/2000", tz="Etc/GMT-1")\n with tm.assert_produces_warning(UserWarning):\n result = ts.to_period()[0]\n expected = ts[0].to_period(ts.freq)\n assert result == expected\n\n def test_to_period_nofreq(self):\n idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-04"])\n msg = "You must pass a freq argument as current index has none."\n with pytest.raises(ValueError, match=msg):\n idx.to_period()\n\n idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"], freq="infer")\n assert idx.freqstr == "D"\n expected = PeriodIndex(["2000-01-01", "2000-01-02", "2000-01-03"], freq="D")\n tm.assert_index_equal(idx.to_period(), expected)\n\n # GH#7606\n idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"])\n assert idx.freqstr is None\n tm.assert_index_equal(idx.to_period(), expected)\n\n @pytest.mark.parametrize("freq", ["2BMS", "1SME-15"])\n def test_to_period_offsets_not_supported(self, freq):\n # GH#56243\n msg = f"{freq[1:]} is not supported as period frequency"\n ts = date_range("1/1/2012", periods=4, freq=freq)\n with pytest.raises(ValueError, match=msg):\n ts.to_period()\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_to_period.py
test_to_period.py
Python
7,986
0.95
0.075556
0.05914
vue-tools
199
2023-12-09T01:37:51.315132
Apache-2.0
true
86aa315e26da2f0eb848fba3d45e8765
from datetime import (\n datetime,\n timezone,\n)\n\nimport dateutil.parser\nimport dateutil.tz\nfrom dateutil.tz import tzlocal\nimport numpy as np\n\nfrom pandas import (\n DatetimeIndex,\n date_range,\n to_datetime,\n)\nimport pandas._testing as tm\nfrom pandas.tests.indexes.datetimes.test_timezones import FixedOffset\n\nfixed_off = FixedOffset(-420, "-07:00")\n\n\nclass TestToPyDatetime:\n def test_dti_to_pydatetime(self):\n dt = dateutil.parser.parse("2012-06-13T01:39:00Z")\n dt = dt.replace(tzinfo=tzlocal())\n\n arr = np.array([dt], dtype=object)\n\n result = to_datetime(arr, utc=True)\n assert result.tz is timezone.utc\n\n rng = date_range("2012-11-03 03:00", "2012-11-05 03:00", tz=tzlocal())\n arr = rng.to_pydatetime()\n result = to_datetime(arr, utc=True)\n assert result.tz is timezone.utc\n\n def test_dti_to_pydatetime_fizedtz(self):\n dates = np.array(\n [\n datetime(2000, 1, 1, tzinfo=fixed_off),\n datetime(2000, 1, 2, tzinfo=fixed_off),\n datetime(2000, 1, 3, tzinfo=fixed_off),\n ]\n )\n dti = DatetimeIndex(dates)\n\n result = dti.to_pydatetime()\n tm.assert_numpy_array_equal(dates, result)\n\n result = dti._mpl_repr()\n tm.assert_numpy_array_equal(dates, result)\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_to_pydatetime.py
test_to_pydatetime.py
Python
1,345
0.85
0.058824
0
vue-tools
675
2023-11-24T21:27:56.015591
Apache-2.0
true
710868a6b9cacfb19e793240a08fc1c9
import numpy as np\n\nfrom pandas import (\n DatetimeIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestToSeries:\n def test_to_series(self):\n naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B")\n idx = naive.tz_localize("US/Pacific")\n\n expected = Series(np.array(idx.tolist(), dtype="object"), name="B")\n result = idx.to_series(index=[0, 1])\n assert expected.dtype == idx.dtype\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_to_series.py
test_to_series.py
Python
493
0.85
0.111111
0
node-utils
514
2025-07-02T07:03:52.770630
BSD-3-Clause
true
e159b2822f2fb35bb9e6aaca5b9105d5
from datetime import datetime\n\nimport dateutil.tz\nfrom dateutil.tz import gettz\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import timezones\n\nfrom pandas import (\n DatetimeIndex,\n Index,\n NaT,\n Timestamp,\n date_range,\n offsets,\n)\nimport pandas._testing as tm\n\n\nclass TestTZConvert:\n def test_tz_convert_nat(self):\n # GH#5546\n dates = [NaT]\n idx = DatetimeIndex(dates)\n idx = idx.tz_localize("US/Pacific")\n tm.assert_index_equal(idx, DatetimeIndex(dates, tz="US/Pacific"))\n idx = idx.tz_convert("US/Eastern")\n tm.assert_index_equal(idx, DatetimeIndex(dates, tz="US/Eastern"))\n idx = idx.tz_convert("UTC")\n tm.assert_index_equal(idx, DatetimeIndex(dates, tz="UTC"))\n\n dates = ["2010-12-01 00:00", "2010-12-02 00:00", NaT]\n idx = DatetimeIndex(dates)\n idx = idx.tz_localize("US/Pacific")\n tm.assert_index_equal(idx, DatetimeIndex(dates, tz="US/Pacific"))\n idx = idx.tz_convert("US/Eastern")\n expected = ["2010-12-01 03:00", "2010-12-02 03:00", NaT]\n tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Eastern"))\n\n idx = idx + offsets.Hour(5)\n expected = ["2010-12-01 08:00", "2010-12-02 08:00", NaT]\n tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Eastern"))\n idx = idx.tz_convert("US/Pacific")\n expected = ["2010-12-01 05:00", "2010-12-02 05:00", NaT]\n tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Pacific"))\n\n idx = idx + np.timedelta64(3, "h")\n expected = ["2010-12-01 08:00", "2010-12-02 08:00", NaT]\n tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Pacific"))\n\n idx = idx.tz_convert("US/Eastern")\n expected = ["2010-12-01 11:00", "2010-12-02 11:00", NaT]\n tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Eastern"))\n\n @pytest.mark.parametrize("prefix", ["", "dateutil/"])\n def test_dti_tz_convert_compat_timestamp(self, prefix):\n strdates = ["1/1/2012", "3/1/2012", "4/1/2012"]\n idx = DatetimeIndex(strdates, tz=prefix + "US/Eastern")\n\n conv = idx[0].tz_convert(prefix + "US/Pacific")\n expected = idx.tz_convert(prefix + "US/Pacific")[0]\n\n assert conv == expected\n\n def test_dti_tz_convert_hour_overflow_dst(self):\n # Regression test for GH#13306\n\n # sorted case US/Eastern -> UTC\n ts = ["2008-05-12 09:50:00", "2008-12-12 09:50:35", "2009-05-12 09:50:32"]\n tt = DatetimeIndex(ts).tz_localize("US/Eastern")\n ut = tt.tz_convert("UTC")\n expected = Index([13, 14, 13], dtype=np.int32)\n tm.assert_index_equal(ut.hour, expected)\n\n # sorted case UTC -> US/Eastern\n ts = ["2008-05-12 13:50:00", "2008-12-12 14:50:35", "2009-05-12 13:50:32"]\n tt = DatetimeIndex(ts).tz_localize("UTC")\n ut = tt.tz_convert("US/Eastern")\n expected = Index([9, 9, 9], dtype=np.int32)\n tm.assert_index_equal(ut.hour, expected)\n\n # unsorted case US/Eastern -> UTC\n ts = ["2008-05-12 09:50:00", "2008-12-12 09:50:35", "2008-05-12 09:50:32"]\n tt = DatetimeIndex(ts).tz_localize("US/Eastern")\n ut = tt.tz_convert("UTC")\n expected = Index([13, 14, 13], dtype=np.int32)\n tm.assert_index_equal(ut.hour, expected)\n\n # unsorted case UTC -> US/Eastern\n ts = ["2008-05-12 13:50:00", "2008-12-12 14:50:35", "2008-05-12 13:50:32"]\n tt = DatetimeIndex(ts).tz_localize("UTC")\n ut = tt.tz_convert("US/Eastern")\n expected = Index([9, 9, 9], dtype=np.int32)\n tm.assert_index_equal(ut.hour, expected)\n\n @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"])\n def test_dti_tz_convert_hour_overflow_dst_timestamps(self, tz):\n # Regression test for GH#13306\n\n # sorted case US/Eastern -> UTC\n ts = [\n Timestamp("2008-05-12 09:50:00", tz=tz),\n Timestamp("2008-12-12 09:50:35", tz=tz),\n Timestamp("2009-05-12 09:50:32", tz=tz),\n ]\n tt = DatetimeIndex(ts)\n ut = tt.tz_convert("UTC")\n expected = Index([13, 14, 13], dtype=np.int32)\n tm.assert_index_equal(ut.hour, expected)\n\n # sorted case UTC -> US/Eastern\n ts = [\n Timestamp("2008-05-12 13:50:00", tz="UTC"),\n Timestamp("2008-12-12 14:50:35", tz="UTC"),\n Timestamp("2009-05-12 13:50:32", tz="UTC"),\n ]\n tt = DatetimeIndex(ts)\n ut = tt.tz_convert("US/Eastern")\n expected = Index([9, 9, 9], dtype=np.int32)\n tm.assert_index_equal(ut.hour, expected)\n\n # unsorted case US/Eastern -> UTC\n ts = [\n Timestamp("2008-05-12 09:50:00", tz=tz),\n Timestamp("2008-12-12 09:50:35", tz=tz),\n Timestamp("2008-05-12 09:50:32", tz=tz),\n ]\n tt = DatetimeIndex(ts)\n ut = tt.tz_convert("UTC")\n expected = Index([13, 14, 13], dtype=np.int32)\n tm.assert_index_equal(ut.hour, expected)\n\n # unsorted case UTC -> US/Eastern\n ts = [\n Timestamp("2008-05-12 13:50:00", tz="UTC"),\n Timestamp("2008-12-12 14:50:35", tz="UTC"),\n Timestamp("2008-05-12 13:50:32", tz="UTC"),\n ]\n tt = DatetimeIndex(ts)\n ut = tt.tz_convert("US/Eastern")\n expected = Index([9, 9, 9], dtype=np.int32)\n tm.assert_index_equal(ut.hour, expected)\n\n @pytest.mark.parametrize("freq, n", [("h", 1), ("min", 60), ("s", 3600)])\n def test_dti_tz_convert_trans_pos_plus_1__bug(self, freq, n):\n # Regression test for tslib.tz_convert(vals, tz1, tz2).\n # See GH#4496 for details.\n idx = date_range(datetime(2011, 3, 26, 23), datetime(2011, 3, 27, 1), freq=freq)\n idx = idx.tz_localize("UTC")\n idx = idx.tz_convert("Europe/Moscow")\n\n expected = np.repeat(np.array([3, 4, 5]), np.array([n, n, 1]))\n tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))\n\n def test_dti_tz_convert_dst(self):\n for freq, n in [("h", 1), ("min", 60), ("s", 3600)]:\n # Start DST\n idx = date_range(\n "2014-03-08 23:00", "2014-03-09 09:00", freq=freq, tz="UTC"\n )\n idx = idx.tz_convert("US/Eastern")\n expected = np.repeat(\n np.array([18, 19, 20, 21, 22, 23, 0, 1, 3, 4, 5]),\n np.array([n, n, n, n, n, n, n, n, n, n, 1]),\n )\n tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))\n\n idx = date_range(\n "2014-03-08 18:00", "2014-03-09 05:00", freq=freq, tz="US/Eastern"\n )\n idx = idx.tz_convert("UTC")\n expected = np.repeat(\n np.array([23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),\n np.array([n, n, n, n, n, n, n, n, n, n, 1]),\n )\n tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))\n\n # End DST\n idx = date_range(\n "2014-11-01 23:00", "2014-11-02 09:00", freq=freq, tz="UTC"\n )\n idx = idx.tz_convert("US/Eastern")\n expected = np.repeat(\n np.array([19, 20, 21, 22, 23, 0, 1, 1, 2, 3, 4]),\n np.array([n, n, n, n, n, n, n, n, n, n, 1]),\n )\n tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))\n\n idx = date_range(\n "2014-11-01 18:00", "2014-11-02 05:00", freq=freq, tz="US/Eastern"\n )\n idx = idx.tz_convert("UTC")\n expected = np.repeat(\n np.array([22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),\n np.array([n, n, n, n, n, n, n, n, n, n, n, n, 1]),\n )\n tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))\n\n # daily\n # Start DST\n idx = date_range("2014-03-08 00:00", "2014-03-09 00:00", freq="D", tz="UTC")\n idx = idx.tz_convert("US/Eastern")\n tm.assert_index_equal(idx.hour, Index([19, 19], dtype=np.int32))\n\n idx = date_range(\n "2014-03-08 00:00", "2014-03-09 00:00", freq="D", tz="US/Eastern"\n )\n idx = idx.tz_convert("UTC")\n tm.assert_index_equal(idx.hour, Index([5, 5], dtype=np.int32))\n\n # End DST\n idx = date_range("2014-11-01 00:00", "2014-11-02 00:00", freq="D", tz="UTC")\n idx = idx.tz_convert("US/Eastern")\n tm.assert_index_equal(idx.hour, Index([20, 20], dtype=np.int32))\n\n idx = date_range(\n "2014-11-01 00:00", "2014-11-02 000:00", freq="D", tz="US/Eastern"\n )\n idx = idx.tz_convert("UTC")\n tm.assert_index_equal(idx.hour, Index([4, 4], dtype=np.int32))\n\n def test_tz_convert_roundtrip(self, tz_aware_fixture):\n tz = tz_aware_fixture\n idx1 = date_range(start="2014-01-01", end="2014-12-31", freq="ME", tz="UTC")\n exp1 = date_range(start="2014-01-01", end="2014-12-31", freq="ME")\n\n idx2 = date_range(start="2014-01-01", end="2014-12-31", freq="D", tz="UTC")\n exp2 = date_range(start="2014-01-01", end="2014-12-31", freq="D")\n\n idx3 = date_range(start="2014-01-01", end="2014-03-01", freq="h", tz="UTC")\n exp3 = date_range(start="2014-01-01", end="2014-03-01", freq="h")\n\n idx4 = date_range(start="2014-08-01", end="2014-10-31", freq="min", tz="UTC")\n exp4 = date_range(start="2014-08-01", end="2014-10-31", freq="min")\n\n for idx, expected in [(idx1, exp1), (idx2, exp2), (idx3, exp3), (idx4, exp4)]:\n converted = idx.tz_convert(tz)\n reset = converted.tz_convert(None)\n tm.assert_index_equal(reset, expected)\n assert reset.tzinfo is None\n expected = converted.tz_convert("UTC").tz_localize(None)\n expected = expected._with_freq("infer")\n tm.assert_index_equal(reset, expected)\n\n def test_dti_tz_convert_tzlocal(self):\n # GH#13583\n # tz_convert doesn't affect to internal\n dti = date_range(start="2001-01-01", end="2001-03-01", tz="UTC")\n dti2 = dti.tz_convert(dateutil.tz.tzlocal())\n tm.assert_numpy_array_equal(dti2.asi8, dti.asi8)\n\n dti = date_range(start="2001-01-01", end="2001-03-01", tz=dateutil.tz.tzlocal())\n dti2 = dti.tz_convert(None)\n tm.assert_numpy_array_equal(dti2.asi8, dti.asi8)\n\n @pytest.mark.parametrize(\n "tz",\n [\n "US/Eastern",\n "dateutil/US/Eastern",\n pytz.timezone("US/Eastern"),\n gettz("US/Eastern"),\n ],\n )\n def test_dti_tz_convert_utc_to_local_no_modify(self, tz):\n rng = date_range("3/11/2012", "3/12/2012", freq="h", tz="utc")\n rng_eastern = rng.tz_convert(tz)\n\n # Values are unmodified\n tm.assert_numpy_array_equal(rng.asi8, rng_eastern.asi8)\n\n assert timezones.tz_compare(rng_eastern.tz, timezones.maybe_get_tz(tz))\n\n @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])\n def test_tz_convert_unsorted(self, tzstr):\n dr = date_range("2012-03-09", freq="h", periods=100, tz="utc")\n dr = dr.tz_convert(tzstr)\n\n result = dr[::-1].hour\n exp = dr.hour[::-1]\n tm.assert_almost_equal(result, exp)\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_tz_convert.py
test_tz_convert.py
Python
11,295
0.95
0.060071
0.087866
vue-tools
961
2025-05-04T06:51:08.660299
MIT
true
d9470f315f06edfb25b449cb5ae7e3d8
from datetime import (\n datetime,\n timedelta,\n)\n\nimport dateutil.tz\nfrom dateutil.tz import gettz\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas import (\n DatetimeIndex,\n Timestamp,\n bdate_range,\n date_range,\n offsets,\n to_datetime,\n)\nimport pandas._testing as tm\n\ntry:\n from zoneinfo import ZoneInfo\nexcept ImportError:\n # Cannot assign to a type [misc]\n ZoneInfo = None # type: ignore[misc, assignment]\n\n\neasts = [pytz.timezone("US/Eastern"), gettz("US/Eastern")]\nif ZoneInfo is not None:\n try:\n tz = ZoneInfo("US/Eastern")\n except KeyError:\n # no tzdata\n pass\n else:\n easts.append(tz)\n\n\nclass TestTZLocalize:\n def test_tz_localize_invalidates_freq(self):\n # we only preserve freq in unambiguous cases\n\n # if localized to US/Eastern, this crosses a DST transition\n dti = date_range("2014-03-08 23:00", "2014-03-09 09:00", freq="h")\n assert dti.freq == "h"\n\n result = dti.tz_localize(None) # no-op\n assert result.freq == "h"\n\n result = dti.tz_localize("UTC") # unambiguous freq preservation\n assert result.freq == "h"\n\n result = dti.tz_localize("US/Eastern", nonexistent="shift_forward")\n assert result.freq is None\n assert result.inferred_freq is None # i.e. we are not _too_ strict here\n\n # Case where we _can_ keep freq because we're length==1\n dti2 = dti[:1]\n result = dti2.tz_localize("US/Eastern")\n assert result.freq == "h"\n\n def test_tz_localize_utc_copies(self, utc_fixture):\n # GH#46460\n times = ["2015-03-08 01:00", "2015-03-08 02:00", "2015-03-08 03:00"]\n index = DatetimeIndex(times)\n\n res = index.tz_localize(utc_fixture)\n assert not tm.shares_memory(res, index)\n\n res2 = index._data.tz_localize(utc_fixture)\n assert not tm.shares_memory(index._data, res2)\n\n def test_dti_tz_localize_nonexistent_raise_coerce(self):\n # GH#13057\n times = ["2015-03-08 01:00", "2015-03-08 02:00", "2015-03-08 03:00"]\n index = DatetimeIndex(times)\n tz = "US/Eastern"\n with pytest.raises(pytz.NonExistentTimeError, match="|".join(times)):\n index.tz_localize(tz=tz)\n\n with pytest.raises(pytz.NonExistentTimeError, match="|".join(times)):\n index.tz_localize(tz=tz, nonexistent="raise")\n\n result = index.tz_localize(tz=tz, nonexistent="NaT")\n test_times = ["2015-03-08 01:00-05:00", "NaT", "2015-03-08 03:00-04:00"]\n dti = to_datetime(test_times, utc=True)\n expected = dti.tz_convert("US/Eastern")\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("tz", easts)\n def test_dti_tz_localize_ambiguous_infer(self, tz):\n # November 6, 2011, fall back, repeat 2 AM hour\n # With no repeated hours, we cannot infer the transition\n dr = date_range(datetime(2011, 11, 6, 0), periods=5, freq=offsets.Hour())\n with pytest.raises(pytz.AmbiguousTimeError, match="Cannot infer dst time"):\n dr.tz_localize(tz)\n\n @pytest.mark.parametrize("tz", easts)\n def test_dti_tz_localize_ambiguous_infer2(self, tz, unit):\n # With repeated hours, we can infer the transition\n dr = date_range(\n datetime(2011, 11, 6, 0), periods=5, freq=offsets.Hour(), tz=tz, unit=unit\n )\n times = [\n "11/06/2011 00:00",\n "11/06/2011 01:00",\n "11/06/2011 01:00",\n "11/06/2011 02:00",\n "11/06/2011 03:00",\n ]\n di = DatetimeIndex(times).as_unit(unit)\n result = di.tz_localize(tz, ambiguous="infer")\n expected = dr._with_freq(None)\n tm.assert_index_equal(result, expected)\n result2 = DatetimeIndex(times, tz=tz, ambiguous="infer").as_unit(unit)\n tm.assert_index_equal(result2, expected)\n\n @pytest.mark.parametrize("tz", easts)\n def test_dti_tz_localize_ambiguous_infer3(self, tz):\n # When there is no dst transition, nothing special happens\n dr = date_range(datetime(2011, 6, 1, 0), periods=10, freq=offsets.Hour())\n localized = dr.tz_localize(tz)\n localized_infer = dr.tz_localize(tz, ambiguous="infer")\n tm.assert_index_equal(localized, localized_infer)\n\n @pytest.mark.parametrize("tz", easts)\n def test_dti_tz_localize_ambiguous_times(self, tz):\n # March 13, 2011, spring forward, skip from 2 AM to 3 AM\n dr = date_range(datetime(2011, 3, 13, 1, 30), periods=3, freq=offsets.Hour())\n with pytest.raises(pytz.NonExistentTimeError, match="2011-03-13 02:30:00"):\n dr.tz_localize(tz)\n\n # after dst transition, it works\n dr = date_range(\n datetime(2011, 3, 13, 3, 30), periods=3, freq=offsets.Hour(), tz=tz\n )\n\n # November 6, 2011, fall back, repeat 2 AM hour\n dr = date_range(datetime(2011, 11, 6, 1, 30), periods=3, freq=offsets.Hour())\n with pytest.raises(pytz.AmbiguousTimeError, match="Cannot infer dst time"):\n dr.tz_localize(tz)\n\n # UTC is OK\n dr = date_range(\n datetime(2011, 3, 13), periods=48, freq=offsets.Minute(30), tz=pytz.utc\n )\n\n @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])\n def test_dti_tz_localize_pass_dates_to_utc(self, tzstr):\n strdates = ["1/1/2012", "3/1/2012", "4/1/2012"]\n\n idx = DatetimeIndex(strdates)\n conv = idx.tz_localize(tzstr)\n\n fromdates = DatetimeIndex(strdates, tz=tzstr)\n\n assert conv.tz == fromdates.tz\n tm.assert_numpy_array_equal(conv.values, fromdates.values)\n\n @pytest.mark.parametrize("prefix", ["", "dateutil/"])\n def test_dti_tz_localize(self, prefix):\n tzstr = prefix + "US/Eastern"\n dti = date_range(start="1/1/2005", end="1/1/2005 0:00:30.256", freq="ms")\n dti2 = dti.tz_localize(tzstr)\n\n dti_utc = date_range(\n start="1/1/2005 05:00", end="1/1/2005 5:00:30.256", freq="ms", tz="utc"\n )\n\n tm.assert_numpy_array_equal(dti2.values, dti_utc.values)\n\n dti3 = dti2.tz_convert(prefix + "US/Pacific")\n tm.assert_numpy_array_equal(dti3.values, dti_utc.values)\n\n dti = date_range(start="11/6/2011 1:59", end="11/6/2011 2:00", freq="ms")\n with pytest.raises(pytz.AmbiguousTimeError, match="Cannot infer dst time"):\n dti.tz_localize(tzstr)\n\n dti = date_range(start="3/13/2011 1:59", end="3/13/2011 2:00", freq="ms")\n with pytest.raises(pytz.NonExistentTimeError, match="2011-03-13 02:00:00"):\n dti.tz_localize(tzstr)\n\n @pytest.mark.parametrize(\n "tz",\n [\n "US/Eastern",\n "dateutil/US/Eastern",\n pytz.timezone("US/Eastern"),\n gettz("US/Eastern"),\n ],\n )\n def test_dti_tz_localize_utc_conversion(self, tz):\n # Localizing to time zone should:\n # 1) check for DST ambiguities\n # 2) convert to UTC\n\n rng = date_range("3/10/2012", "3/11/2012", freq="30min")\n\n converted = rng.tz_localize(tz)\n expected_naive = rng + offsets.Hour(5)\n tm.assert_numpy_array_equal(converted.asi8, expected_naive.asi8)\n\n # DST ambiguity, this should fail\n rng = date_range("3/11/2012", "3/12/2012", freq="30min")\n # Is this really how it should fail??\n with pytest.raises(pytz.NonExistentTimeError, match="2012-03-11 02:00:00"):\n rng.tz_localize(tz)\n\n def test_dti_tz_localize_roundtrip(self, tz_aware_fixture):\n # note: this tz tests that a tz-naive index can be localized\n # and de-localized successfully, when there are no DST transitions\n # in the range.\n idx = date_range(start="2014-06-01", end="2014-08-30", freq="15min")\n tz = tz_aware_fixture\n localized = idx.tz_localize(tz)\n # can't localize a tz-aware object\n with pytest.raises(\n TypeError, match="Already tz-aware, use tz_convert to convert"\n ):\n localized.tz_localize(tz)\n reset = localized.tz_localize(None)\n assert reset.tzinfo is None\n expected = idx._with_freq(None)\n tm.assert_index_equal(reset, expected)\n\n def test_dti_tz_localize_naive(self):\n rng = date_range("1/1/2011", periods=100, freq="h")\n\n conv = rng.tz_localize("US/Pacific")\n exp = date_range("1/1/2011", periods=100, freq="h", tz="US/Pacific")\n\n tm.assert_index_equal(conv, exp._with_freq(None))\n\n def test_dti_tz_localize_tzlocal(self):\n # GH#13583\n offset = dateutil.tz.tzlocal().utcoffset(datetime(2011, 1, 1))\n offset = int(offset.total_seconds() * 1000000000)\n\n dti = date_range(start="2001-01-01", end="2001-03-01")\n dti2 = dti.tz_localize(dateutil.tz.tzlocal())\n tm.assert_numpy_array_equal(dti2.asi8 + offset, dti.asi8)\n\n dti = date_range(start="2001-01-01", end="2001-03-01", tz=dateutil.tz.tzlocal())\n dti2 = dti.tz_localize(None)\n tm.assert_numpy_array_equal(dti2.asi8 - offset, dti.asi8)\n\n @pytest.mark.parametrize("tz", easts)\n def test_dti_tz_localize_ambiguous_nat(self, tz):\n times = [\n "11/06/2011 00:00",\n "11/06/2011 01:00",\n "11/06/2011 01:00",\n "11/06/2011 02:00",\n "11/06/2011 03:00",\n ]\n di = DatetimeIndex(times)\n localized = di.tz_localize(tz, ambiguous="NaT")\n\n times = [\n "11/06/2011 00:00",\n np.nan,\n np.nan,\n "11/06/2011 02:00",\n "11/06/2011 03:00",\n ]\n di_test = DatetimeIndex(times, tz="US/Eastern")\n\n # left dtype is datetime64[ns, US/Eastern]\n # right is datetime64[ns, tzfile('/usr/share/zoneinfo/US/Eastern')]\n tm.assert_numpy_array_equal(di_test.values, localized.values)\n\n @pytest.mark.parametrize("tz", easts)\n def test_dti_tz_localize_ambiguous_flags(self, tz, unit):\n # November 6, 2011, fall back, repeat 2 AM hour\n\n # Pass in flags to determine right dst transition\n dr = date_range(\n datetime(2011, 11, 6, 0), periods=5, freq=offsets.Hour(), tz=tz, unit=unit\n )\n times = [\n "11/06/2011 00:00",\n "11/06/2011 01:00",\n "11/06/2011 01:00",\n "11/06/2011 02:00",\n "11/06/2011 03:00",\n ]\n\n # Test tz_localize\n di = DatetimeIndex(times).as_unit(unit)\n is_dst = [1, 1, 0, 0, 0]\n localized = di.tz_localize(tz, ambiguous=is_dst)\n expected = dr._with_freq(None)\n tm.assert_index_equal(expected, localized)\n\n result = DatetimeIndex(times, tz=tz, ambiguous=is_dst).as_unit(unit)\n tm.assert_index_equal(result, expected)\n\n localized = di.tz_localize(tz, ambiguous=np.array(is_dst))\n tm.assert_index_equal(dr, localized)\n\n localized = di.tz_localize(tz, ambiguous=np.array(is_dst).astype("bool"))\n tm.assert_index_equal(dr, localized)\n\n # Test constructor\n localized = DatetimeIndex(times, tz=tz, ambiguous=is_dst).as_unit(unit)\n tm.assert_index_equal(dr, localized)\n\n # Test duplicate times where inferring the dst fails\n times += times\n di = DatetimeIndex(times).as_unit(unit)\n\n # When the sizes are incompatible, make sure error is raised\n msg = "Length of ambiguous bool-array must be the same size as vals"\n with pytest.raises(Exception, match=msg):\n di.tz_localize(tz, ambiguous=is_dst)\n\n # When sizes are compatible and there are repeats ('infer' won't work)\n is_dst = np.hstack((is_dst, is_dst))\n localized = di.tz_localize(tz, ambiguous=is_dst)\n dr = dr.append(dr)\n tm.assert_index_equal(dr, localized)\n\n @pytest.mark.parametrize("tz", easts)\n def test_dti_tz_localize_ambiguous_flags2(self, tz, unit):\n # When there is no dst transition, nothing special happens\n dr = date_range(datetime(2011, 6, 1, 0), periods=10, freq=offsets.Hour())\n is_dst = np.array([1] * 10)\n localized = dr.tz_localize(tz)\n localized_is_dst = dr.tz_localize(tz, ambiguous=is_dst)\n tm.assert_index_equal(localized, localized_is_dst)\n\n def test_dti_tz_localize_bdate_range(self):\n dr = bdate_range("1/1/2009", "1/1/2010")\n dr_utc = bdate_range("1/1/2009", "1/1/2010", tz=pytz.utc)\n localized = dr.tz_localize(pytz.utc)\n tm.assert_index_equal(dr_utc, localized)\n\n @pytest.mark.parametrize(\n "start_ts, tz, end_ts, shift",\n [\n ["2015-03-29 02:20:00", "Europe/Warsaw", "2015-03-29 03:00:00", "forward"],\n [\n "2015-03-29 02:20:00",\n "Europe/Warsaw",\n "2015-03-29 01:59:59.999999999",\n "backward",\n ],\n [\n "2015-03-29 02:20:00",\n "Europe/Warsaw",\n "2015-03-29 03:20:00",\n timedelta(hours=1),\n ],\n [\n "2015-03-29 02:20:00",\n "Europe/Warsaw",\n "2015-03-29 01:20:00",\n timedelta(hours=-1),\n ],\n ["2018-03-11 02:33:00", "US/Pacific", "2018-03-11 03:00:00", "forward"],\n [\n "2018-03-11 02:33:00",\n "US/Pacific",\n "2018-03-11 01:59:59.999999999",\n "backward",\n ],\n [\n "2018-03-11 02:33:00",\n "US/Pacific",\n "2018-03-11 03:33:00",\n timedelta(hours=1),\n ],\n [\n "2018-03-11 02:33:00",\n "US/Pacific",\n "2018-03-11 01:33:00",\n timedelta(hours=-1),\n ],\n ],\n )\n @pytest.mark.parametrize("tz_type", ["", "dateutil/"])\n def test_dti_tz_localize_nonexistent_shift(\n self, start_ts, tz, end_ts, shift, tz_type, unit\n ):\n # GH#8917\n tz = tz_type + tz\n if isinstance(shift, str):\n shift = "shift_" + shift\n dti = DatetimeIndex([Timestamp(start_ts)]).as_unit(unit)\n result = dti.tz_localize(tz, nonexistent=shift)\n expected = DatetimeIndex([Timestamp(end_ts)]).tz_localize(tz).as_unit(unit)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("offset", [-1, 1])\n def test_dti_tz_localize_nonexistent_shift_invalid(self, offset, warsaw):\n # GH#8917\n tz = warsaw\n dti = DatetimeIndex([Timestamp("2015-03-29 02:20:00")])\n msg = "The provided timedelta will relocalize on a nonexistent time"\n with pytest.raises(ValueError, match=msg):\n dti.tz_localize(tz, nonexistent=timedelta(seconds=offset))\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_tz_localize.py
test_tz_localize.py
Python
14,830
0.95
0.064677
0.109145
node-utils
502
2025-03-02T08:51:22.255758
Apache-2.0
true
ba856f0da53ebfbfa11a5b635669e73c
from datetime import (\n datetime,\n timedelta,\n)\n\nfrom pandas import (\n DatetimeIndex,\n NaT,\n Timestamp,\n)\nimport pandas._testing as tm\n\n\ndef test_unique(tz_naive_fixture):\n idx = DatetimeIndex(["2017"] * 2, tz=tz_naive_fixture)\n expected = idx[:1]\n\n result = idx.unique()\n tm.assert_index_equal(result, expected)\n # GH#21737\n # Ensure the underlying data is consistent\n assert result[0] == expected[0]\n\n\ndef test_index_unique(rand_series_with_duplicate_datetimeindex):\n dups = rand_series_with_duplicate_datetimeindex\n index = dups.index\n\n uniques = index.unique()\n expected = DatetimeIndex(\n [\n datetime(2000, 1, 2),\n datetime(2000, 1, 3),\n datetime(2000, 1, 4),\n datetime(2000, 1, 5),\n ],\n dtype=index.dtype,\n )\n assert uniques.dtype == index.dtype # sanity\n tm.assert_index_equal(uniques, expected)\n assert index.nunique() == 4\n\n # GH#2563\n assert isinstance(uniques, DatetimeIndex)\n\n dups_local = index.tz_localize("US/Eastern")\n dups_local.name = "foo"\n result = dups_local.unique()\n expected = DatetimeIndex(expected, name="foo")\n expected = expected.tz_localize("US/Eastern")\n assert result.tz is not None\n assert result.name == "foo"\n tm.assert_index_equal(result, expected)\n\n\ndef test_index_unique2():\n # NaT, note this is excluded\n arr = [1370745748 + t for t in range(20)] + [NaT._value]\n idx = DatetimeIndex(arr * 3)\n tm.assert_index_equal(idx.unique(), DatetimeIndex(arr))\n assert idx.nunique() == 20\n assert idx.nunique(dropna=False) == 21\n\n\ndef test_index_unique3():\n arr = [\n Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)\n ] + [NaT]\n idx = DatetimeIndex(arr * 3)\n tm.assert_index_equal(idx.unique(), DatetimeIndex(arr))\n assert idx.nunique() == 20\n assert idx.nunique(dropna=False) == 21\n\n\ndef test_is_unique_monotonic(rand_series_with_duplicate_datetimeindex):\n index = rand_series_with_duplicate_datetimeindex.index\n assert not index.is_unique\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\test_unique.py
test_unique.py
Python
2,096
0.95
0.090909
0.064516
vue-tools
779
2025-02-21T00:33:44.251836
Apache-2.0
true
a597494afecf0d99a3e209c24b81ea67
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_asof.cpython-313.pyc
test_asof.cpython-313.pyc
Other
1,785
0.8
0
0.125
node-utils
821
2024-03-11T05:22:57.706668
GPL-3.0
true
19f7102df2990f19434f54bb9b18ceaa
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_astype.cpython-313.pyc
test_astype.cpython-313.pyc
Other
18,781
0.8
0
0
react-lib
262
2024-05-13T09:40:03.871778
Apache-2.0
true
9296b168a212bdffa22ccb4052a379dd
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_delete.cpython-313.pyc
test_delete.cpython-313.pyc
Other
5,928
0.8
0
0
awesome-app
996
2025-02-25T17:40:33.981022
MIT
true
b95dd5e60038faa71da23f897619107d
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_factorize.cpython-313.pyc
test_factorize.cpython-313.pyc
Other
7,106
0.8
0
0
python-kit
494
2023-10-29T01:23:53.894773
Apache-2.0
true
c7424867a2cc06162f36f164f9bcfbbf
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_fillna.cpython-313.pyc
test_fillna.cpython-313.pyc
Other
3,078
0.8
0
0
python-kit
563
2023-09-03T03:45:43.395446
MIT
true
58bbb0953c6b336d7c74c82dcc0f0aad
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_insert.cpython-313.pyc
test_insert.cpython-313.pyc
Other
12,459
0.8
0
0
python-kit
619
2024-05-30T09:13:26.317119
GPL-3.0
true
7abfff8fe55b803c487a0172819f3fbd
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_isocalendar.cpython-313.pyc
test_isocalendar.cpython-313.pyc
Other
1,462
0.8
0
0
awesome-app
561
2025-04-24T13:37:55.346402
GPL-3.0
true
d6a2b8b70739fb3d9e7119966f4e7ed2
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_map.cpython-313.pyc
test_map.cpython-313.pyc
Other
3,230
0.8
0
0
node-utils
702
2024-11-27T07:25:54.790640
Apache-2.0
true
3fb72bcac98b34a0bbc45ecfe312479b
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_normalize.cpython-313.pyc
test_normalize.cpython-313.pyc
Other
4,582
0.8
0
0
vue-tools
984
2024-08-04T23:48:51.471713
Apache-2.0
true
668e20e6dbe41bb96d158e180069e5c5
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_repeat.cpython-313.pyc
test_repeat.cpython-313.pyc
Other
4,104
0.8
0
0
react-lib
817
2024-04-18T20:03:21.915796
MIT
true
fc3023c7e311393ccba390f774b747da
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_resolution.cpython-313.pyc
test_resolution.cpython-313.pyc
Other
1,288
0.7
0
0
awesome-app
630
2024-05-29T10:08:17.625681
Apache-2.0
true
bb9f3bb564d97f05620bfb21efc64603
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_round.cpython-313.pyc
test_round.cpython-313.pyc
Other
10,375
0.8
0
0
node-utils
603
2023-10-24T10:11:18.598838
GPL-3.0
true
5b7e94dd0a3bcbe4f723e9a853410d19
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_shift.cpython-313.pyc
test_shift.cpython-313.pyc
Other
9,653
0.8
0
0
vue-tools
228
2024-11-21T07:40:51.383449
MIT
true
5f8dbc4d671186a88eb038c0e8830e2c
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_snap.cpython-313.pyc
test_snap.cpython-313.pyc
Other
2,064
0.8
0
0.041667
node-utils
884
2024-08-28T19:03:05.886571
GPL-3.0
true
629f5dadff30560a3dc15a80ded2c136
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_to_frame.cpython-313.pyc
test_to_frame.cpython-313.pyc
Other
1,768
0.8
0
0
react-lib
218
2024-06-27T11:50:54.187952
GPL-3.0
true
9b89d5ebc38bfb6a24aad1072aeb2e27
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_to_julian_date.cpython-313.pyc
test_to_julian_date.cpython-313.pyc
Other
3,384
0.7
0
0
python-kit
73
2025-01-27T14:34:02.802013
MIT
true
f77d2cd9e2903f4877ec1fa3d889ffc1
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_to_period.cpython-313.pyc
test_to_period.cpython-313.pyc
Other
12,579
0.8
0
0
vue-tools
681
2024-02-22T23:09:17.138674
MIT
true
b315c0862490a89099a686941beb7842
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_to_pydatetime.cpython-313.pyc
test_to_pydatetime.cpython-313.pyc
Other
2,540
0.8
0
0
awesome-app
117
2024-01-30T03:14:10.818588
GPL-3.0
true
98988941dab743c4404f2f224ed5d6c6
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_to_series.cpython-313.pyc
test_to_series.cpython-313.pyc
Other
1,326
0.7
0
0
react-lib
115
2024-02-08T19:00:53.891346
Apache-2.0
true
e888a216b60b14b29310ea870434e606
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_tz_convert.cpython-313.pyc
test_tz_convert.cpython-313.pyc
Other
15,013
0.8
0
0.047337
awesome-app
63
2024-07-01T13:05:28.485372
BSD-3-Clause
true
c311749faf380e6a2ab6a51b6b877a7a
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_tz_localize.cpython-313.pyc
test_tz_localize.cpython-313.pyc
Other
20,020
0.8
0
0.009132
node-utils
102
2023-11-12T06:45:28.444407
GPL-3.0
true
0efe939e5c85816ee1467f43122065e8
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\test_unique.cpython-313.pyc
test_unique.cpython-313.pyc
Other
3,650
0.8
0
0
react-lib
741
2025-05-05T22:15:01.138507
BSD-3-Clause
true
b1e247a7b5b5fc5c61375e39564cab94
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\methods\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
213
0.7
0
0
node-utils
436
2024-07-10T23:50:01.070938
Apache-2.0
true
a62c07aa18d4691a033356b4b9bbeaa5
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_arithmetic.cpython-313.pyc
test_arithmetic.cpython-313.pyc
Other
2,729
0.8
0
0
node-utils
704
2025-02-10T12:08:29.089995
MIT
true
88bdec20e6053a03410aae0ffa8b752d
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
56,520
0.6
0.00156
0.009494
vue-tools
660
2024-05-31T08:58:39.709472
GPL-3.0
true
37aee75fc4645f5adce0f90948969895
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_datetime.cpython-313.pyc
test_datetime.cpython-313.pyc
Other
10,824
0.95
0
0.007519
awesome-app
629
2024-12-28T20:27:10.531431
MIT
true
be0913150bc9061217eeb30a3fc80f66
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_date_range.cpython-313.pyc
test_date_range.cpython-313.pyc
Other
78,641
0.75
0.002186
0.008889
python-kit
86
2025-03-19T23:34:18.639747
BSD-3-Clause
true
1fc6315f3bafc282b381f2e1b87e4872
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_formats.cpython-313.pyc
test_formats.cpython-313.pyc
Other
17,111
0.8
0
0
awesome-app
277
2023-08-23T19:23:19.180046
MIT
true
dcecde730f930dc7d942954c9a0fbfd6
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_freq_attr.cpython-313.pyc
test_freq_attr.cpython-313.pyc
Other
2,896
0.8
0
0
awesome-app
770
2024-02-07T10:41:40.281205
MIT
true
ac1b92953500c9505865cdcbe6824830
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_indexing.cpython-313.pyc
test_indexing.cpython-313.pyc
Other
41,270
0.95
0
0
python-kit
290
2023-08-23T01:10:19.038569
GPL-3.0
true
c02e1b1c64436c74a9bb773697dfa809
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_iter.cpython-313.pyc
test_iter.cpython-313.pyc
Other
4,149
0.8
0
0
react-lib
494
2024-06-23T21:09:06.005603
BSD-3-Clause
true
20c76bc05947a4d25d272e037bab04f2
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_join.cpython-313.pyc
test_join.cpython-313.pyc
Other
8,235
0.8
0
0
vue-tools
723
2023-12-21T17:14:41.321326
Apache-2.0
true
b82947014c824cf61ed547ebf45523db
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_npfuncs.cpython-313.pyc
test_npfuncs.cpython-313.pyc
Other
1,063
0.8
0
0
awesome-app
32
2024-09-21T20:19:53.740709
BSD-3-Clause
true
2342746be8a1bfd8eee7f7f10a617595
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_ops.cpython-313.pyc
test_ops.cpython-313.pyc
Other
3,215
0.8
0
0
react-lib
72
2024-07-10T13:30:08.005713
MIT
true
2b100da48ae3ffeff5725c024b48a5ab
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_partial_slicing.cpython-313.pyc
test_partial_slicing.cpython-313.pyc
Other
22,774
0.95
0
0
python-kit
406
2024-06-27T00:01:12.034882
GPL-3.0
true
9765c7454b2bdc9b9844738beff35e12
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_pickle.cpython-313.pyc
test_pickle.cpython-313.pyc
Other
2,728
0.7
0
0
awesome-app
976
2025-05-22T16:38:45.856920
BSD-3-Clause
true
47b350d2449d10ba6eb1706a0cbe75b8
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_reindex.cpython-313.pyc
test_reindex.cpython-313.pyc
Other
2,976
0.8
0
0
awesome-app
455
2025-01-06T22:07:55.636461
MIT
true
c527a94a2829773553eadc275cc690a9
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_scalar_compat.cpython-313.pyc
test_scalar_compat.cpython-313.pyc
Other
17,109
0.8
0.007874
0.016
awesome-app
466
2025-05-30T04:59:09.143317
GPL-3.0
true
1d8771b47e68ba2e03d3b8b74cecb47f
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_setops.cpython-313.pyc
test_setops.cpython-313.pyc
Other
31,085
0.8
0
0.003906
node-utils
519
2023-08-18T14:20:56.874132
BSD-3-Clause
true
48674cd3f8c80c332bdeb79b379036ba
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\test_timezones.cpython-313.pyc
test_timezones.cpython-313.pyc
Other
12,079
0.8
0.007813
0.031746
react-lib
468
2023-09-27T07:27:48.663497
MIT
true
db04b6c5700a9b2df16c676d6a5d167b
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\datetimes\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
205
0.7
0
0
vue-tools
150
2023-10-01T03:41:45.694432
BSD-3-Clause
true
91743f4a51a14718469244f1af55bdff
import re\n\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import (\n CategoricalDtype,\n IntervalDtype,\n)\n\nfrom pandas import (\n CategoricalIndex,\n Index,\n IntervalIndex,\n NaT,\n Timedelta,\n Timestamp,\n interval_range,\n)\nimport pandas._testing as tm\n\n\nclass AstypeTests:\n """Tests common to IntervalIndex with any subtype"""\n\n def test_astype_idempotent(self, index):\n result = index.astype("interval")\n tm.assert_index_equal(result, index)\n\n result = index.astype(index.dtype)\n tm.assert_index_equal(result, index)\n\n def test_astype_object(self, index):\n result = index.astype(object)\n expected = Index(index.values, dtype="object")\n tm.assert_index_equal(result, expected)\n assert not result.equals(index)\n\n def test_astype_category(self, index):\n result = index.astype("category")\n expected = CategoricalIndex(index.values)\n tm.assert_index_equal(result, expected)\n\n result = index.astype(CategoricalDtype())\n tm.assert_index_equal(result, expected)\n\n # non-default params\n categories = index.dropna().unique().values[:-1]\n dtype = CategoricalDtype(categories=categories, ordered=True)\n result = index.astype(dtype)\n expected = CategoricalIndex(index.values, categories=categories, ordered=True)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "dtype",\n [\n "int64",\n "uint64",\n "float64",\n "complex128",\n "period[M]",\n "timedelta64",\n "timedelta64[ns]",\n "datetime64",\n "datetime64[ns]",\n "datetime64[ns, US/Eastern]",\n ],\n )\n def test_astype_cannot_cast(self, index, dtype):\n msg = "Cannot cast IntervalIndex to dtype"\n with pytest.raises(TypeError, match=msg):\n index.astype(dtype)\n\n def test_astype_invalid_dtype(self, index):\n msg = "data type [\"']fake_dtype[\"'] not understood"\n with pytest.raises(TypeError, match=msg):\n index.astype("fake_dtype")\n\n\nclass TestIntSubtype(AstypeTests):\n """Tests specific to IntervalIndex with integer-like subtype"""\n\n indexes = [\n IntervalIndex.from_breaks(np.arange(-10, 11, dtype="int64")),\n IntervalIndex.from_breaks(np.arange(100, dtype="uint64"), closed="left"),\n ]\n\n @pytest.fixture(params=indexes)\n def index(self, request):\n return request.param\n\n @pytest.mark.parametrize(\n "subtype", ["float64", "datetime64[ns]", "timedelta64[ns]"]\n )\n def test_subtype_conversion(self, index, subtype):\n dtype = IntervalDtype(subtype, index.closed)\n result = index.astype(dtype)\n expected = IntervalIndex.from_arrays(\n index.left.astype(subtype), index.right.astype(subtype), closed=index.closed\n )\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "subtype_start, subtype_end", [("int64", "uint64"), ("uint64", "int64")]\n )\n def test_subtype_integer(self, subtype_start, subtype_end):\n index = IntervalIndex.from_breaks(np.arange(100, dtype=subtype_start))\n dtype = IntervalDtype(subtype_end, index.closed)\n result = index.astype(dtype)\n expected = IntervalIndex.from_arrays(\n index.left.astype(subtype_end),\n index.right.astype(subtype_end),\n closed=index.closed,\n )\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.xfail(reason="GH#15832")\n def test_subtype_integer_errors(self):\n # int64 -> uint64 fails with negative values\n index = interval_range(-10, 10)\n dtype = IntervalDtype("uint64", "right")\n\n # Until we decide what the exception message _should_ be, we\n # assert something that it should _not_ be.\n # We should _not_ be getting a message suggesting that the -10\n # has been wrapped around to a large-positive integer\n msg = "^(?!(left side of interval must be <= right side))"\n with pytest.raises(ValueError, match=msg):\n index.astype(dtype)\n\n\nclass TestFloatSubtype(AstypeTests):\n """Tests specific to IntervalIndex with float subtype"""\n\n indexes = [\n interval_range(-10.0, 10.0, closed="neither"),\n IntervalIndex.from_arrays(\n [-1.5, np.nan, 0.0, 0.0, 1.5], [-0.5, np.nan, 1.0, 1.0, 3.0], closed="both"\n ),\n ]\n\n @pytest.fixture(params=indexes)\n def index(self, request):\n return request.param\n\n @pytest.mark.parametrize("subtype", ["int64", "uint64"])\n def test_subtype_integer(self, subtype):\n index = interval_range(0.0, 10.0)\n dtype = IntervalDtype(subtype, "right")\n result = index.astype(dtype)\n expected = IntervalIndex.from_arrays(\n index.left.astype(subtype), index.right.astype(subtype), closed=index.closed\n )\n tm.assert_index_equal(result, expected)\n\n # raises with NA\n msg = r"Cannot convert non-finite values \(NA or inf\) to integer"\n with pytest.raises(ValueError, match=msg):\n index.insert(0, np.nan).astype(dtype)\n\n @pytest.mark.parametrize("subtype", ["int64", "uint64"])\n def test_subtype_integer_with_non_integer_borders(self, subtype):\n index = interval_range(0.0, 3.0, freq=0.25)\n dtype = IntervalDtype(subtype, "right")\n result = index.astype(dtype)\n expected = IntervalIndex.from_arrays(\n index.left.astype(subtype), index.right.astype(subtype), closed=index.closed\n )\n tm.assert_index_equal(result, expected)\n\n def test_subtype_integer_errors(self):\n # float64 -> uint64 fails with negative values\n index = interval_range(-10.0, 10.0)\n dtype = IntervalDtype("uint64", "right")\n msg = re.escape(\n "Cannot convert interval[float64, right] to interval[uint64, right]; "\n "subtypes are incompatible"\n )\n with pytest.raises(TypeError, match=msg):\n index.astype(dtype)\n\n @pytest.mark.parametrize("subtype", ["datetime64[ns]", "timedelta64[ns]"])\n def test_subtype_datetimelike(self, index, subtype):\n dtype = IntervalDtype(subtype, "right")\n msg = "Cannot convert .* to .*; subtypes are incompatible"\n with pytest.raises(TypeError, match=msg):\n index.astype(dtype)\n\n @pytest.mark.filterwarnings(\n "ignore:invalid value encountered in cast:RuntimeWarning"\n )\n def test_astype_category(self, index):\n super().test_astype_category(index)\n\n\nclass TestDatetimelikeSubtype(AstypeTests):\n """Tests specific to IntervalIndex with datetime-like subtype"""\n\n indexes = [\n interval_range(Timestamp("2018-01-01"), periods=10, closed="neither"),\n interval_range(Timestamp("2018-01-01"), periods=10).insert(2, NaT),\n interval_range(Timestamp("2018-01-01", tz="US/Eastern"), periods=10),\n interval_range(Timedelta("0 days"), periods=10, closed="both"),\n interval_range(Timedelta("0 days"), periods=10).insert(2, NaT),\n ]\n\n @pytest.fixture(params=indexes)\n def index(self, request):\n return request.param\n\n @pytest.mark.parametrize("subtype", ["int64", "uint64"])\n def test_subtype_integer(self, index, subtype):\n dtype = IntervalDtype(subtype, "right")\n\n if subtype != "int64":\n msg = (\n r"Cannot convert interval\[(timedelta64|datetime64)\[ns.*\], .*\] "\n r"to interval\[uint64, .*\]"\n )\n with pytest.raises(TypeError, match=msg):\n index.astype(dtype)\n return\n\n result = index.astype(dtype)\n new_left = index.left.astype(subtype)\n new_right = index.right.astype(subtype)\n\n expected = IntervalIndex.from_arrays(new_left, new_right, closed=index.closed)\n tm.assert_index_equal(result, expected)\n\n def test_subtype_float(self, index):\n dtype = IntervalDtype("float64", "right")\n msg = "Cannot convert .* to .*; subtypes are incompatible"\n with pytest.raises(TypeError, match=msg):\n index.astype(dtype)\n\n def test_subtype_datetimelike(self):\n # datetime -> timedelta raises\n dtype = IntervalDtype("timedelta64[ns]", "right")\n msg = "Cannot convert .* to .*; subtypes are incompatible"\n\n index = interval_range(Timestamp("2018-01-01"), periods=10)\n with pytest.raises(TypeError, match=msg):\n index.astype(dtype)\n\n index = interval_range(Timestamp("2018-01-01", tz="CET"), periods=10)\n with pytest.raises(TypeError, match=msg):\n index.astype(dtype)\n\n # timedelta -> datetime raises\n dtype = IntervalDtype("datetime64[ns]", "right")\n index = interval_range(Timedelta("0 days"), periods=10)\n with pytest.raises(TypeError, match=msg):\n index.astype(dtype)\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_astype.py
test_astype.py
Python
9,002
0.95
0.094488
0.047619
react-lib
947
2023-10-16T12:22:50.970477
Apache-2.0
true
73f7c8c9d067710732fd30dc98dc659d
from functools import partial\n\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nfrom pandas.core.dtypes.common import is_unsigned_integer_dtype\nfrom pandas.core.dtypes.dtypes import IntervalDtype\n\nfrom pandas import (\n Categorical,\n CategoricalDtype,\n CategoricalIndex,\n Index,\n Interval,\n IntervalIndex,\n date_range,\n notna,\n period_range,\n timedelta_range,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import IntervalArray\nimport pandas.core.common as com\n\n\n@pytest.fixture(params=[None, "foo"])\ndef name(request):\n return request.param\n\n\nclass ConstructorTests:\n """\n Common tests for all variations of IntervalIndex construction. Input data\n to be supplied in breaks format, then converted by the subclass method\n get_kwargs_from_breaks to the expected format.\n """\n\n @pytest.fixture(\n params=[\n ([3, 14, 15, 92, 653], np.int64),\n (np.arange(10, dtype="int64"), np.int64),\n (Index(np.arange(-10, 11, dtype=np.int64)), np.int64),\n (Index(np.arange(10, 31, dtype=np.uint64)), np.uint64),\n (Index(np.arange(20, 30, 0.5), dtype=np.float64), np.float64),\n (date_range("20180101", periods=10), "<M8[ns]"),\n (\n date_range("20180101", periods=10, tz="US/Eastern"),\n "datetime64[ns, US/Eastern]",\n ),\n (timedelta_range("1 day", periods=10), "<m8[ns]"),\n ]\n )\n def breaks_and_expected_subtype(self, request):\n return request.param\n\n def test_constructor(self, constructor, breaks_and_expected_subtype, closed, name):\n breaks, expected_subtype = breaks_and_expected_subtype\n\n result_kwargs = self.get_kwargs_from_breaks(breaks, closed)\n\n result = constructor(closed=closed, name=name, **result_kwargs)\n\n assert result.closed == closed\n assert result.name == name\n assert result.dtype.subtype == expected_subtype\n tm.assert_index_equal(result.left, Index(breaks[:-1], dtype=expected_subtype))\n tm.assert_index_equal(result.right, Index(breaks[1:], dtype=expected_subtype))\n\n @pytest.mark.parametrize(\n "breaks, subtype",\n [\n (Index([0, 1, 2, 3, 4], dtype=np.int64), "float64"),\n (Index([0, 1, 2, 3, 4], dtype=np.int64), "datetime64[ns]"),\n (Index([0, 1, 2, 3, 4], dtype=np.int64), "timedelta64[ns]"),\n (Index([0, 1, 2, 3, 4], dtype=np.float64), "int64"),\n (date_range("2017-01-01", periods=5), "int64"),\n (timedelta_range("1 day", periods=5), "int64"),\n ],\n )\n def test_constructor_dtype(self, constructor, breaks, subtype):\n # GH 19262: conversion via dtype parameter\n expected_kwargs = self.get_kwargs_from_breaks(breaks.astype(subtype))\n expected = constructor(**expected_kwargs)\n\n result_kwargs = self.get_kwargs_from_breaks(breaks)\n iv_dtype = IntervalDtype(subtype, "right")\n for dtype in (iv_dtype, str(iv_dtype)):\n result = constructor(dtype=dtype, **result_kwargs)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "breaks",\n [\n Index([0, 1, 2, 3, 4], dtype=np.int64),\n Index([0, 1, 2, 3, 4], dtype=np.uint64),\n Index([0, 1, 2, 3, 4], dtype=np.float64),\n date_range("2017-01-01", periods=5),\n timedelta_range("1 day", periods=5),\n ],\n )\n def test_constructor_pass_closed(self, constructor, breaks):\n # not passing closed to IntervalDtype, but to IntervalArray constructor\n iv_dtype = IntervalDtype(breaks.dtype)\n\n result_kwargs = self.get_kwargs_from_breaks(breaks)\n\n for dtype in (iv_dtype, str(iv_dtype)):\n with tm.assert_produces_warning(None):\n result = constructor(dtype=dtype, closed="left", **result_kwargs)\n assert result.dtype.closed == "left"\n\n @pytest.mark.parametrize("breaks", [[np.nan] * 2, [np.nan] * 4, [np.nan] * 50])\n def test_constructor_nan(self, constructor, breaks, closed):\n # GH 18421\n result_kwargs = self.get_kwargs_from_breaks(breaks)\n result = constructor(closed=closed, **result_kwargs)\n\n expected_subtype = np.float64\n expected_values = np.array(breaks[:-1], dtype=object)\n\n assert result.closed == closed\n assert result.dtype.subtype == expected_subtype\n tm.assert_numpy_array_equal(np.array(result), expected_values)\n\n @pytest.mark.parametrize(\n "breaks",\n [\n [],\n np.array([], dtype="int64"),\n np.array([], dtype="uint64"),\n np.array([], dtype="float64"),\n np.array([], dtype="datetime64[ns]"),\n np.array([], dtype="timedelta64[ns]"),\n ],\n )\n def test_constructor_empty(self, constructor, breaks, closed):\n # GH 18421\n result_kwargs = self.get_kwargs_from_breaks(breaks)\n result = constructor(closed=closed, **result_kwargs)\n\n expected_values = np.array([], dtype=object)\n expected_subtype = getattr(breaks, "dtype", np.int64)\n\n assert result.empty\n assert result.closed == closed\n assert result.dtype.subtype == expected_subtype\n tm.assert_numpy_array_equal(np.array(result), expected_values)\n\n @pytest.mark.parametrize(\n "breaks",\n [\n tuple("0123456789"),\n list("abcdefghij"),\n np.array(list("abcdefghij"), dtype=object),\n np.array(list("abcdefghij"), dtype="<U1"),\n ],\n )\n def test_constructor_string(self, constructor, breaks):\n # GH 19016\n msg = (\n "category, object, and string subtypes are not supported "\n "for IntervalIndex"\n )\n with pytest.raises(TypeError, match=msg):\n constructor(**self.get_kwargs_from_breaks(breaks))\n\n @pytest.mark.parametrize("cat_constructor", [Categorical, CategoricalIndex])\n def test_constructor_categorical_valid(self, constructor, cat_constructor):\n # GH 21243/21253\n\n breaks = np.arange(10, dtype="int64")\n expected = IntervalIndex.from_breaks(breaks)\n\n cat_breaks = cat_constructor(breaks)\n result_kwargs = self.get_kwargs_from_breaks(cat_breaks)\n result = constructor(**result_kwargs)\n tm.assert_index_equal(result, expected)\n\n def test_generic_errors(self, constructor):\n # filler input data to be used when supplying invalid kwargs\n filler = self.get_kwargs_from_breaks(range(10))\n\n # invalid closed\n msg = "closed must be one of 'right', 'left', 'both', 'neither'"\n with pytest.raises(ValueError, match=msg):\n constructor(closed="invalid", **filler)\n\n # unsupported dtype\n msg = "dtype must be an IntervalDtype, got int64"\n with pytest.raises(TypeError, match=msg):\n constructor(dtype="int64", **filler)\n\n # invalid dtype\n msg = "data type [\"']invalid[\"'] not understood"\n with pytest.raises(TypeError, match=msg):\n constructor(dtype="invalid", **filler)\n\n # no point in nesting periods in an IntervalIndex\n periods = period_range("2000-01-01", periods=10)\n periods_kwargs = self.get_kwargs_from_breaks(periods)\n msg = "Period dtypes are not supported, use a PeriodIndex instead"\n with pytest.raises(ValueError, match=msg):\n constructor(**periods_kwargs)\n\n # decreasing values\n decreasing_kwargs = self.get_kwargs_from_breaks(range(10, -1, -1))\n msg = "left side of interval must be <= right side"\n with pytest.raises(ValueError, match=msg):\n constructor(**decreasing_kwargs)\n\n\nclass TestFromArrays(ConstructorTests):\n """Tests specific to IntervalIndex.from_arrays"""\n\n @pytest.fixture\n def constructor(self):\n return IntervalIndex.from_arrays\n\n def get_kwargs_from_breaks(self, breaks, closed="right"):\n """\n converts intervals in breaks format to a dictionary of kwargs to\n specific to the format expected by IntervalIndex.from_arrays\n """\n return {"left": breaks[:-1], "right": breaks[1:]}\n\n def test_constructor_errors(self):\n # GH 19016: categorical data\n data = Categorical(list("01234abcde"), ordered=True)\n msg = (\n "category, object, and string subtypes are not supported "\n "for IntervalIndex"\n )\n with pytest.raises(TypeError, match=msg):\n IntervalIndex.from_arrays(data[:-1], data[1:])\n\n # unequal length\n left = [0, 1, 2]\n right = [2, 3]\n msg = "left and right must have the same length"\n with pytest.raises(ValueError, match=msg):\n IntervalIndex.from_arrays(left, right)\n\n @pytest.mark.parametrize(\n "left_subtype, right_subtype", [(np.int64, np.float64), (np.float64, np.int64)]\n )\n def test_mixed_float_int(self, left_subtype, right_subtype):\n """mixed int/float left/right results in float for both sides"""\n left = np.arange(9, dtype=left_subtype)\n right = np.arange(1, 10, dtype=right_subtype)\n result = IntervalIndex.from_arrays(left, right)\n\n expected_left = Index(left, dtype=np.float64)\n expected_right = Index(right, dtype=np.float64)\n expected_subtype = np.float64\n\n tm.assert_index_equal(result.left, expected_left)\n tm.assert_index_equal(result.right, expected_right)\n assert result.dtype.subtype == expected_subtype\n\n @pytest.mark.parametrize("interval_cls", [IntervalArray, IntervalIndex])\n def test_from_arrays_mismatched_datetimelike_resos(self, interval_cls):\n # GH#55714\n left = date_range("2016-01-01", periods=3, unit="s")\n right = date_range("2017-01-01", periods=3, unit="ms")\n result = interval_cls.from_arrays(left, right)\n expected = interval_cls.from_arrays(left.as_unit("ms"), right)\n tm.assert_equal(result, expected)\n\n # td64\n left2 = left - left[0]\n right2 = right - left[0]\n result2 = interval_cls.from_arrays(left2, right2)\n expected2 = interval_cls.from_arrays(left2.as_unit("ms"), right2)\n tm.assert_equal(result2, expected2)\n\n # dt64tz\n left3 = left.tz_localize("UTC")\n right3 = right.tz_localize("UTC")\n result3 = interval_cls.from_arrays(left3, right3)\n expected3 = interval_cls.from_arrays(left3.as_unit("ms"), right3)\n tm.assert_equal(result3, expected3)\n\n\nclass TestFromBreaks(ConstructorTests):\n """Tests specific to IntervalIndex.from_breaks"""\n\n @pytest.fixture\n def constructor(self):\n return IntervalIndex.from_breaks\n\n def get_kwargs_from_breaks(self, breaks, closed="right"):\n """\n converts intervals in breaks format to a dictionary of kwargs to\n specific to the format expected by IntervalIndex.from_breaks\n """\n return {"breaks": breaks}\n\n def test_constructor_errors(self):\n # GH 19016: categorical data\n data = Categorical(list("01234abcde"), ordered=True)\n msg = (\n "category, object, and string subtypes are not supported "\n "for IntervalIndex"\n )\n with pytest.raises(TypeError, match=msg):\n IntervalIndex.from_breaks(data)\n\n def test_length_one(self):\n """breaks of length one produce an empty IntervalIndex"""\n breaks = [0]\n result = IntervalIndex.from_breaks(breaks)\n expected = IntervalIndex.from_breaks([])\n tm.assert_index_equal(result, expected)\n\n def test_left_right_dont_share_data(self):\n # GH#36310\n breaks = np.arange(5)\n result = IntervalIndex.from_breaks(breaks)._data\n assert result._left.base is None or result._left.base is not result._right.base\n\n\nclass TestFromTuples(ConstructorTests):\n """Tests specific to IntervalIndex.from_tuples"""\n\n @pytest.fixture\n def constructor(self):\n return IntervalIndex.from_tuples\n\n def get_kwargs_from_breaks(self, breaks, closed="right"):\n """\n converts intervals in breaks format to a dictionary of kwargs to\n specific to the format expected by IntervalIndex.from_tuples\n """\n if is_unsigned_integer_dtype(breaks):\n pytest.skip(f"{breaks.dtype} not relevant IntervalIndex.from_tuples tests")\n\n if len(breaks) == 0:\n return {"data": breaks}\n\n tuples = list(zip(breaks[:-1], breaks[1:]))\n if isinstance(breaks, (list, tuple)):\n return {"data": tuples}\n elif isinstance(getattr(breaks, "dtype", None), CategoricalDtype):\n return {"data": breaks._constructor(tuples)}\n return {"data": com.asarray_tuplesafe(tuples)}\n\n def test_constructor_errors(self):\n # non-tuple\n tuples = [(0, 1), 2, (3, 4)]\n msg = "IntervalIndex.from_tuples received an invalid item, 2"\n with pytest.raises(TypeError, match=msg.format(t=tuples)):\n IntervalIndex.from_tuples(tuples)\n\n # too few/many items\n tuples = [(0, 1), (2,), (3, 4)]\n msg = "IntervalIndex.from_tuples requires tuples of length 2, got {t}"\n with pytest.raises(ValueError, match=msg.format(t=tuples)):\n IntervalIndex.from_tuples(tuples)\n\n tuples = [(0, 1), (2, 3, 4), (5, 6)]\n with pytest.raises(ValueError, match=msg.format(t=tuples)):\n IntervalIndex.from_tuples(tuples)\n\n def test_na_tuples(self):\n # tuple (NA, NA) evaluates the same as NA as an element\n na_tuple = [(0, 1), (np.nan, np.nan), (2, 3)]\n idx_na_tuple = IntervalIndex.from_tuples(na_tuple)\n idx_na_element = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)])\n tm.assert_index_equal(idx_na_tuple, idx_na_element)\n\n\nclass TestClassConstructors(ConstructorTests):\n """Tests specific to the IntervalIndex/Index constructors"""\n\n @pytest.fixture(\n params=[IntervalIndex, partial(Index, dtype="interval")],\n ids=["IntervalIndex", "Index"],\n )\n def klass(self, request):\n # We use a separate fixture here to include Index.__new__ with dtype kwarg\n return request.param\n\n @pytest.fixture\n def constructor(self):\n return IntervalIndex\n\n def get_kwargs_from_breaks(self, breaks, closed="right"):\n """\n converts intervals in breaks format to a dictionary of kwargs to\n specific to the format expected by the IntervalIndex/Index constructors\n """\n if is_unsigned_integer_dtype(breaks):\n pytest.skip(f"{breaks.dtype} not relevant for class constructor tests")\n\n if len(breaks) == 0:\n return {"data": breaks}\n\n ivs = [\n Interval(left, right, closed) if notna(left) else left\n for left, right in zip(breaks[:-1], breaks[1:])\n ]\n\n if isinstance(breaks, list):\n return {"data": ivs}\n elif isinstance(getattr(breaks, "dtype", None), CategoricalDtype):\n return {"data": breaks._constructor(ivs)}\n return {"data": np.array(ivs, dtype=object)}\n\n def test_generic_errors(self, constructor):\n """\n override the base class implementation since errors are handled\n differently; checks unnecessary since caught at the Interval level\n """\n\n def test_constructor_string(self):\n # GH23013\n # When forming the interval from breaks,\n # the interval of strings is already forbidden.\n pass\n\n def test_constructor_errors(self, klass):\n # mismatched closed within intervals with no constructor override\n ivs = [Interval(0, 1, closed="right"), Interval(2, 3, closed="left")]\n msg = "intervals must all be closed on the same side"\n with pytest.raises(ValueError, match=msg):\n klass(ivs)\n\n # scalar\n msg = (\n r"(IntervalIndex|Index)\(...\) must be called with a collection of "\n "some kind, 5 was passed"\n )\n with pytest.raises(TypeError, match=msg):\n klass(5)\n\n # not an interval; dtype depends on 32bit/windows builds\n msg = "type <class 'numpy.int(32|64)'> with value 0 is not an interval"\n with pytest.raises(TypeError, match=msg):\n klass([0, 1])\n\n @pytest.mark.parametrize(\n "data, closed",\n [\n ([], "both"),\n ([np.nan, np.nan], "neither"),\n (\n [Interval(0, 3, closed="neither"), Interval(2, 5, closed="neither")],\n "left",\n ),\n (\n [Interval(0, 3, closed="left"), Interval(2, 5, closed="right")],\n "neither",\n ),\n (IntervalIndex.from_breaks(range(5), closed="both"), "right"),\n ],\n )\n def test_override_inferred_closed(self, constructor, data, closed):\n # GH 19370\n if isinstance(data, IntervalIndex):\n tuples = data.to_tuples()\n else:\n tuples = [(iv.left, iv.right) if notna(iv) else iv for iv in data]\n expected = IntervalIndex.from_tuples(tuples, closed=closed)\n result = constructor(data, closed=closed)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "values_constructor", [list, np.array, IntervalIndex, IntervalArray]\n )\n def test_index_object_dtype(self, values_constructor):\n # Index(intervals, dtype=object) is an Index (not an IntervalIndex)\n intervals = [Interval(0, 1), Interval(1, 2), Interval(2, 3)]\n values = values_constructor(intervals)\n result = Index(values, dtype=object)\n\n assert type(result) is Index\n tm.assert_numpy_array_equal(result.values, np.array(values))\n\n def test_index_mixed_closed(self):\n # GH27172\n intervals = [\n Interval(0, 1, closed="left"),\n Interval(1, 2, closed="right"),\n Interval(2, 3, closed="neither"),\n Interval(3, 4, closed="both"),\n ]\n result = Index(intervals)\n expected = Index(intervals, dtype=object)\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("timezone", ["UTC", "US/Pacific", "GMT"])\ndef test_interval_index_subtype(timezone, inclusive_endpoints_fixture):\n # GH#46999\n dates = date_range("2022", periods=3, tz=timezone)\n dtype = f"interval[datetime64[ns, {timezone}], {inclusive_endpoints_fixture}]"\n result = IntervalIndex.from_arrays(\n ["2022-01-01", "2022-01-02"],\n ["2022-01-02", "2022-01-03"],\n closed=inclusive_endpoints_fixture,\n dtype=dtype,\n )\n expected = IntervalIndex.from_arrays(\n dates[:-1], dates[1:], closed=inclusive_endpoints_fixture\n )\n tm.assert_index_equal(result, expected)\n\n\ndef test_dtype_closed_mismatch():\n # GH#38394 closed specified in both dtype and IntervalIndex constructor\n\n dtype = IntervalDtype(np.int64, "left")\n\n msg = "closed keyword does not match dtype.closed"\n with pytest.raises(ValueError, match=msg):\n IntervalIndex([], dtype=dtype, closed="neither")\n\n with pytest.raises(ValueError, match=msg):\n IntervalArray([], dtype=dtype, closed="neither")\n\n\n@pytest.mark.parametrize(\n "dtype",\n ["Float64", pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow"))],\n)\ndef test_ea_dtype(dtype):\n # GH#56765\n bins = [(0.0, 0.4), (0.4, 0.6)]\n interval_dtype = IntervalDtype(subtype=dtype, closed="left")\n result = IntervalIndex.from_tuples(bins, closed="left", dtype=interval_dtype)\n assert result.dtype == interval_dtype\n expected = IntervalIndex.from_tuples(bins, closed="left").astype(interval_dtype)\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_constructors.py
test_constructors.py
Python
19,853
0.95
0.117757
0.078475
python-kit
372
2024-06-18T05:01:32.198830
Apache-2.0
true
1f8ce5753fad138d3a818ef034d6a248
import numpy as np\n\nfrom pandas import (\n IntervalIndex,\n date_range,\n)\n\n\nclass TestEquals:\n def test_equals(self, closed):\n expected = IntervalIndex.from_breaks(np.arange(5), closed=closed)\n assert expected.equals(expected)\n assert expected.equals(expected.copy())\n\n assert not expected.equals(expected.astype(object))\n assert not expected.equals(np.array(expected))\n assert not expected.equals(list(expected))\n\n assert not expected.equals([1, 2])\n assert not expected.equals(np.array([1, 2]))\n assert not expected.equals(date_range("20130101", periods=2))\n\n expected_name1 = IntervalIndex.from_breaks(\n np.arange(5), closed=closed, name="foo"\n )\n expected_name2 = IntervalIndex.from_breaks(\n np.arange(5), closed=closed, name="bar"\n )\n assert expected.equals(expected_name1)\n assert expected_name1.equals(expected_name2)\n\n for other_closed in {"left", "right", "both", "neither"} - {closed}:\n expected_other_closed = IntervalIndex.from_breaks(\n np.arange(5), closed=other_closed\n )\n assert not expected.equals(expected_other_closed)\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_equals.py
test_equals.py
Python
1,226
0.85
0.083333
0
python-kit
48
2024-06-03T18:09:30.553355
BSD-3-Clause
true
f044003bd71ee32b33c81b574ecf1b79
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n DatetimeIndex,\n Index,\n Interval,\n IntervalIndex,\n Series,\n Timedelta,\n Timestamp,\n)\nimport pandas._testing as tm\n\n\nclass TestIntervalIndexRendering:\n # TODO: this is a test for DataFrame/Series, not IntervalIndex\n @pytest.mark.parametrize(\n "constructor,expected",\n [\n (\n Series,\n (\n "(0.0, 1.0] a\n"\n "NaN b\n"\n "(2.0, 3.0] c\n"\n "dtype: object"\n ),\n ),\n (DataFrame, (" 0\n(0.0, 1.0] a\nNaN b\n(2.0, 3.0] c")),\n ],\n )\n def test_repr_missing(self, constructor, expected, using_infer_string, request):\n # GH 25984\n if using_infer_string and constructor is Series:\n request.applymarker(pytest.mark.xfail(reason="repr different"))\n index = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)])\n obj = constructor(list("abc"), index=index)\n result = repr(obj)\n assert result == expected\n\n def test_repr_floats(self):\n # GH 32553\n\n markers = Series(\n [1, 2],\n index=IntervalIndex(\n [\n Interval(left, right)\n for left, right in zip(\n Index([329.973, 345.137], dtype="float64"),\n Index([345.137, 360.191], dtype="float64"),\n )\n ]\n ),\n )\n result = str(markers)\n expected = "(329.973, 345.137] 1\n(345.137, 360.191] 2\ndtype: int64"\n assert result == expected\n\n @pytest.mark.filterwarnings(\n "ignore:invalid value encountered in cast:RuntimeWarning"\n )\n @pytest.mark.parametrize(\n "tuples, closed, expected_data",\n [\n ([(0, 1), (1, 2), (2, 3)], "left", ["[0, 1)", "[1, 2)", "[2, 3)"]),\n (\n [(0.5, 1.0), np.nan, (2.0, 3.0)],\n "right",\n ["(0.5, 1.0]", "NaN", "(2.0, 3.0]"],\n ),\n (\n [\n (Timestamp("20180101"), Timestamp("20180102")),\n np.nan,\n ((Timestamp("20180102"), Timestamp("20180103"))),\n ],\n "both",\n [\n "[2018-01-01 00:00:00, 2018-01-02 00:00:00]",\n "NaN",\n "[2018-01-02 00:00:00, 2018-01-03 00:00:00]",\n ],\n ),\n (\n [\n (Timedelta("0 days"), Timedelta("1 days")),\n (Timedelta("1 days"), Timedelta("2 days")),\n np.nan,\n ],\n "neither",\n [\n "(0 days 00:00:00, 1 days 00:00:00)",\n "(1 days 00:00:00, 2 days 00:00:00)",\n "NaN",\n ],\n ),\n ],\n )\n def test_get_values_for_csv(self, tuples, closed, expected_data):\n # GH 28210\n index = IntervalIndex.from_tuples(tuples, closed=closed)\n result = index._get_values_for_csv(na_rep="NaN")\n expected = np.array(expected_data)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_timestamp_with_timezone(self, unit):\n # GH 55035\n left = DatetimeIndex(["2020-01-01"], dtype=f"M8[{unit}, UTC]")\n right = DatetimeIndex(["2020-01-02"], dtype=f"M8[{unit}, UTC]")\n index = IntervalIndex.from_arrays(left, right)\n result = repr(index)\n expected = (\n "IntervalIndex([(2020-01-01 00:00:00+00:00, 2020-01-02 00:00:00+00:00]], "\n f"dtype='interval[datetime64[{unit}, UTC], right]')"\n )\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_formats.py
test_formats.py
Python
3,880
0.95
0.067227
0.044643
awesome-app
115
2023-11-28T21:27:01.903130
GPL-3.0
true
142b5bce5f9bfb0fa248b4c5b89ac7bd
import re\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import InvalidIndexError\n\nfrom pandas import (\n NA,\n CategoricalIndex,\n DatetimeIndex,\n Index,\n Interval,\n IntervalIndex,\n MultiIndex,\n NaT,\n Timedelta,\n Timestamp,\n array,\n date_range,\n interval_range,\n isna,\n period_range,\n timedelta_range,\n)\nimport pandas._testing as tm\n\n\nclass TestGetItem:\n def test_getitem(self, closed):\n idx = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), closed=closed)\n assert idx[0] == Interval(0.0, 1.0, closed=closed)\n assert idx[1] == Interval(1.0, 2.0, closed=closed)\n assert isna(idx[2])\n\n result = idx[0:1]\n expected = IntervalIndex.from_arrays((0.0,), (1.0,), closed=closed)\n tm.assert_index_equal(result, expected)\n\n result = idx[0:2]\n expected = IntervalIndex.from_arrays((0.0, 1), (1.0, 2.0), closed=closed)\n tm.assert_index_equal(result, expected)\n\n result = idx[1:3]\n expected = IntervalIndex.from_arrays(\n (1.0, np.nan), (2.0, np.nan), closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n def test_getitem_2d_deprecated(self):\n # GH#30588 multi-dim indexing is deprecated, but raising is also acceptable\n idx = IntervalIndex.from_breaks(range(11), closed="right")\n with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):\n idx[:, None]\n with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):\n # GH#44051\n idx[True]\n with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):\n # GH#44051\n idx[False]\n\n\nclass TestWhere:\n def test_where(self, listlike_box):\n klass = listlike_box\n\n idx = IntervalIndex.from_breaks(range(11), closed="right")\n cond = [True] * len(idx)\n expected = idx\n result = expected.where(klass(cond))\n tm.assert_index_equal(result, expected)\n\n cond = [False] + [True] * len(idx[1:])\n expected = IntervalIndex([np.nan] + idx[1:].tolist())\n result = idx.where(klass(cond))\n tm.assert_index_equal(result, expected)\n\n\nclass TestTake:\n def test_take(self, closed):\n index = IntervalIndex.from_breaks(range(11), closed=closed)\n\n result = index.take(range(10))\n tm.assert_index_equal(result, index)\n\n result = index.take([0, 0, 1])\n expected = IntervalIndex.from_arrays([0, 0, 1], [1, 1, 2], closed=closed)\n tm.assert_index_equal(result, expected)\n\n\nclass TestGetLoc:\n @pytest.mark.parametrize("side", ["right", "left", "both", "neither"])\n def test_get_loc_interval(self, closed, side):\n idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)\n\n for bound in [[0, 1], [1, 2], [2, 3], [3, 4], [0, 2], [2.5, 3], [-1, 4]]:\n # if get_loc is supplied an interval, it should only search\n # for exact matches, not overlaps or covers, else KeyError.\n msg = re.escape(f"Interval({bound[0]}, {bound[1]}, closed='{side}')")\n if closed == side:\n if bound == [0, 1]:\n assert idx.get_loc(Interval(0, 1, closed=side)) == 0\n elif bound == [2, 3]:\n assert idx.get_loc(Interval(2, 3, closed=side)) == 1\n else:\n with pytest.raises(KeyError, match=msg):\n idx.get_loc(Interval(*bound, closed=side))\n else:\n with pytest.raises(KeyError, match=msg):\n idx.get_loc(Interval(*bound, closed=side))\n\n @pytest.mark.parametrize("scalar", [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5])\n def test_get_loc_scalar(self, closed, scalar):\n # correct = {side: {query: answer}}.\n # If query is not in the dict, that query should raise a KeyError\n correct = {\n "right": {0.5: 0, 1: 0, 2.5: 1, 3: 1},\n "left": {0: 0, 0.5: 0, 2: 1, 2.5: 1},\n "both": {0: 0, 0.5: 0, 1: 0, 2: 1, 2.5: 1, 3: 1},\n "neither": {0.5: 0, 2.5: 1},\n }\n\n idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)\n\n # if get_loc is supplied a scalar, it should return the index of\n # the interval which contains the scalar, or KeyError.\n if scalar in correct[closed].keys():\n assert idx.get_loc(scalar) == correct[closed][scalar]\n else:\n with pytest.raises(KeyError, match=str(scalar)):\n idx.get_loc(scalar)\n\n @pytest.mark.parametrize("scalar", [-1, 0, 0.5, 3, 4.5, 5, 6])\n def test_get_loc_length_one_scalar(self, scalar, closed):\n # GH 20921\n index = IntervalIndex.from_tuples([(0, 5)], closed=closed)\n if scalar in index[0]:\n result = index.get_loc(scalar)\n assert result == 0\n else:\n with pytest.raises(KeyError, match=str(scalar)):\n index.get_loc(scalar)\n\n @pytest.mark.parametrize("other_closed", ["left", "right", "both", "neither"])\n @pytest.mark.parametrize("left, right", [(0, 5), (-1, 4), (-1, 6), (6, 7)])\n def test_get_loc_length_one_interval(self, left, right, closed, other_closed):\n # GH 20921\n index = IntervalIndex.from_tuples([(0, 5)], closed=closed)\n interval = Interval(left, right, closed=other_closed)\n if interval == index[0]:\n result = index.get_loc(interval)\n assert result == 0\n else:\n with pytest.raises(\n KeyError,\n match=re.escape(f"Interval({left}, {right}, closed='{other_closed}')"),\n ):\n index.get_loc(interval)\n\n # Make consistent with test_interval_new.py (see #16316, #16386)\n @pytest.mark.parametrize(\n "breaks",\n [\n date_range("20180101", periods=4),\n date_range("20180101", periods=4, tz="US/Eastern"),\n timedelta_range("0 days", periods=4),\n ],\n ids=lambda x: str(x.dtype),\n )\n def test_get_loc_datetimelike_nonoverlapping(self, breaks):\n # GH 20636\n # nonoverlapping = IntervalIndex method and no i8 conversion\n index = IntervalIndex.from_breaks(breaks)\n\n value = index[0].mid\n result = index.get_loc(value)\n expected = 0\n assert result == expected\n\n interval = Interval(index[0].left, index[0].right)\n result = index.get_loc(interval)\n expected = 0\n assert result == expected\n\n @pytest.mark.parametrize(\n "arrays",\n [\n (date_range("20180101", periods=4), date_range("20180103", periods=4)),\n (\n date_range("20180101", periods=4, tz="US/Eastern"),\n date_range("20180103", periods=4, tz="US/Eastern"),\n ),\n (\n timedelta_range("0 days", periods=4),\n timedelta_range("2 days", periods=4),\n ),\n ],\n ids=lambda x: str(x[0].dtype),\n )\n def test_get_loc_datetimelike_overlapping(self, arrays):\n # GH 20636\n index = IntervalIndex.from_arrays(*arrays)\n\n value = index[0].mid + Timedelta("12 hours")\n result = index.get_loc(value)\n expected = slice(0, 2, None)\n assert result == expected\n\n interval = Interval(index[0].left, index[0].right)\n result = index.get_loc(interval)\n expected = 0\n assert result == expected\n\n @pytest.mark.parametrize(\n "values",\n [\n date_range("2018-01-04", periods=4, freq="-1D"),\n date_range("2018-01-04", periods=4, freq="-1D", tz="US/Eastern"),\n timedelta_range("3 days", periods=4, freq="-1D"),\n np.arange(3.0, -1.0, -1.0),\n np.arange(3, -1, -1),\n ],\n ids=lambda x: str(x.dtype),\n )\n def test_get_loc_decreasing(self, values):\n # GH 25860\n index = IntervalIndex.from_arrays(values[1:], values[:-1])\n result = index.get_loc(index[0])\n expected = 0\n assert result == expected\n\n @pytest.mark.parametrize("key", [[5], (2, 3)])\n def test_get_loc_non_scalar_errors(self, key):\n # GH 31117\n idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])\n\n msg = str(key)\n with pytest.raises(InvalidIndexError, match=msg):\n idx.get_loc(key)\n\n def test_get_indexer_with_nans(self):\n # GH#41831\n index = IntervalIndex([np.nan, Interval(1, 2), np.nan])\n\n expected = np.array([True, False, True])\n for key in [None, np.nan, NA]:\n assert key in index\n result = index.get_loc(key)\n tm.assert_numpy_array_equal(result, expected)\n\n for key in [NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")]:\n with pytest.raises(KeyError, match=str(key)):\n index.get_loc(key)\n\n\nclass TestGetIndexer:\n @pytest.mark.parametrize(\n "query, expected",\n [\n ([Interval(2, 4, closed="right")], [1]),\n ([Interval(2, 4, closed="left")], [-1]),\n ([Interval(2, 4, closed="both")], [-1]),\n ([Interval(2, 4, closed="neither")], [-1]),\n ([Interval(1, 4, closed="right")], [-1]),\n ([Interval(0, 4, closed="right")], [-1]),\n ([Interval(0.5, 1.5, closed="right")], [-1]),\n ([Interval(2, 4, closed="right"), Interval(0, 1, closed="right")], [1, -1]),\n ([Interval(2, 4, closed="right"), Interval(2, 4, closed="right")], [1, 1]),\n ([Interval(5, 7, closed="right"), Interval(2, 4, closed="right")], [2, 1]),\n ([Interval(2, 4, closed="right"), Interval(2, 4, closed="left")], [1, -1]),\n ],\n )\n def test_get_indexer_with_interval(self, query, expected):\n tuples = [(0, 2), (2, 4), (5, 7)]\n index = IntervalIndex.from_tuples(tuples, closed="right")\n\n result = index.get_indexer(query)\n expected = np.array(expected, dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n "query, expected",\n [\n ([-0.5], [-1]),\n ([0], [-1]),\n ([0.5], [0]),\n ([1], [0]),\n ([1.5], [1]),\n ([2], [1]),\n ([2.5], [-1]),\n ([3], [-1]),\n ([3.5], [2]),\n ([4], [2]),\n ([4.5], [-1]),\n ([1, 2], [0, 1]),\n ([1, 2, 3], [0, 1, -1]),\n ([1, 2, 3, 4], [0, 1, -1, 2]),\n ([1, 2, 3, 4, 2], [0, 1, -1, 2, 1]),\n ],\n )\n def test_get_indexer_with_int_and_float(self, query, expected):\n tuples = [(0, 1), (1, 2), (3, 4)]\n index = IntervalIndex.from_tuples(tuples, closed="right")\n\n result = index.get_indexer(query)\n expected = np.array(expected, dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize("item", [[3], np.arange(0.5, 5, 0.5)])\n def test_get_indexer_length_one(self, item, closed):\n # GH 17284\n index = IntervalIndex.from_tuples([(0, 5)], closed=closed)\n result = index.get_indexer(item)\n expected = np.array([0] * len(item), dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize("size", [1, 5])\n def test_get_indexer_length_one_interval(self, size, closed):\n # GH 17284\n index = IntervalIndex.from_tuples([(0, 5)], closed=closed)\n result = index.get_indexer([Interval(0, 5, closed)] * size)\n expected = np.array([0] * size, dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n "target",\n [\n IntervalIndex.from_tuples([(7, 8), (1, 2), (3, 4), (0, 1)]),\n IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4), np.nan]),\n IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)], closed="both"),\n [-1, 0, 0.5, 1, 2, 2.5, np.nan],\n ["foo", "foo", "bar", "baz"],\n ],\n )\n def test_get_indexer_categorical(self, target, ordered):\n # GH 30063: categorical and non-categorical results should be consistent\n index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)])\n categorical_target = CategoricalIndex(target, ordered=ordered)\n\n result = index.get_indexer(categorical_target)\n expected = index.get_indexer(target)\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.filterwarnings(\n "ignore:invalid value encountered in cast:RuntimeWarning"\n )\n def test_get_indexer_categorical_with_nans(self):\n # GH#41934 nans in both index and in target\n ii = IntervalIndex.from_breaks(range(5))\n ii2 = ii.append(IntervalIndex([np.nan]))\n ci2 = CategoricalIndex(ii2)\n\n result = ii2.get_indexer(ci2)\n expected = np.arange(5, dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n # not-all-matches\n result = ii2[1:].get_indexer(ci2[::-1])\n expected = np.array([3, 2, 1, 0, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n # non-unique target, non-unique nans\n result = ii2.get_indexer(ci2.append(ci2))\n expected = np.array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_indexer_datetime(self):\n ii = IntervalIndex.from_breaks(date_range("2018-01-01", periods=4))\n # TODO: with mismatched resolution get_indexer currently raises;\n # this should probably coerce?\n target = DatetimeIndex(["2018-01-02"], dtype="M8[ns]")\n result = ii.get_indexer(target)\n expected = np.array([0], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n result = ii.get_indexer(target.astype(str))\n tm.assert_numpy_array_equal(result, expected)\n\n # https://github.com/pandas-dev/pandas/issues/47772\n result = ii.get_indexer(target.asi8)\n expected = np.array([-1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n "tuples, closed",\n [\n ([(0, 2), (1, 3), (3, 4)], "neither"),\n ([(0, 5), (1, 4), (6, 7)], "left"),\n ([(0, 1), (0, 1), (1, 2)], "right"),\n ([(0, 1), (2, 3), (3, 4)], "both"),\n ],\n )\n def test_get_indexer_errors(self, tuples, closed):\n # IntervalIndex needs non-overlapping for uniqueness when querying\n index = IntervalIndex.from_tuples(tuples, closed=closed)\n\n msg = (\n "cannot handle overlapping indices; use "\n "IntervalIndex.get_indexer_non_unique"\n )\n with pytest.raises(InvalidIndexError, match=msg):\n index.get_indexer([0, 2])\n\n @pytest.mark.parametrize(\n "query, expected",\n [\n ([-0.5], ([-1], [0])),\n ([0], ([0], [])),\n ([0.5], ([0], [])),\n ([1], ([0, 1], [])),\n ([1.5], ([0, 1], [])),\n ([2], ([0, 1, 2], [])),\n ([2.5], ([1, 2], [])),\n ([3], ([2], [])),\n ([3.5], ([2], [])),\n ([4], ([-1], [0])),\n ([4.5], ([-1], [0])),\n ([1, 2], ([0, 1, 0, 1, 2], [])),\n ([1, 2, 3], ([0, 1, 0, 1, 2, 2], [])),\n ([1, 2, 3, 4], ([0, 1, 0, 1, 2, 2, -1], [3])),\n ([1, 2, 3, 4, 2], ([0, 1, 0, 1, 2, 2, -1, 0, 1, 2], [3])),\n ],\n )\n def test_get_indexer_non_unique_with_int_and_float(self, query, expected):\n tuples = [(0, 2.5), (1, 3), (2, 4)]\n index = IntervalIndex.from_tuples(tuples, closed="left")\n\n result_indexer, result_missing = index.get_indexer_non_unique(query)\n expected_indexer = np.array(expected[0], dtype="intp")\n expected_missing = np.array(expected[1], dtype="intp")\n\n tm.assert_numpy_array_equal(result_indexer, expected_indexer)\n tm.assert_numpy_array_equal(result_missing, expected_missing)\n\n # TODO we may also want to test get_indexer for the case when\n # the intervals are duplicated, decreasing, non-monotonic, etc..\n\n def test_get_indexer_non_monotonic(self):\n # GH 16410\n idx1 = IntervalIndex.from_tuples([(2, 3), (4, 5), (0, 1)])\n idx2 = IntervalIndex.from_tuples([(0, 1), (2, 3), (6, 7), (8, 9)])\n result = idx1.get_indexer(idx2)\n expected = np.array([2, 0, -1, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1.get_indexer(idx1[1:])\n expected = np.array([1, 2], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_indexer_with_nans(self):\n # GH#41831\n index = IntervalIndex([np.nan, np.nan])\n other = IntervalIndex([np.nan])\n\n assert not index._index_as_unique\n\n result = index.get_indexer_for(other)\n expected = np.array([0, 1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_index_non_unique_non_monotonic(self):\n # GH#44084 (root cause)\n index = IntervalIndex.from_tuples(\n [(0.0, 1.0), (1.0, 2.0), (0.0, 1.0), (1.0, 2.0)]\n )\n\n result, _ = index.get_indexer_non_unique([Interval(1.0, 2.0)])\n expected = np.array([1, 3], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_indexer_multiindex_with_intervals(self):\n # GH#44084 (MultiIndex case as reported)\n interval_index = IntervalIndex.from_tuples(\n [(2.0, 3.0), (0.0, 1.0), (1.0, 2.0)], name="interval"\n )\n foo_index = Index([1, 2, 3], name="foo")\n\n multi_index = MultiIndex.from_product([foo_index, interval_index])\n\n result = multi_index.get_level_values("interval").get_indexer_for(\n [Interval(0.0, 1.0)]\n )\n expected = np.array([1, 4, 7], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize("box", [IntervalIndex, array, list])\n def test_get_indexer_interval_index(self, box):\n # GH#30178\n rng = period_range("2022-07-01", freq="D", periods=3)\n idx = box(interval_range(Timestamp("2022-07-01"), freq="3D", periods=3))\n\n actual = rng.get_indexer(idx)\n expected = np.array([-1, -1, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(actual, expected)\n\n def test_get_indexer_read_only(self):\n idx = interval_range(start=0, end=5)\n arr = np.array([1, 2])\n arr.flags.writeable = False\n result = idx.get_indexer(arr)\n expected = np.array([0, 1])\n tm.assert_numpy_array_equal(result, expected, check_dtype=False)\n\n result = idx.get_indexer_non_unique(arr)[0]\n tm.assert_numpy_array_equal(result, expected, check_dtype=False)\n\n\nclass TestSliceLocs:\n def test_slice_locs_with_interval(self):\n # increasing monotonically\n index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)])\n\n assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3)\n assert index.slice_locs(start=Interval(0, 2)) == (0, 3)\n assert index.slice_locs(end=Interval(2, 4)) == (0, 3)\n assert index.slice_locs(end=Interval(0, 2)) == (0, 1)\n assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 1)\n\n # decreasing monotonically\n index = IntervalIndex.from_tuples([(2, 4), (1, 3), (0, 2)])\n\n assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (2, 1)\n assert index.slice_locs(start=Interval(0, 2)) == (2, 3)\n assert index.slice_locs(end=Interval(2, 4)) == (0, 1)\n assert index.slice_locs(end=Interval(0, 2)) == (0, 3)\n assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (0, 3)\n\n # sorted duplicates\n index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4)])\n\n assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3)\n assert index.slice_locs(start=Interval(0, 2)) == (0, 3)\n assert index.slice_locs(end=Interval(2, 4)) == (0, 3)\n assert index.slice_locs(end=Interval(0, 2)) == (0, 2)\n assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2)\n\n # unsorted duplicates\n index = IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)])\n\n with pytest.raises(\n KeyError,\n match=re.escape(\n '"Cannot get left slice bound for non-unique label: '\n "Interval(0, 2, closed='right')\""\n ),\n ):\n index.slice_locs(start=Interval(0, 2), end=Interval(2, 4))\n\n with pytest.raises(\n KeyError,\n match=re.escape(\n '"Cannot get left slice bound for non-unique label: '\n "Interval(0, 2, closed='right')\""\n ),\n ):\n index.slice_locs(start=Interval(0, 2))\n\n assert index.slice_locs(end=Interval(2, 4)) == (0, 2)\n\n with pytest.raises(\n KeyError,\n match=re.escape(\n '"Cannot get right slice bound for non-unique label: '\n "Interval(0, 2, closed='right')\""\n ),\n ):\n index.slice_locs(end=Interval(0, 2))\n\n with pytest.raises(\n KeyError,\n match=re.escape(\n '"Cannot get right slice bound for non-unique label: '\n "Interval(0, 2, closed='right')\""\n ),\n ):\n index.slice_locs(start=Interval(2, 4), end=Interval(0, 2))\n\n # another unsorted duplicates\n index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)])\n\n assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3)\n assert index.slice_locs(start=Interval(0, 2)) == (0, 4)\n assert index.slice_locs(end=Interval(2, 4)) == (0, 3)\n assert index.slice_locs(end=Interval(0, 2)) == (0, 2)\n assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2)\n\n def test_slice_locs_with_ints_and_floats_succeeds(self):\n # increasing non-overlapping\n index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)])\n\n assert index.slice_locs(0, 1) == (0, 1)\n assert index.slice_locs(0, 2) == (0, 2)\n assert index.slice_locs(0, 3) == (0, 2)\n assert index.slice_locs(3, 1) == (2, 1)\n assert index.slice_locs(3, 4) == (2, 3)\n assert index.slice_locs(0, 4) == (0, 3)\n\n # decreasing non-overlapping\n index = IntervalIndex.from_tuples([(3, 4), (1, 2), (0, 1)])\n assert index.slice_locs(0, 1) == (3, 3)\n assert index.slice_locs(0, 2) == (3, 2)\n assert index.slice_locs(0, 3) == (3, 1)\n assert index.slice_locs(3, 1) == (1, 3)\n assert index.slice_locs(3, 4) == (1, 1)\n assert index.slice_locs(0, 4) == (3, 1)\n\n @pytest.mark.parametrize("query", [[0, 1], [0, 2], [0, 3], [0, 4]])\n @pytest.mark.parametrize(\n "tuples",\n [\n [(0, 2), (1, 3), (2, 4)],\n [(2, 4), (1, 3), (0, 2)],\n [(0, 2), (0, 2), (2, 4)],\n [(0, 2), (2, 4), (0, 2)],\n [(0, 2), (0, 2), (2, 4), (1, 3)],\n ],\n )\n def test_slice_locs_with_ints_and_floats_errors(self, tuples, query):\n start, stop = query\n index = IntervalIndex.from_tuples(tuples)\n with pytest.raises(\n KeyError,\n match=(\n "'can only get slices from an IntervalIndex if bounds are "\n "non-overlapping and all monotonic increasing or decreasing'"\n ),\n ):\n index.slice_locs(start, stop)\n\n\nclass TestPutmask:\n @pytest.mark.parametrize("tz", ["US/Pacific", None])\n def test_putmask_dt64(self, tz):\n # GH#37968\n dti = date_range("2016-01-01", periods=9, tz=tz)\n idx = IntervalIndex.from_breaks(dti)\n mask = np.zeros(idx.shape, dtype=bool)\n mask[0:3] = True\n\n result = idx.putmask(mask, idx[-1])\n expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:]))\n tm.assert_index_equal(result, expected)\n\n def test_putmask_td64(self):\n # GH#37968\n dti = date_range("2016-01-01", periods=9)\n tdi = dti - dti[0]\n idx = IntervalIndex.from_breaks(tdi)\n mask = np.zeros(idx.shape, dtype=bool)\n mask[0:3] = True\n\n result = idx.putmask(mask, idx[-1])\n expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:]))\n tm.assert_index_equal(result, expected)\n\n\nclass TestContains:\n # .__contains__, not .contains\n\n def test_contains_dunder(self):\n index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right")\n\n # __contains__ requires perfect matches to intervals.\n assert 0 not in index\n assert 1 not in index\n assert 2 not in index\n\n assert Interval(0, 1, closed="right") in index\n assert Interval(0, 2, closed="right") not in index\n assert Interval(0, 0.5, closed="right") not in index\n assert Interval(3, 5, closed="right") not in index\n assert Interval(-1, 0, closed="left") not in index\n assert Interval(0, 1, closed="left") not in index\n assert Interval(0, 1, closed="both") not in index\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_indexing.py
test_indexing.py
Python
25,425
0.95
0.089021
0.08042
awesome-app
884
2023-11-14T03:01:18.688794
GPL-3.0
true
aa29f1fb23b1631c3f3058bc051a3a94
from itertools import permutations\nimport re\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Index,\n Interval,\n IntervalIndex,\n Timedelta,\n Timestamp,\n date_range,\n interval_range,\n isna,\n notna,\n timedelta_range,\n)\nimport pandas._testing as tm\nimport pandas.core.common as com\n\n\n@pytest.fixture(params=[None, "foo"])\ndef name(request):\n return request.param\n\n\nclass TestIntervalIndex:\n index = IntervalIndex.from_arrays([0, 1], [1, 2])\n\n def create_index(self, closed="right"):\n return IntervalIndex.from_breaks(range(11), closed=closed)\n\n def create_index_with_nan(self, closed="right"):\n mask = [True, False] + [True] * 8\n return IntervalIndex.from_arrays(\n np.where(mask, np.arange(10), np.nan),\n np.where(mask, np.arange(1, 11), np.nan),\n closed=closed,\n )\n\n def test_properties(self, closed):\n index = self.create_index(closed=closed)\n assert len(index) == 10\n assert index.size == 10\n assert index.shape == (10,)\n\n tm.assert_index_equal(index.left, Index(np.arange(10, dtype=np.int64)))\n tm.assert_index_equal(index.right, Index(np.arange(1, 11, dtype=np.int64)))\n tm.assert_index_equal(index.mid, Index(np.arange(0.5, 10.5, dtype=np.float64)))\n\n assert index.closed == closed\n\n ivs = [\n Interval(left, right, closed)\n for left, right in zip(range(10), range(1, 11))\n ]\n expected = np.array(ivs, dtype=object)\n tm.assert_numpy_array_equal(np.asarray(index), expected)\n\n # with nans\n index = self.create_index_with_nan(closed=closed)\n assert len(index) == 10\n assert index.size == 10\n assert index.shape == (10,)\n\n expected_left = Index([0, np.nan, 2, 3, 4, 5, 6, 7, 8, 9])\n expected_right = expected_left + 1\n expected_mid = expected_left + 0.5\n tm.assert_index_equal(index.left, expected_left)\n tm.assert_index_equal(index.right, expected_right)\n tm.assert_index_equal(index.mid, expected_mid)\n\n assert index.closed == closed\n\n ivs = [\n Interval(left, right, closed) if notna(left) else np.nan\n for left, right in zip(expected_left, expected_right)\n ]\n expected = np.array(ivs, dtype=object)\n tm.assert_numpy_array_equal(np.asarray(index), expected)\n\n @pytest.mark.parametrize(\n "breaks",\n [\n [1, 1, 2, 5, 15, 53, 217, 1014, 5335, 31240, 201608],\n [-np.inf, -100, -10, 0.5, 1, 1.5, 3.8, 101, 202, np.inf],\n date_range("2017-01-01", "2017-01-04"),\n pytest.param(\n date_range("2017-01-01", "2017-01-04", unit="s"),\n marks=pytest.mark.xfail(reason="mismatched result unit"),\n ),\n pd.to_timedelta(["1ns", "2ms", "3s", "4min", "5h", "6D"]),\n ],\n )\n def test_length(self, closed, breaks):\n # GH 18789\n index = IntervalIndex.from_breaks(breaks, closed=closed)\n result = index.length\n expected = Index(iv.length for iv in index)\n tm.assert_index_equal(result, expected)\n\n # with NA\n index = index.insert(1, np.nan)\n result = index.length\n expected = Index(iv.length if notna(iv) else iv for iv in index)\n tm.assert_index_equal(result, expected)\n\n def test_with_nans(self, closed):\n index = self.create_index(closed=closed)\n assert index.hasnans is False\n\n result = index.isna()\n expected = np.zeros(len(index), dtype=bool)\n tm.assert_numpy_array_equal(result, expected)\n\n result = index.notna()\n expected = np.ones(len(index), dtype=bool)\n tm.assert_numpy_array_equal(result, expected)\n\n index = self.create_index_with_nan(closed=closed)\n assert index.hasnans is True\n\n result = index.isna()\n expected = np.array([False, True] + [False] * (len(index) - 2))\n tm.assert_numpy_array_equal(result, expected)\n\n result = index.notna()\n expected = np.array([True, False] + [True] * (len(index) - 2))\n tm.assert_numpy_array_equal(result, expected)\n\n def test_copy(self, closed):\n expected = self.create_index(closed=closed)\n\n result = expected.copy()\n assert result.equals(expected)\n\n result = expected.copy(deep=True)\n assert result.equals(expected)\n assert result.left is not expected.left\n\n def test_ensure_copied_data(self, closed):\n # exercise the copy flag in the constructor\n\n # not copying\n index = self.create_index(closed=closed)\n result = IntervalIndex(index, copy=False)\n tm.assert_numpy_array_equal(\n index.left.values, result.left.values, check_same="same"\n )\n tm.assert_numpy_array_equal(\n index.right.values, result.right.values, check_same="same"\n )\n\n # by-definition make a copy\n result = IntervalIndex(np.array(index), copy=False)\n tm.assert_numpy_array_equal(\n index.left.values, result.left.values, check_same="copy"\n )\n tm.assert_numpy_array_equal(\n index.right.values, result.right.values, check_same="copy"\n )\n\n def test_delete(self, closed):\n breaks = np.arange(1, 11, dtype=np.int64)\n expected = IntervalIndex.from_breaks(breaks, closed=closed)\n result = self.create_index(closed=closed).delete(0)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "data",\n [\n interval_range(0, periods=10, closed="neither"),\n interval_range(1.7, periods=8, freq=2.5, closed="both"),\n interval_range(Timestamp("20170101"), periods=12, closed="left"),\n interval_range(Timedelta("1 day"), periods=6, closed="right"),\n ],\n )\n def test_insert(self, data):\n item = data[0]\n idx_item = IntervalIndex([item])\n\n # start\n expected = idx_item.append(data)\n result = data.insert(0, item)\n tm.assert_index_equal(result, expected)\n\n # end\n expected = data.append(idx_item)\n result = data.insert(len(data), item)\n tm.assert_index_equal(result, expected)\n\n # mid\n expected = data[:3].append(idx_item).append(data[3:])\n result = data.insert(3, item)\n tm.assert_index_equal(result, expected)\n\n # invalid type\n res = data.insert(1, "foo")\n expected = data.astype(object).insert(1, "foo")\n tm.assert_index_equal(res, expected)\n\n msg = "can only insert Interval objects and NA into an IntervalArray"\n with pytest.raises(TypeError, match=msg):\n data._data.insert(1, "foo")\n\n # invalid closed\n msg = "'value.closed' is 'left', expected 'right'."\n for closed in {"left", "right", "both", "neither"} - {item.closed}:\n msg = f"'value.closed' is '{closed}', expected '{item.closed}'."\n bad_item = Interval(item.left, item.right, closed=closed)\n res = data.insert(1, bad_item)\n expected = data.astype(object).insert(1, bad_item)\n tm.assert_index_equal(res, expected)\n with pytest.raises(ValueError, match=msg):\n data._data.insert(1, bad_item)\n\n # GH 18295 (test missing)\n na_idx = IntervalIndex([np.nan], closed=data.closed)\n for na in [np.nan, None, pd.NA]:\n expected = data[:1].append(na_idx).append(data[1:])\n result = data.insert(1, na)\n tm.assert_index_equal(result, expected)\n\n if data.left.dtype.kind not in ["m", "M"]:\n # trying to insert pd.NaT into a numeric-dtyped Index should cast\n expected = data.astype(object).insert(1, pd.NaT)\n\n msg = "can only insert Interval objects and NA into an IntervalArray"\n with pytest.raises(TypeError, match=msg):\n data._data.insert(1, pd.NaT)\n\n result = data.insert(1, pd.NaT)\n tm.assert_index_equal(result, expected)\n\n def test_is_unique_interval(self, closed):\n """\n Interval specific tests for is_unique in addition to base class tests\n """\n # unique overlapping - distinct endpoints\n idx = IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], closed=closed)\n assert idx.is_unique is True\n\n # unique overlapping - shared endpoints\n idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)\n assert idx.is_unique is True\n\n # unique nested\n idx = IntervalIndex.from_tuples([(-1, 1), (-2, 2)], closed=closed)\n assert idx.is_unique is True\n\n # unique NaN\n idx = IntervalIndex.from_tuples([(np.nan, np.nan)], closed=closed)\n assert idx.is_unique is True\n\n # non-unique NaN\n idx = IntervalIndex.from_tuples(\n [(np.nan, np.nan), (np.nan, np.nan)], closed=closed\n )\n assert idx.is_unique is False\n\n def test_monotonic(self, closed):\n # increasing non-overlapping\n idx = IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)], closed=closed)\n assert idx.is_monotonic_increasing is True\n assert idx._is_strictly_monotonic_increasing is True\n assert idx.is_monotonic_decreasing is False\n assert idx._is_strictly_monotonic_decreasing is False\n\n # decreasing non-overlapping\n idx = IntervalIndex.from_tuples([(4, 5), (2, 3), (1, 2)], closed=closed)\n assert idx.is_monotonic_increasing is False\n assert idx._is_strictly_monotonic_increasing is False\n assert idx.is_monotonic_decreasing is True\n assert idx._is_strictly_monotonic_decreasing is True\n\n # unordered non-overlapping\n idx = IntervalIndex.from_tuples([(0, 1), (4, 5), (2, 3)], closed=closed)\n assert idx.is_monotonic_increasing is False\n assert idx._is_strictly_monotonic_increasing is False\n assert idx.is_monotonic_decreasing is False\n assert idx._is_strictly_monotonic_decreasing is False\n\n # increasing overlapping\n idx = IntervalIndex.from_tuples([(0, 2), (0.5, 2.5), (1, 3)], closed=closed)\n assert idx.is_monotonic_increasing is True\n assert idx._is_strictly_monotonic_increasing is True\n assert idx.is_monotonic_decreasing is False\n assert idx._is_strictly_monotonic_decreasing is False\n\n # decreasing overlapping\n idx = IntervalIndex.from_tuples([(1, 3), (0.5, 2.5), (0, 2)], closed=closed)\n assert idx.is_monotonic_increasing is False\n assert idx._is_strictly_monotonic_increasing is False\n assert idx.is_monotonic_decreasing is True\n assert idx._is_strictly_monotonic_decreasing is True\n\n # unordered overlapping\n idx = IntervalIndex.from_tuples([(0.5, 2.5), (0, 2), (1, 3)], closed=closed)\n assert idx.is_monotonic_increasing is False\n assert idx._is_strictly_monotonic_increasing is False\n assert idx.is_monotonic_decreasing is False\n assert idx._is_strictly_monotonic_decreasing is False\n\n # increasing overlapping shared endpoints\n idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)\n assert idx.is_monotonic_increasing is True\n assert idx._is_strictly_monotonic_increasing is True\n assert idx.is_monotonic_decreasing is False\n assert idx._is_strictly_monotonic_decreasing is False\n\n # decreasing overlapping shared endpoints\n idx = IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)], closed=closed)\n assert idx.is_monotonic_increasing is False\n assert idx._is_strictly_monotonic_increasing is False\n assert idx.is_monotonic_decreasing is True\n assert idx._is_strictly_monotonic_decreasing is True\n\n # stationary\n idx = IntervalIndex.from_tuples([(0, 1), (0, 1)], closed=closed)\n assert idx.is_monotonic_increasing is True\n assert idx._is_strictly_monotonic_increasing is False\n assert idx.is_monotonic_decreasing is True\n assert idx._is_strictly_monotonic_decreasing is False\n\n # empty\n idx = IntervalIndex([], closed=closed)\n assert idx.is_monotonic_increasing is True\n assert idx._is_strictly_monotonic_increasing is True\n assert idx.is_monotonic_decreasing is True\n assert idx._is_strictly_monotonic_decreasing is True\n\n def test_is_monotonic_with_nans(self):\n # GH#41831\n index = IntervalIndex([np.nan, np.nan])\n\n assert not index.is_monotonic_increasing\n assert not index._is_strictly_monotonic_increasing\n assert not index.is_monotonic_increasing\n assert not index._is_strictly_monotonic_decreasing\n assert not index.is_monotonic_decreasing\n\n @pytest.mark.parametrize(\n "breaks",\n [\n date_range("20180101", periods=4),\n date_range("20180101", periods=4, tz="US/Eastern"),\n timedelta_range("0 days", periods=4),\n ],\n ids=lambda x: str(x.dtype),\n )\n def test_maybe_convert_i8(self, breaks):\n # GH 20636\n index = IntervalIndex.from_breaks(breaks)\n\n # intervalindex\n result = index._maybe_convert_i8(index)\n expected = IntervalIndex.from_breaks(breaks.asi8)\n tm.assert_index_equal(result, expected)\n\n # interval\n interval = Interval(breaks[0], breaks[1])\n result = index._maybe_convert_i8(interval)\n expected = Interval(breaks[0]._value, breaks[1]._value)\n assert result == expected\n\n # datetimelike index\n result = index._maybe_convert_i8(breaks)\n expected = Index(breaks.asi8)\n tm.assert_index_equal(result, expected)\n\n # datetimelike scalar\n result = index._maybe_convert_i8(breaks[0])\n expected = breaks[0]._value\n assert result == expected\n\n # list-like of datetimelike scalars\n result = index._maybe_convert_i8(list(breaks))\n expected = Index(breaks.asi8)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "breaks",\n [date_range("2018-01-01", periods=5), timedelta_range("0 days", periods=5)],\n )\n def test_maybe_convert_i8_nat(self, breaks):\n # GH 20636\n index = IntervalIndex.from_breaks(breaks)\n\n to_convert = breaks._constructor([pd.NaT] * 3).as_unit("ns")\n expected = Index([np.nan] * 3, dtype=np.float64)\n result = index._maybe_convert_i8(to_convert)\n tm.assert_index_equal(result, expected)\n\n to_convert = to_convert.insert(0, breaks[0])\n expected = expected.insert(0, float(breaks[0]._value))\n result = index._maybe_convert_i8(to_convert)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "make_key",\n [lambda breaks: breaks, list],\n ids=["lambda", "list"],\n )\n def test_maybe_convert_i8_numeric(self, make_key, any_real_numpy_dtype):\n # GH 20636\n breaks = np.arange(5, dtype=any_real_numpy_dtype)\n index = IntervalIndex.from_breaks(breaks)\n key = make_key(breaks)\n\n result = index._maybe_convert_i8(key)\n kind = breaks.dtype.kind\n expected_dtype = {"i": np.int64, "u": np.uint64, "f": np.float64}[kind]\n expected = Index(key, dtype=expected_dtype)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "make_key",\n [\n IntervalIndex.from_breaks,\n lambda breaks: Interval(breaks[0], breaks[1]),\n lambda breaks: breaks[0],\n ],\n ids=["IntervalIndex", "Interval", "scalar"],\n )\n def test_maybe_convert_i8_numeric_identical(self, make_key, any_real_numpy_dtype):\n # GH 20636\n breaks = np.arange(5, dtype=any_real_numpy_dtype)\n index = IntervalIndex.from_breaks(breaks)\n key = make_key(breaks)\n\n # test if _maybe_convert_i8 won't change key if an Interval or IntervalIndex\n result = index._maybe_convert_i8(key)\n assert result is key\n\n @pytest.mark.parametrize(\n "breaks1, breaks2",\n permutations(\n [\n date_range("20180101", periods=4),\n date_range("20180101", periods=4, tz="US/Eastern"),\n timedelta_range("0 days", periods=4),\n ],\n 2,\n ),\n ids=lambda x: str(x.dtype),\n )\n @pytest.mark.parametrize(\n "make_key",\n [\n IntervalIndex.from_breaks,\n lambda breaks: Interval(breaks[0], breaks[1]),\n lambda breaks: breaks,\n lambda breaks: breaks[0],\n list,\n ],\n ids=["IntervalIndex", "Interval", "Index", "scalar", "list"],\n )\n def test_maybe_convert_i8_errors(self, breaks1, breaks2, make_key):\n # GH 20636\n index = IntervalIndex.from_breaks(breaks1)\n key = make_key(breaks2)\n\n msg = (\n f"Cannot index an IntervalIndex of subtype {breaks1.dtype} with "\n f"values of dtype {breaks2.dtype}"\n )\n msg = re.escape(msg)\n with pytest.raises(ValueError, match=msg):\n index._maybe_convert_i8(key)\n\n def test_contains_method(self):\n # can select values that are IN the range of a value\n i = IntervalIndex.from_arrays([0, 1], [1, 2])\n\n expected = np.array([False, False], dtype="bool")\n actual = i.contains(0)\n tm.assert_numpy_array_equal(actual, expected)\n actual = i.contains(3)\n tm.assert_numpy_array_equal(actual, expected)\n\n expected = np.array([True, False], dtype="bool")\n actual = i.contains(0.5)\n tm.assert_numpy_array_equal(actual, expected)\n actual = i.contains(1)\n tm.assert_numpy_array_equal(actual, expected)\n\n # __contains__ not implemented for "interval in interval", follow\n # that for the contains method for now\n with pytest.raises(\n NotImplementedError, match="contains not implemented for two"\n ):\n i.contains(Interval(0, 1))\n\n def test_dropna(self, closed):\n expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], closed=closed)\n\n ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], closed=closed)\n result = ii.dropna()\n tm.assert_index_equal(result, expected)\n\n ii = IntervalIndex.from_arrays([0, 1, np.nan], [1, 2, np.nan], closed=closed)\n result = ii.dropna()\n tm.assert_index_equal(result, expected)\n\n def test_non_contiguous(self, closed):\n index = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)\n target = [0.5, 1.5, 2.5]\n actual = index.get_indexer(target)\n expected = np.array([0, -1, 1], dtype="intp")\n tm.assert_numpy_array_equal(actual, expected)\n\n assert 1.5 not in index\n\n def test_isin(self, closed):\n index = self.create_index(closed=closed)\n\n expected = np.array([True] + [False] * (len(index) - 1))\n result = index.isin(index[:1])\n tm.assert_numpy_array_equal(result, expected)\n\n result = index.isin([index[0]])\n tm.assert_numpy_array_equal(result, expected)\n\n other = IntervalIndex.from_breaks(np.arange(-2, 10), closed=closed)\n expected = np.array([True] * (len(index) - 1) + [False])\n result = index.isin(other)\n tm.assert_numpy_array_equal(result, expected)\n\n result = index.isin(other.tolist())\n tm.assert_numpy_array_equal(result, expected)\n\n for other_closed in ["right", "left", "both", "neither"]:\n other = self.create_index(closed=other_closed)\n expected = np.repeat(closed == other_closed, len(index))\n result = index.isin(other)\n tm.assert_numpy_array_equal(result, expected)\n\n result = index.isin(other.tolist())\n tm.assert_numpy_array_equal(result, expected)\n\n def test_comparison(self):\n actual = Interval(0, 1) < self.index\n expected = np.array([False, True])\n tm.assert_numpy_array_equal(actual, expected)\n\n actual = Interval(0.5, 1.5) < self.index\n expected = np.array([False, True])\n tm.assert_numpy_array_equal(actual, expected)\n actual = self.index > Interval(0.5, 1.5)\n tm.assert_numpy_array_equal(actual, expected)\n\n actual = self.index == self.index\n expected = np.array([True, True])\n tm.assert_numpy_array_equal(actual, expected)\n actual = self.index <= self.index\n tm.assert_numpy_array_equal(actual, expected)\n actual = self.index >= self.index\n tm.assert_numpy_array_equal(actual, expected)\n\n actual = self.index < self.index\n expected = np.array([False, False])\n tm.assert_numpy_array_equal(actual, expected)\n actual = self.index > self.index\n tm.assert_numpy_array_equal(actual, expected)\n\n actual = self.index == IntervalIndex.from_breaks([0, 1, 2], "left")\n tm.assert_numpy_array_equal(actual, expected)\n\n actual = self.index == self.index.values\n tm.assert_numpy_array_equal(actual, np.array([True, True]))\n actual = self.index.values == self.index\n tm.assert_numpy_array_equal(actual, np.array([True, True]))\n actual = self.index <= self.index.values\n tm.assert_numpy_array_equal(actual, np.array([True, True]))\n actual = self.index != self.index.values\n tm.assert_numpy_array_equal(actual, np.array([False, False]))\n actual = self.index > self.index.values\n tm.assert_numpy_array_equal(actual, np.array([False, False]))\n actual = self.index.values > self.index\n tm.assert_numpy_array_equal(actual, np.array([False, False]))\n\n # invalid comparisons\n actual = self.index == 0\n tm.assert_numpy_array_equal(actual, np.array([False, False]))\n actual = self.index == self.index.left\n tm.assert_numpy_array_equal(actual, np.array([False, False]))\n\n msg = "|".join(\n [\n "not supported between instances of 'int' and '.*.Interval'",\n r"Invalid comparison between dtype=interval\[int64, right\] and ",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n self.index > 0\n with pytest.raises(TypeError, match=msg):\n self.index <= 0\n with pytest.raises(TypeError, match=msg):\n self.index > np.arange(2)\n\n msg = "Lengths must match to compare"\n with pytest.raises(ValueError, match=msg):\n self.index > np.arange(3)\n\n def test_missing_values(self, closed):\n idx = Index(\n [np.nan, Interval(0, 1, closed=closed), Interval(1, 2, closed=closed)]\n )\n idx2 = IntervalIndex.from_arrays([np.nan, 0, 1], [np.nan, 1, 2], closed=closed)\n assert idx.equals(idx2)\n\n msg = (\n "missing values must be missing in the same location both left "\n "and right sides"\n )\n with pytest.raises(ValueError, match=msg):\n IntervalIndex.from_arrays(\n [np.nan, 0, 1], np.array([0, 1, 2]), closed=closed\n )\n\n tm.assert_numpy_array_equal(isna(idx), np.array([True, False, False]))\n\n def test_sort_values(self, closed):\n index = self.create_index(closed=closed)\n\n result = index.sort_values()\n tm.assert_index_equal(result, index)\n\n result = index.sort_values(ascending=False)\n tm.assert_index_equal(result, index[::-1])\n\n # with nan\n index = IntervalIndex([Interval(1, 2), np.nan, Interval(0, 1)])\n\n result = index.sort_values()\n expected = IntervalIndex([Interval(0, 1), Interval(1, 2), np.nan])\n tm.assert_index_equal(result, expected)\n\n result = index.sort_values(ascending=False, na_position="first")\n expected = IntervalIndex([np.nan, Interval(1, 2), Interval(0, 1)])\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("tz", [None, "US/Eastern"])\n def test_datetime(self, tz):\n start = Timestamp("2000-01-01", tz=tz)\n dates = date_range(start=start, periods=10)\n index = IntervalIndex.from_breaks(dates)\n\n # test mid\n start = Timestamp("2000-01-01T12:00", tz=tz)\n expected = date_range(start=start, periods=9)\n tm.assert_index_equal(index.mid, expected)\n\n # __contains__ doesn't check individual points\n assert Timestamp("2000-01-01", tz=tz) not in index\n assert Timestamp("2000-01-01T12", tz=tz) not in index\n assert Timestamp("2000-01-02", tz=tz) not in index\n iv_true = Interval(\n Timestamp("2000-01-02", tz=tz), Timestamp("2000-01-03", tz=tz)\n )\n iv_false = Interval(\n Timestamp("1999-12-31", tz=tz), Timestamp("2000-01-01", tz=tz)\n )\n assert iv_true in index\n assert iv_false not in index\n\n # .contains does check individual points\n assert not index.contains(Timestamp("2000-01-01", tz=tz)).any()\n assert index.contains(Timestamp("2000-01-01T12", tz=tz)).any()\n assert index.contains(Timestamp("2000-01-02", tz=tz)).any()\n\n # test get_indexer\n start = Timestamp("1999-12-31T12:00", tz=tz)\n target = date_range(start=start, periods=7, freq="12h")\n actual = index.get_indexer(target)\n expected = np.array([-1, -1, 0, 0, 1, 1, 2], dtype="intp")\n tm.assert_numpy_array_equal(actual, expected)\n\n start = Timestamp("2000-01-08T18:00", tz=tz)\n target = date_range(start=start, periods=7, freq="6h")\n actual = index.get_indexer(target)\n expected = np.array([7, 7, 8, 8, 8, 8, -1], dtype="intp")\n tm.assert_numpy_array_equal(actual, expected)\n\n def test_append(self, closed):\n index1 = IntervalIndex.from_arrays([0, 1], [1, 2], closed=closed)\n index2 = IntervalIndex.from_arrays([1, 2], [2, 3], closed=closed)\n\n result = index1.append(index2)\n expected = IntervalIndex.from_arrays([0, 1, 1, 2], [1, 2, 2, 3], closed=closed)\n tm.assert_index_equal(result, expected)\n\n result = index1.append([index1, index2])\n expected = IntervalIndex.from_arrays(\n [0, 1, 0, 1, 1, 2], [1, 2, 1, 2, 2, 3], closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n for other_closed in {"left", "right", "both", "neither"} - {closed}:\n index_other_closed = IntervalIndex.from_arrays(\n [0, 1], [1, 2], closed=other_closed\n )\n result = index1.append(index_other_closed)\n expected = index1.astype(object).append(index_other_closed.astype(object))\n tm.assert_index_equal(result, expected)\n\n def test_is_non_overlapping_monotonic(self, closed):\n # Should be True in all cases\n tpls = [(0, 1), (2, 3), (4, 5), (6, 7)]\n idx = IntervalIndex.from_tuples(tpls, closed=closed)\n assert idx.is_non_overlapping_monotonic is True\n\n idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)\n assert idx.is_non_overlapping_monotonic is True\n\n # Should be False in all cases (overlapping)\n tpls = [(0, 2), (1, 3), (4, 5), (6, 7)]\n idx = IntervalIndex.from_tuples(tpls, closed=closed)\n assert idx.is_non_overlapping_monotonic is False\n\n idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)\n assert idx.is_non_overlapping_monotonic is False\n\n # Should be False in all cases (non-monotonic)\n tpls = [(0, 1), (2, 3), (6, 7), (4, 5)]\n idx = IntervalIndex.from_tuples(tpls, closed=closed)\n assert idx.is_non_overlapping_monotonic is False\n\n idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)\n assert idx.is_non_overlapping_monotonic is False\n\n # Should be False for closed='both', otherwise True (GH16560)\n if closed == "both":\n idx = IntervalIndex.from_breaks(range(4), closed=closed)\n assert idx.is_non_overlapping_monotonic is False\n else:\n idx = IntervalIndex.from_breaks(range(4), closed=closed)\n assert idx.is_non_overlapping_monotonic is True\n\n @pytest.mark.parametrize(\n "start, shift, na_value",\n [\n (0, 1, np.nan),\n (Timestamp("2018-01-01"), Timedelta("1 day"), pd.NaT),\n (Timedelta("0 days"), Timedelta("1 day"), pd.NaT),\n ],\n )\n def test_is_overlapping(self, start, shift, na_value, closed):\n # GH 23309\n # see test_interval_tree.py for extensive tests; interface tests here\n\n # non-overlapping\n tuples = [(start + n * shift, start + (n + 1) * shift) for n in (0, 2, 4)]\n index = IntervalIndex.from_tuples(tuples, closed=closed)\n assert index.is_overlapping is False\n\n # non-overlapping with NA\n tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]\n index = IntervalIndex.from_tuples(tuples, closed=closed)\n assert index.is_overlapping is False\n\n # overlapping\n tuples = [(start + n * shift, start + (n + 2) * shift) for n in range(3)]\n index = IntervalIndex.from_tuples(tuples, closed=closed)\n assert index.is_overlapping is True\n\n # overlapping with NA\n tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]\n index = IntervalIndex.from_tuples(tuples, closed=closed)\n assert index.is_overlapping is True\n\n # common endpoints\n tuples = [(start + n * shift, start + (n + 1) * shift) for n in range(3)]\n index = IntervalIndex.from_tuples(tuples, closed=closed)\n result = index.is_overlapping\n expected = closed == "both"\n assert result is expected\n\n # common endpoints with NA\n tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]\n index = IntervalIndex.from_tuples(tuples, closed=closed)\n result = index.is_overlapping\n assert result is expected\n\n # intervals with duplicate left values\n a = [10, 15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85]\n b = [15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90]\n index = IntervalIndex.from_arrays(a, b, closed="right")\n result = index.is_overlapping\n assert result is False\n\n @pytest.mark.parametrize(\n "tuples",\n [\n list(zip(range(10), range(1, 11))),\n list(\n zip(\n date_range("20170101", periods=10),\n date_range("20170101", periods=10),\n )\n ),\n list(\n zip(\n timedelta_range("0 days", periods=10),\n timedelta_range("1 day", periods=10),\n )\n ),\n ],\n )\n def test_to_tuples(self, tuples):\n # GH 18756\n idx = IntervalIndex.from_tuples(tuples)\n result = idx.to_tuples()\n expected = Index(com.asarray_tuplesafe(tuples))\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "tuples",\n [\n list(zip(range(10), range(1, 11))) + [np.nan],\n list(\n zip(\n date_range("20170101", periods=10),\n date_range("20170101", periods=10),\n )\n )\n + [np.nan],\n list(\n zip(\n timedelta_range("0 days", periods=10),\n timedelta_range("1 day", periods=10),\n )\n )\n + [np.nan],\n ],\n )\n @pytest.mark.parametrize("na_tuple", [True, False])\n def test_to_tuples_na(self, tuples, na_tuple):\n # GH 18756\n idx = IntervalIndex.from_tuples(tuples)\n result = idx.to_tuples(na_tuple=na_tuple)\n\n # check the non-NA portion\n expected_notna = Index(com.asarray_tuplesafe(tuples[:-1]))\n result_notna = result[:-1]\n tm.assert_index_equal(result_notna, expected_notna)\n\n # check the NA portion\n result_na = result[-1]\n if na_tuple:\n assert isinstance(result_na, tuple)\n assert len(result_na) == 2\n assert all(isna(x) for x in result_na)\n else:\n assert isna(result_na)\n\n def test_nbytes(self):\n # GH 19209\n left = np.arange(0, 4, dtype="i8")\n right = np.arange(1, 5, dtype="i8")\n\n result = IntervalIndex.from_arrays(left, right).nbytes\n expected = 64 # 4 * 8 * 2\n assert result == expected\n\n @pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"])\n def test_set_closed(self, name, closed, new_closed):\n # GH 21670\n index = interval_range(0, 5, closed=closed, name=name)\n result = index.set_closed(new_closed)\n expected = interval_range(0, 5, closed=new_closed, name=name)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("bad_closed", ["foo", 10, "LEFT", True, False])\n def test_set_closed_errors(self, bad_closed):\n # GH 21670\n index = interval_range(0, 5)\n msg = f"invalid option for 'closed': {bad_closed}"\n with pytest.raises(ValueError, match=msg):\n index.set_closed(bad_closed)\n\n def test_is_all_dates(self):\n # GH 23576\n year_2017 = Interval(\n Timestamp("2017-01-01 00:00:00"), Timestamp("2018-01-01 00:00:00")\n )\n year_2017_index = IntervalIndex([year_2017])\n assert not year_2017_index._is_all_dates\n\n\ndef test_dir():\n # GH#27571 dir(interval_index) should not raise\n index = IntervalIndex.from_arrays([0, 1], [1, 2])\n result = dir(index)\n assert "str" not in result\n\n\ndef test_searchsorted_different_argument_classes(listlike_box):\n # https://github.com/pandas-dev/pandas/issues/32762\n values = IntervalIndex([Interval(0, 1), Interval(1, 2)])\n result = values.searchsorted(listlike_box(values))\n expected = np.array([0, 1], dtype=result.dtype)\n tm.assert_numpy_array_equal(result, expected)\n\n result = values._data.searchsorted(listlike_box(values))\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2]\n)\ndef test_searchsorted_invalid_argument(arg):\n values = IntervalIndex([Interval(0, 1), Interval(1, 2)])\n msg = "'<' not supported between instances of 'pandas._libs.interval.Interval' and "\n with pytest.raises(TypeError, match=msg):\n values.searchsorted(arg)\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_interval.py
test_interval.py
Python
34,741
0.95
0.072985
0.093628
react-lib
634
2025-05-15T00:13:40.053056
BSD-3-Clause
true
cbfc149e9cfcdfff860fc3950fb734ee
from datetime import timedelta\n\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.common import is_integer\n\nfrom pandas import (\n DateOffset,\n Interval,\n IntervalIndex,\n Timedelta,\n Timestamp,\n date_range,\n interval_range,\n timedelta_range,\n)\nimport pandas._testing as tm\n\nfrom pandas.tseries.offsets import Day\n\n\n@pytest.fixture(params=[None, "foo"])\ndef name(request):\n return request.param\n\n\nclass TestIntervalRange:\n @pytest.mark.parametrize("freq, periods", [(1, 100), (2.5, 40), (5, 20), (25, 4)])\n def test_constructor_numeric(self, closed, name, freq, periods):\n start, end = 0, 100\n breaks = np.arange(101, step=freq)\n expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)\n\n # defined from start/end/freq\n result = interval_range(\n start=start, end=end, freq=freq, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n # defined from start/periods/freq\n result = interval_range(\n start=start, periods=periods, freq=freq, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n # defined from end/periods/freq\n result = interval_range(\n end=end, periods=periods, freq=freq, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n # GH 20976: linspace behavior defined from start/end/periods\n result = interval_range(\n start=start, end=end, periods=periods, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("tz", [None, "US/Eastern"])\n @pytest.mark.parametrize(\n "freq, periods", [("D", 364), ("2D", 182), ("22D18h", 16), ("ME", 11)]\n )\n def test_constructor_timestamp(self, closed, name, freq, periods, tz):\n start, end = Timestamp("20180101", tz=tz), Timestamp("20181231", tz=tz)\n breaks = date_range(start=start, end=end, freq=freq)\n expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)\n\n # defined from start/end/freq\n result = interval_range(\n start=start, end=end, freq=freq, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n # defined from start/periods/freq\n result = interval_range(\n start=start, periods=periods, freq=freq, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n # defined from end/periods/freq\n result = interval_range(\n end=end, periods=periods, freq=freq, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n # GH 20976: linspace behavior defined from start/end/periods\n if not breaks.freq.n == 1 and tz is None:\n result = interval_range(\n start=start, end=end, periods=periods, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "freq, periods", [("D", 100), ("2D12h", 40), ("5D", 20), ("25D", 4)]\n )\n def test_constructor_timedelta(self, closed, name, freq, periods):\n start, end = Timedelta("0 days"), Timedelta("100 days")\n breaks = timedelta_range(start=start, end=end, freq=freq)\n expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)\n\n # defined from start/end/freq\n result = interval_range(\n start=start, end=end, freq=freq, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n # defined from start/periods/freq\n result = interval_range(\n start=start, periods=periods, freq=freq, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n # defined from end/periods/freq\n result = interval_range(\n end=end, periods=periods, freq=freq, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n # GH 20976: linspace behavior defined from start/end/periods\n result = interval_range(\n start=start, end=end, periods=periods, name=name, closed=closed\n )\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "start, end, freq, expected_endpoint",\n [\n (0, 10, 3, 9),\n (0, 10, 1.5, 9),\n (0.5, 10, 3, 9.5),\n (Timedelta("0D"), Timedelta("10D"), "2D4h", Timedelta("8D16h")),\n (\n Timestamp("2018-01-01"),\n Timestamp("2018-02-09"),\n "MS",\n Timestamp("2018-02-01"),\n ),\n (\n Timestamp("2018-01-01", tz="US/Eastern"),\n Timestamp("2018-01-20", tz="US/Eastern"),\n "5D12h",\n Timestamp("2018-01-17 12:00:00", tz="US/Eastern"),\n ),\n ],\n )\n def test_early_truncation(self, start, end, freq, expected_endpoint):\n # index truncates early if freq causes end to be skipped\n result = interval_range(start=start, end=end, freq=freq)\n result_endpoint = result.right[-1]\n assert result_endpoint == expected_endpoint\n\n @pytest.mark.parametrize(\n "start, end, freq",\n [(0.5, None, None), (None, 4.5, None), (0.5, None, 1.5), (None, 6.5, 1.5)],\n )\n def test_no_invalid_float_truncation(self, start, end, freq):\n # GH 21161\n if freq is None:\n breaks = [0.5, 1.5, 2.5, 3.5, 4.5]\n else:\n breaks = [0.5, 2.0, 3.5, 5.0, 6.5]\n expected = IntervalIndex.from_breaks(breaks)\n\n result = interval_range(start=start, end=end, periods=4, freq=freq)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "start, mid, end",\n [\n (\n Timestamp("2018-03-10", tz="US/Eastern"),\n Timestamp("2018-03-10 23:30:00", tz="US/Eastern"),\n Timestamp("2018-03-12", tz="US/Eastern"),\n ),\n (\n Timestamp("2018-11-03", tz="US/Eastern"),\n Timestamp("2018-11-04 00:30:00", tz="US/Eastern"),\n Timestamp("2018-11-05", tz="US/Eastern"),\n ),\n ],\n )\n def test_linspace_dst_transition(self, start, mid, end):\n # GH 20976: linspace behavior defined from start/end/periods\n # accounts for the hour gained/lost during DST transition\n start = start.as_unit("ns")\n mid = mid.as_unit("ns")\n end = end.as_unit("ns")\n result = interval_range(start=start, end=end, periods=2)\n expected = IntervalIndex.from_breaks([start, mid, end])\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("freq", [2, 2.0])\n @pytest.mark.parametrize("end", [10, 10.0])\n @pytest.mark.parametrize("start", [0, 0.0])\n def test_float_subtype(self, start, end, freq):\n # Has float subtype if any of start/end/freq are float, even if all\n # resulting endpoints can safely be upcast to integers\n\n # defined from start/end/freq\n index = interval_range(start=start, end=end, freq=freq)\n result = index.dtype.subtype\n expected = "int64" if is_integer(start + end + freq) else "float64"\n assert result == expected\n\n # defined from start/periods/freq\n index = interval_range(start=start, periods=5, freq=freq)\n result = index.dtype.subtype\n expected = "int64" if is_integer(start + freq) else "float64"\n assert result == expected\n\n # defined from end/periods/freq\n index = interval_range(end=end, periods=5, freq=freq)\n result = index.dtype.subtype\n expected = "int64" if is_integer(end + freq) else "float64"\n assert result == expected\n\n # GH 20976: linspace behavior defined from start/end/periods\n index = interval_range(start=start, end=end, periods=5)\n result = index.dtype.subtype\n expected = "int64" if is_integer(start + end) else "float64"\n assert result == expected\n\n def test_interval_range_fractional_period(self):\n # float value for periods\n expected = interval_range(start=0, periods=10)\n msg = "Non-integer 'periods' in pd.date_range, .* pd.interval_range"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = interval_range(start=0, periods=10.5)\n tm.assert_index_equal(result, expected)\n\n def test_constructor_coverage(self):\n # equivalent timestamp-like start/end\n start, end = Timestamp("2017-01-01"), Timestamp("2017-01-15")\n expected = interval_range(start=start, end=end)\n\n result = interval_range(start=start.to_pydatetime(), end=end.to_pydatetime())\n tm.assert_index_equal(result, expected)\n\n result = interval_range(start=start.asm8, end=end.asm8)\n tm.assert_index_equal(result, expected)\n\n # equivalent freq with timestamp\n equiv_freq = [\n "D",\n Day(),\n Timedelta(days=1),\n timedelta(days=1),\n DateOffset(days=1),\n ]\n for freq in equiv_freq:\n result = interval_range(start=start, end=end, freq=freq)\n tm.assert_index_equal(result, expected)\n\n # equivalent timedelta-like start/end\n start, end = Timedelta(days=1), Timedelta(days=10)\n expected = interval_range(start=start, end=end)\n\n result = interval_range(start=start.to_pytimedelta(), end=end.to_pytimedelta())\n tm.assert_index_equal(result, expected)\n\n result = interval_range(start=start.asm8, end=end.asm8)\n tm.assert_index_equal(result, expected)\n\n # equivalent freq with timedelta\n equiv_freq = ["D", Day(), Timedelta(days=1), timedelta(days=1)]\n for freq in equiv_freq:\n result = interval_range(start=start, end=end, freq=freq)\n tm.assert_index_equal(result, expected)\n\n def test_errors(self):\n # not enough params\n msg = (\n "Of the four parameters: start, end, periods, and freq, "\n "exactly three must be specified"\n )\n\n with pytest.raises(ValueError, match=msg):\n interval_range(start=0)\n\n with pytest.raises(ValueError, match=msg):\n interval_range(end=5)\n\n with pytest.raises(ValueError, match=msg):\n interval_range(periods=2)\n\n with pytest.raises(ValueError, match=msg):\n interval_range()\n\n # too many params\n with pytest.raises(ValueError, match=msg):\n interval_range(start=0, end=5, periods=6, freq=1.5)\n\n # mixed units\n msg = "start, end, freq need to be type compatible"\n with pytest.raises(TypeError, match=msg):\n interval_range(start=0, end=Timestamp("20130101"), freq=2)\n\n with pytest.raises(TypeError, match=msg):\n interval_range(start=0, end=Timedelta("1 day"), freq=2)\n\n with pytest.raises(TypeError, match=msg):\n interval_range(start=0, end=10, freq="D")\n\n with pytest.raises(TypeError, match=msg):\n interval_range(start=Timestamp("20130101"), end=10, freq="D")\n\n with pytest.raises(TypeError, match=msg):\n interval_range(\n start=Timestamp("20130101"), end=Timedelta("1 day"), freq="D"\n )\n\n with pytest.raises(TypeError, match=msg):\n interval_range(\n start=Timestamp("20130101"), end=Timestamp("20130110"), freq=2\n )\n\n with pytest.raises(TypeError, match=msg):\n interval_range(start=Timedelta("1 day"), end=10, freq="D")\n\n with pytest.raises(TypeError, match=msg):\n interval_range(\n start=Timedelta("1 day"), end=Timestamp("20130110"), freq="D"\n )\n\n with pytest.raises(TypeError, match=msg):\n interval_range(start=Timedelta("1 day"), end=Timedelta("10 days"), freq=2)\n\n # invalid periods\n msg = "periods must be a number, got foo"\n with pytest.raises(TypeError, match=msg):\n interval_range(start=0, periods="foo")\n\n # invalid start\n msg = "start must be numeric or datetime-like, got foo"\n with pytest.raises(ValueError, match=msg):\n interval_range(start="foo", periods=10)\n\n # invalid end\n msg = r"end must be numeric or datetime-like, got \(0, 1\]"\n with pytest.raises(ValueError, match=msg):\n interval_range(end=Interval(0, 1), periods=10)\n\n # invalid freq for datetime-like\n msg = "freq must be numeric or convertible to DateOffset, got foo"\n with pytest.raises(ValueError, match=msg):\n interval_range(start=0, end=10, freq="foo")\n\n with pytest.raises(ValueError, match=msg):\n interval_range(start=Timestamp("20130101"), periods=10, freq="foo")\n\n with pytest.raises(ValueError, match=msg):\n interval_range(end=Timedelta("1 day"), periods=10, freq="foo")\n\n # mixed tz\n start = Timestamp("2017-01-01", tz="US/Eastern")\n end = Timestamp("2017-01-07", tz="US/Pacific")\n msg = "Start and end cannot both be tz-aware with different timezones"\n with pytest.raises(TypeError, match=msg):\n interval_range(start=start, end=end)\n\n def test_float_freq(self):\n # GH 54477\n result = interval_range(0, 1, freq=0.1)\n expected = IntervalIndex.from_breaks([0 + 0.1 * n for n in range(11)])\n tm.assert_index_equal(result, expected)\n\n result = interval_range(0, 1, freq=0.6)\n expected = IntervalIndex.from_breaks([0, 0.6])\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_interval_range.py
test_interval_range.py
Python
13,758
0.95
0.075881
0.118033
node-utils
427
2024-01-24T17:00:35.305923
Apache-2.0
true
311606bfc19dbe45ecf03ded8cf563eb
from itertools import permutations\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.interval import IntervalTree\nfrom pandas.compat import IS64\n\nimport pandas._testing as tm\n\n\ndef skipif_32bit(param):\n """\n Skip parameters in a parametrize on 32bit systems. Specifically used\n here to skip leaf_size parameters related to GH 23440.\n """\n marks = pytest.mark.skipif(not IS64, reason="GH 23440: int type mismatch on 32bit")\n return pytest.param(param, marks=marks)\n\n\n@pytest.fixture(params=["int64", "float64", "uint64"])\ndef dtype(request):\n return request.param\n\n\n@pytest.fixture(params=[skipif_32bit(1), skipif_32bit(2), 10])\ndef leaf_size(request):\n """\n Fixture to specify IntervalTree leaf_size parameter; to be used with the\n tree fixture.\n """\n return request.param\n\n\n@pytest.fixture(\n params=[\n np.arange(5, dtype="int64"),\n np.arange(5, dtype="uint64"),\n np.arange(5, dtype="float64"),\n np.array([0, 1, 2, 3, 4, np.nan], dtype="float64"),\n ]\n)\ndef tree(request, leaf_size):\n left = request.param\n return IntervalTree(left, left + 2, leaf_size=leaf_size)\n\n\nclass TestIntervalTree:\n def test_get_indexer(self, tree):\n result = tree.get_indexer(np.array([1.0, 5.5, 6.5]))\n expected = np.array([0, 4, -1], dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n with pytest.raises(\n KeyError, match="'indexer does not intersect a unique set of intervals'"\n ):\n tree.get_indexer(np.array([3.0]))\n\n @pytest.mark.parametrize(\n "dtype, target_value, target_dtype",\n [("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")],\n )\n def test_get_indexer_overflow(self, dtype, target_value, target_dtype):\n left, right = np.array([0, 1], dtype=dtype), np.array([1, 2], dtype=dtype)\n tree = IntervalTree(left, right)\n\n result = tree.get_indexer(np.array([target_value], dtype=target_dtype))\n expected = np.array([-1], dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_indexer_non_unique(self, tree):\n indexer, missing = tree.get_indexer_non_unique(np.array([1.0, 2.0, 6.5]))\n\n result = indexer[:1]\n expected = np.array([0], dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n result = np.sort(indexer[1:3])\n expected = np.array([0, 1], dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n result = np.sort(indexer[3:])\n expected = np.array([-1], dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n result = missing\n expected = np.array([2], dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n "dtype, target_value, target_dtype",\n [("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")],\n )\n def test_get_indexer_non_unique_overflow(self, dtype, target_value, target_dtype):\n left, right = np.array([0, 2], dtype=dtype), np.array([1, 3], dtype=dtype)\n tree = IntervalTree(left, right)\n target = np.array([target_value], dtype=target_dtype)\n\n result_indexer, result_missing = tree.get_indexer_non_unique(target)\n expected_indexer = np.array([-1], dtype="intp")\n tm.assert_numpy_array_equal(result_indexer, expected_indexer)\n\n expected_missing = np.array([0], dtype="intp")\n tm.assert_numpy_array_equal(result_missing, expected_missing)\n\n def test_duplicates(self, dtype):\n left = np.array([0, 0, 0], dtype=dtype)\n tree = IntervalTree(left, left + 1)\n\n with pytest.raises(\n KeyError, match="'indexer does not intersect a unique set of intervals'"\n ):\n tree.get_indexer(np.array([0.5]))\n\n indexer, missing = tree.get_indexer_non_unique(np.array([0.5]))\n result = np.sort(indexer)\n expected = np.array([0, 1, 2], dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n result = missing\n expected = np.array([], dtype="intp")\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n "leaf_size", [skipif_32bit(1), skipif_32bit(10), skipif_32bit(100), 10000]\n )\n def test_get_indexer_closed(self, closed, leaf_size):\n x = np.arange(1000, dtype="float64")\n found = x.astype("intp")\n not_found = (-1 * np.ones(1000)).astype("intp")\n\n tree = IntervalTree(x, x + 0.5, closed=closed, leaf_size=leaf_size)\n tm.assert_numpy_array_equal(found, tree.get_indexer(x + 0.25))\n\n expected = found if tree.closed_left else not_found\n tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.0))\n\n expected = found if tree.closed_right else not_found\n tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.5))\n\n @pytest.mark.parametrize(\n "left, right, expected",\n [\n (np.array([0, 1, 4], dtype="int64"), np.array([2, 3, 5]), True),\n (np.array([0, 1, 2], dtype="int64"), np.array([5, 4, 3]), True),\n (np.array([0, 1, np.nan]), np.array([5, 4, np.nan]), True),\n (np.array([0, 2, 4], dtype="int64"), np.array([1, 3, 5]), False),\n (np.array([0, 2, np.nan]), np.array([1, 3, np.nan]), False),\n ],\n )\n @pytest.mark.parametrize("order", (list(x) for x in permutations(range(3))))\n def test_is_overlapping(self, closed, order, left, right, expected):\n # GH 23309\n tree = IntervalTree(left[order], right[order], closed=closed)\n result = tree.is_overlapping\n assert result is expected\n\n @pytest.mark.parametrize("order", (list(x) for x in permutations(range(3))))\n def test_is_overlapping_endpoints(self, closed, order):\n """shared endpoints are marked as overlapping"""\n # GH 23309\n left, right = np.arange(3, dtype="int64"), np.arange(1, 4)\n tree = IntervalTree(left[order], right[order], closed=closed)\n result = tree.is_overlapping\n expected = closed == "both"\n assert result is expected\n\n @pytest.mark.parametrize(\n "left, right",\n [\n (np.array([], dtype="int64"), np.array([], dtype="int64")),\n (np.array([0], dtype="int64"), np.array([1], dtype="int64")),\n (np.array([np.nan]), np.array([np.nan])),\n (np.array([np.nan] * 3), np.array([np.nan] * 3)),\n ],\n )\n def test_is_overlapping_trivial(self, closed, left, right):\n # GH 23309\n tree = IntervalTree(left, right, closed=closed)\n assert tree.is_overlapping is False\n\n @pytest.mark.skipif(not IS64, reason="GH 23440")\n def test_construction_overflow(self):\n # GH 25485\n left, right = np.arange(101, dtype="int64"), [np.iinfo(np.int64).max] * 101\n tree = IntervalTree(left, right)\n\n # pivot should be average of left/right medians\n result = tree.root.pivot\n expected = (50 + np.iinfo(np.int64).max) / 2\n assert result == expected\n\n @pytest.mark.parametrize(\n "left, right, expected",\n [\n ([-np.inf, 1.0], [1.0, 2.0], 0.0),\n ([-np.inf, -2.0], [-2.0, -1.0], -2.0),\n ([-2.0, -1.0], [-1.0, np.inf], 0.0),\n ([1.0, 2.0], [2.0, np.inf], 2.0),\n ],\n )\n def test_inf_bound_infinite_recursion(self, left, right, expected):\n # GH 46658\n\n tree = IntervalTree(left * 101, right * 101)\n\n result = tree.root.pivot\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_interval_tree.py
test_interval_tree.py
Python
7,560
0.95
0.096154
0.035714
awesome-app
18
2025-02-06T01:45:29.157425
Apache-2.0
true
59659ed7d9635a27d6f2c7d9e67c7064
import pytest\n\nfrom pandas import (\n IntervalIndex,\n MultiIndex,\n RangeIndex,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture\ndef range_index():\n return RangeIndex(3, name="range_index")\n\n\n@pytest.fixture\ndef interval_index():\n return IntervalIndex.from_tuples(\n [(0.0, 1.0), (1.0, 2.0), (1.5, 2.5)], name="interval_index"\n )\n\n\ndef test_join_overlapping_in_mi_to_same_intervalindex(range_index, interval_index):\n # GH-45661\n multi_index = MultiIndex.from_product([interval_index, range_index])\n result = multi_index.join(interval_index)\n\n tm.assert_index_equal(result, multi_index)\n\n\ndef test_join_overlapping_to_multiindex_with_same_interval(range_index, interval_index):\n # GH-45661\n multi_index = MultiIndex.from_product([interval_index, range_index])\n result = interval_index.join(multi_index)\n\n tm.assert_index_equal(result, multi_index)\n\n\ndef test_join_overlapping_interval_to_another_intervalindex(interval_index):\n # GH-45661\n flipped_interval_index = interval_index[::-1]\n result = interval_index.join(flipped_interval_index)\n\n tm.assert_index_equal(result, interval_index)\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_join.py
test_join.py
Python
1,148
0.95
0.113636
0.1
node-utils
609
2024-05-10T00:57:50.245880
Apache-2.0
true
cfca2ac73c52d2556c73dd5a5eac1179
import pytest\n\nfrom pandas import IntervalIndex\nimport pandas._testing as tm\n\n\nclass TestPickle:\n @pytest.mark.parametrize("closed", ["left", "right", "both"])\n def test_pickle_round_trip_closed(self, closed):\n # https://github.com/pandas-dev/pandas/issues/35658\n idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed)\n result = tm.round_trip_pickle(idx)\n tm.assert_index_equal(result, idx)\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_pickle.py
test_pickle.py
Python
435
0.95
0.153846
0.1
python-kit
9
2024-03-17T00:33:30.770450
GPL-3.0
true
d47457222b8ce2715a2c07ea9b8a2e92
import numpy as np\nimport pytest\n\nfrom pandas import (\n Index,\n IntervalIndex,\n Timestamp,\n interval_range,\n)\nimport pandas._testing as tm\n\n\ndef monotonic_index(start, end, dtype="int64", closed="right"):\n return IntervalIndex.from_breaks(np.arange(start, end, dtype=dtype), closed=closed)\n\n\ndef empty_index(dtype="int64", closed="right"):\n return IntervalIndex(np.array([], dtype=dtype), closed=closed)\n\n\nclass TestIntervalIndex:\n def test_union(self, closed, sort):\n index = monotonic_index(0, 11, closed=closed)\n other = monotonic_index(5, 13, closed=closed)\n\n expected = monotonic_index(0, 13, closed=closed)\n result = index[::-1].union(other, sort=sort)\n if sort in (None, True):\n tm.assert_index_equal(result, expected)\n else:\n tm.assert_index_equal(result.sort_values(), expected)\n\n result = other[::-1].union(index, sort=sort)\n if sort in (None, True):\n tm.assert_index_equal(result, expected)\n else:\n tm.assert_index_equal(result.sort_values(), expected)\n\n tm.assert_index_equal(index.union(index, sort=sort), index)\n tm.assert_index_equal(index.union(index[:1], sort=sort), index)\n\n def test_union_empty_result(self, closed, sort):\n # GH 19101: empty result, same dtype\n index = empty_index(dtype="int64", closed=closed)\n result = index.union(index, sort=sort)\n tm.assert_index_equal(result, index)\n\n # GH 19101: empty result, different numeric dtypes -> common dtype is f8\n other = empty_index(dtype="float64", closed=closed)\n result = index.union(other, sort=sort)\n expected = other\n tm.assert_index_equal(result, expected)\n\n other = index.union(index, sort=sort)\n tm.assert_index_equal(result, expected)\n\n other = empty_index(dtype="uint64", closed=closed)\n result = index.union(other, sort=sort)\n tm.assert_index_equal(result, expected)\n\n result = other.union(index, sort=sort)\n tm.assert_index_equal(result, expected)\n\n def test_intersection(self, closed, sort):\n index = monotonic_index(0, 11, closed=closed)\n other = monotonic_index(5, 13, closed=closed)\n\n expected = monotonic_index(5, 11, closed=closed)\n result = index[::-1].intersection(other, sort=sort)\n if sort in (None, True):\n tm.assert_index_equal(result, expected)\n else:\n tm.assert_index_equal(result.sort_values(), expected)\n\n result = other[::-1].intersection(index, sort=sort)\n if sort in (None, True):\n tm.assert_index_equal(result, expected)\n else:\n tm.assert_index_equal(result.sort_values(), expected)\n\n tm.assert_index_equal(index.intersection(index, sort=sort), index)\n\n # GH 26225: nested intervals\n index = IntervalIndex.from_tuples([(1, 2), (1, 3), (1, 4), (0, 2)])\n other = IntervalIndex.from_tuples([(1, 2), (1, 3)])\n expected = IntervalIndex.from_tuples([(1, 2), (1, 3)])\n result = index.intersection(other)\n tm.assert_index_equal(result, expected)\n\n # GH 26225\n index = IntervalIndex.from_tuples([(0, 3), (0, 2)])\n other = IntervalIndex.from_tuples([(0, 2), (1, 3)])\n expected = IntervalIndex.from_tuples([(0, 2)])\n result = index.intersection(other)\n tm.assert_index_equal(result, expected)\n\n # GH 26225: duplicate nan element\n index = IntervalIndex([np.nan, np.nan])\n other = IntervalIndex([np.nan])\n expected = IntervalIndex([np.nan])\n result = index.intersection(other)\n tm.assert_index_equal(result, expected)\n\n def test_intersection_empty_result(self, closed, sort):\n index = monotonic_index(0, 11, closed=closed)\n\n # GH 19101: empty result, same dtype\n other = monotonic_index(300, 314, closed=closed)\n expected = empty_index(dtype="int64", closed=closed)\n result = index.intersection(other, sort=sort)\n tm.assert_index_equal(result, expected)\n\n # GH 19101: empty result, different numeric dtypes -> common dtype is float64\n other = monotonic_index(300, 314, dtype="float64", closed=closed)\n result = index.intersection(other, sort=sort)\n expected = other[:0]\n tm.assert_index_equal(result, expected)\n\n other = monotonic_index(300, 314, dtype="uint64", closed=closed)\n result = index.intersection(other, sort=sort)\n tm.assert_index_equal(result, expected)\n\n def test_intersection_duplicates(self):\n # GH#38743\n index = IntervalIndex.from_tuples([(1, 2), (1, 2), (2, 3), (3, 4)])\n other = IntervalIndex.from_tuples([(1, 2), (2, 3)])\n expected = IntervalIndex.from_tuples([(1, 2), (2, 3)])\n result = index.intersection(other)\n tm.assert_index_equal(result, expected)\n\n def test_difference(self, closed, sort):\n index = IntervalIndex.from_arrays([1, 0, 3, 2], [1, 2, 3, 4], closed=closed)\n result = index.difference(index[:1], sort=sort)\n expected = index[1:]\n if sort is None:\n expected = expected.sort_values()\n tm.assert_index_equal(result, expected)\n\n # GH 19101: empty result, same dtype\n result = index.difference(index, sort=sort)\n expected = empty_index(dtype="int64", closed=closed)\n tm.assert_index_equal(result, expected)\n\n # GH 19101: empty result, different dtypes\n other = IntervalIndex.from_arrays(\n index.left.astype("float64"), index.right, closed=closed\n )\n result = index.difference(other, sort=sort)\n tm.assert_index_equal(result, expected)\n\n def test_symmetric_difference(self, closed, sort):\n index = monotonic_index(0, 11, closed=closed)\n result = index[1:].symmetric_difference(index[:-1], sort=sort)\n expected = IntervalIndex([index[0], index[-1]])\n if sort in (None, True):\n tm.assert_index_equal(result, expected)\n else:\n tm.assert_index_equal(result.sort_values(), expected)\n\n # GH 19101: empty result, same dtype\n result = index.symmetric_difference(index, sort=sort)\n expected = empty_index(dtype="int64", closed=closed)\n if sort in (None, True):\n tm.assert_index_equal(result, expected)\n else:\n tm.assert_index_equal(result.sort_values(), expected)\n\n # GH 19101: empty result, different dtypes\n other = IntervalIndex.from_arrays(\n index.left.astype("float64"), index.right, closed=closed\n )\n result = index.symmetric_difference(other, sort=sort)\n expected = empty_index(dtype="float64", closed=closed)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.filterwarnings("ignore:'<' not supported between:RuntimeWarning")\n @pytest.mark.parametrize(\n "op_name", ["union", "intersection", "difference", "symmetric_difference"]\n )\n def test_set_incompatible_types(self, closed, op_name, sort):\n index = monotonic_index(0, 11, closed=closed)\n set_op = getattr(index, op_name)\n\n # TODO: standardize return type of non-union setops type(self vs other)\n # non-IntervalIndex\n if op_name == "difference":\n expected = index\n else:\n expected = getattr(index.astype("O"), op_name)(Index([1, 2, 3]))\n result = set_op(Index([1, 2, 3]), sort=sort)\n tm.assert_index_equal(result, expected)\n\n # mixed closed -> cast to object\n for other_closed in {"right", "left", "both", "neither"} - {closed}:\n other = monotonic_index(0, 11, closed=other_closed)\n expected = getattr(index.astype(object), op_name)(other, sort=sort)\n if op_name == "difference":\n expected = index\n result = set_op(other, sort=sort)\n tm.assert_index_equal(result, expected)\n\n # GH 19016: incompatible dtypes -> cast to object\n other = interval_range(Timestamp("20180101"), periods=9, closed=closed)\n expected = getattr(index.astype(object), op_name)(other, sort=sort)\n if op_name == "difference":\n expected = index\n result = set_op(other, sort=sort)\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\test_setops.py
test_setops.py
Python
8,346
0.95
0.105769
0.093567
awesome-app
111
2024-08-25T05:23:32.671564
BSD-3-Clause
true
73ec52064c1ae290763d4860769d9661
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_astype.cpython-313.pyc
test_astype.cpython-313.pyc
Other
14,754
0.8
0
0
react-lib
447
2025-01-21T22:49:02.852039
GPL-3.0
true
7520193c0ec26b5c00a336b581ef6494
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
29,167
0.95
0.02071
0.002976
node-utils
590
2024-03-19T02:10:07.761997
Apache-2.0
true
2027dc6b808c22c0ddbff365613ba47c
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_equals.cpython-313.pyc
test_equals.cpython-313.pyc
Other
2,429
0.8
0
0
awesome-app
270
2023-11-01T18:49:44.561618
MIT
true
83f9eb8e7f51dd231d230f08180ca3ba
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_formats.cpython-313.pyc
test_formats.cpython-313.pyc
Other
4,775
0.8
0
0.019608
react-lib
361
2023-08-07T05:16:34.841999
MIT
true
d88667b3a788a9176dada5a2c4f9cfb1
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_indexing.cpython-313.pyc
test_indexing.cpython-313.pyc
Other
38,075
0.8
0.008955
0.009146
python-kit
254
2024-05-21T22:27:28.785064
Apache-2.0
true
59091845783e92aa3647ae1df5b32f78
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_interval.cpython-313.pyc
test_interval.cpython-313.pyc
Other
49,573
0.95
0.009615
0.004926
node-utils
332
2023-12-04T08:33:42.428450
GPL-3.0
true
4802fe19c064a91cb498c4f0813f1ac7
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_interval_range.cpython-313.pyc
test_interval_range.cpython-313.pyc
Other
16,254
0.8
0
0
react-lib
344
2023-11-14T08:23:57.011822
Apache-2.0
true
5ff0ba21577739abf5b24a6a4b284569
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_interval_tree.cpython-313.pyc
test_interval_tree.cpython-313.pyc
Other
13,355
0.8
0
0.009524
python-kit
238
2025-04-04T08:07:53.433085
BSD-3-Clause
true
584d11ffb6cfb6541f644eebac643c8c
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_join.cpython-313.pyc
test_join.cpython-313.pyc
Other
1,943
0.7
0
0
node-utils
301
2024-07-05T18:34:53.746639
Apache-2.0
true
bca0b0aa21626489b099f2612044ddb8
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_pickle.cpython-313.pyc
test_pickle.cpython-313.pyc
Other
1,162
0.7
0
0
node-utils
53
2023-11-14T10:20:53.973564
MIT
true
5ada1aaaa825339c031b74caffd7f4a4
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\test_setops.cpython-313.pyc
test_setops.cpython-313.pyc
Other
10,259
0.8
0
0
python-kit
502
2023-07-19T07:06:21.342397
GPL-3.0
true
56fd9271a400196c8709902bef989562
\n\n
.venv\Lib\site-packages\pandas\tests\indexes\interval\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
204
0.7
0
0
vue-tools
787
2024-03-17T15:46:34.054585
Apache-2.0
true
0d9054e0f7fbdf231e496fee7cdb636e
import numpy as np\nimport pytest\n\nfrom pandas import (\n Index,\n MultiIndex,\n)\n\n\n# Note: identical the "multi" entry in the top-level "index" fixture\n@pytest.fixture\ndef idx():\n # a MultiIndex used to test the general functionality of the\n # general functionality of this object\n major_axis = Index(["foo", "bar", "baz", "qux"])\n minor_axis = Index(["one", "two"])\n\n major_codes = np.array([0, 0, 1, 2, 3, 3])\n minor_codes = np.array([0, 1, 0, 1, 0, 1])\n index_names = ["first", "second"]\n mi = MultiIndex(\n levels=[major_axis, minor_axis],\n codes=[major_codes, minor_codes],\n names=index_names,\n verify_integrity=False,\n )\n return mi\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\conftest.py
conftest.py
Python
698
0.95
0.037037
0.130435
awesome-app
658
2024-01-28T08:40:28.986933
BSD-3-Clause
true
2affbd8fe3418515ef52ca6b649957fb
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Index,\n MultiIndex,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\ndef test_infer_objects(idx):\n with pytest.raises(NotImplementedError, match="to_frame"):\n idx.infer_objects()\n\n\ndef test_shift(idx):\n # GH8083 test the base class for shift\n msg = (\n "This method is only implemented for DatetimeIndex, PeriodIndex and "\n "TimedeltaIndex; Got type MultiIndex"\n )\n with pytest.raises(NotImplementedError, match=msg):\n idx.shift(1)\n with pytest.raises(NotImplementedError, match=msg):\n idx.shift(1, 2)\n\n\ndef test_groupby(idx):\n groups = idx.groupby(np.array([1, 1, 1, 2, 2, 2]))\n labels = idx.tolist()\n exp = {1: labels[:3], 2: labels[3:]}\n tm.assert_dict_equal(groups, exp)\n\n # GH5620\n groups = idx.groupby(idx)\n exp = {key: [key] for key in idx}\n tm.assert_dict_equal(groups, exp)\n\n\ndef test_truncate_multiindex():\n # GH 34564 for MultiIndex level names check\n major_axis = Index(list(range(4)))\n minor_axis = Index(list(range(2)))\n\n major_codes = np.array([0, 0, 1, 2, 3, 3])\n minor_codes = np.array([0, 1, 0, 1, 0, 1])\n\n index = MultiIndex(\n levels=[major_axis, minor_axis],\n codes=[major_codes, minor_codes],\n names=["L1", "L2"],\n )\n\n result = index.truncate(before=1)\n assert "foo" not in result.levels[0]\n assert 1 in result.levels[0]\n assert index.names == result.names\n\n result = index.truncate(after=1)\n assert 2 not in result.levels[0]\n assert 1 in result.levels[0]\n assert index.names == result.names\n\n result = index.truncate(before=1, after=2)\n assert len(result.levels[0]) == 2\n assert index.names == result.names\n\n msg = "after < before"\n with pytest.raises(ValueError, match=msg):\n index.truncate(3, 1)\n\n\n# TODO: reshape\n\n\ndef test_reorder_levels(idx):\n # this blows up\n with pytest.raises(IndexError, match="^Too many levels"):\n idx.reorder_levels([2, 1, 0])\n\n\ndef test_numpy_repeat():\n reps = 2\n numbers = [1, 2, 3]\n names = np.array(["foo", "bar"])\n\n m = MultiIndex.from_product([numbers, names], names=names)\n expected = MultiIndex.from_product([numbers, names.repeat(reps)], names=names)\n tm.assert_index_equal(np.repeat(m, reps), expected)\n\n msg = "the 'axis' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.repeat(m, reps, axis=1)\n\n\ndef test_append_mixed_dtypes():\n # GH 13660\n dti = date_range("2011-01-01", freq="ME", periods=3)\n dti_tz = date_range("2011-01-01", freq="ME", periods=3, tz="US/Eastern")\n pi = period_range("2011-01", freq="M", periods=3)\n\n mi = MultiIndex.from_arrays(\n [[1, 2, 3], [1.1, np.nan, 3.3], ["a", "b", "c"], dti, dti_tz, pi]\n )\n assert mi.nlevels == 6\n\n res = mi.append(mi)\n exp = MultiIndex.from_arrays(\n [\n [1, 2, 3, 1, 2, 3],\n [1.1, np.nan, 3.3, 1.1, np.nan, 3.3],\n ["a", "b", "c", "a", "b", "c"],\n dti.append(dti),\n dti_tz.append(dti_tz),\n pi.append(pi),\n ]\n )\n tm.assert_index_equal(res, exp)\n\n other = MultiIndex.from_arrays(\n [\n ["x", "y", "z"],\n ["x", "y", "z"],\n ["x", "y", "z"],\n ["x", "y", "z"],\n ["x", "y", "z"],\n ["x", "y", "z"],\n ]\n )\n\n res = mi.append(other)\n exp = MultiIndex.from_arrays(\n [\n [1, 2, 3, "x", "y", "z"],\n [1.1, np.nan, 3.3, "x", "y", "z"],\n ["a", "b", "c", "x", "y", "z"],\n dti.append(Index(["x", "y", "z"])),\n dti_tz.append(Index(["x", "y", "z"])),\n pi.append(Index(["x", "y", "z"])),\n ]\n )\n tm.assert_index_equal(res, exp)\n\n\ndef test_iter(idx):\n result = list(idx)\n expected = [\n ("foo", "one"),\n ("foo", "two"),\n ("bar", "one"),\n ("baz", "two"),\n ("qux", "one"),\n ("qux", "two"),\n ]\n assert result == expected\n\n\ndef test_sub(idx):\n first = idx\n\n # - now raises (previously was set op difference)\n msg = "cannot perform __sub__ with this index type: MultiIndex"\n with pytest.raises(TypeError, match=msg):\n first - idx[-3:]\n with pytest.raises(TypeError, match=msg):\n idx[-3:] - first\n with pytest.raises(TypeError, match=msg):\n idx[-3:] - first.tolist()\n msg = "cannot perform __rsub__ with this index type: MultiIndex"\n with pytest.raises(TypeError, match=msg):\n first.tolist() - idx[-3:]\n\n\ndef test_map(idx):\n # callable\n index = idx\n\n result = index.map(lambda x: x)\n tm.assert_index_equal(result, index)\n\n\n@pytest.mark.parametrize(\n "mapper",\n [\n lambda values, idx: {i: e for e, i in zip(values, idx)},\n lambda values, idx: pd.Series(values, idx),\n ],\n)\ndef test_map_dictlike(idx, mapper):\n identity = mapper(idx.values, idx)\n\n # we don't infer to uint64 dtype for a dict\n if idx.dtype == np.uint64 and isinstance(identity, dict):\n expected = idx.astype("int64")\n else:\n expected = idx\n\n result = idx.map(identity)\n tm.assert_index_equal(result, expected)\n\n # empty mappable\n expected = Index([np.nan] * len(idx))\n result = idx.map(mapper(expected, idx))\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "func",\n [\n np.exp,\n np.exp2,\n np.expm1,\n np.log,\n np.log2,\n np.log10,\n np.log1p,\n np.sqrt,\n np.sin,\n np.cos,\n np.tan,\n np.arcsin,\n np.arccos,\n np.arctan,\n np.sinh,\n np.cosh,\n np.tanh,\n np.arcsinh,\n np.arccosh,\n np.arctanh,\n np.deg2rad,\n np.rad2deg,\n ],\n ids=lambda func: func.__name__,\n)\ndef test_numpy_ufuncs(idx, func):\n # test ufuncs of numpy. see:\n # https://numpy.org/doc/stable/reference/ufuncs.html\n\n expected_exception = TypeError\n msg = (\n "loop of ufunc does not support argument 0 of type tuple which "\n f"has no callable {func.__name__} method"\n )\n with pytest.raises(expected_exception, match=msg):\n func(idx)\n\n\n@pytest.mark.parametrize(\n "func",\n [np.isfinite, np.isinf, np.isnan, np.signbit],\n ids=lambda func: func.__name__,\n)\ndef test_numpy_type_funcs(idx, func):\n msg = (\n f"ufunc '{func.__name__}' not supported for the input types, and the inputs "\n "could not be safely coerced to any supported types according to "\n "the casting rule ''safe''"\n )\n with pytest.raises(TypeError, match=msg):\n func(idx)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_analytics.py
test_analytics.py
Python
6,710
0.95
0.08365
0.055814
node-utils
185
2023-11-06T22:49:42.373811
Apache-2.0
true
605de6141f1a6b35918c2a65ded531a1
import numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import CategoricalDtype\n\nimport pandas._testing as tm\n\n\ndef test_astype(idx):\n expected = idx.copy()\n actual = idx.astype("O")\n tm.assert_copy(actual.levels, expected.levels)\n tm.assert_copy(actual.codes, expected.codes)\n assert actual.names == list(expected.names)\n\n with pytest.raises(TypeError, match="^Setting.*dtype.*object"):\n idx.astype(np.dtype(int))\n\n\n@pytest.mark.parametrize("ordered", [True, False])\ndef test_astype_category(idx, ordered):\n # GH 18630\n msg = "> 1 ndim Categorical are not supported at this time"\n with pytest.raises(NotImplementedError, match=msg):\n idx.astype(CategoricalDtype(ordered=ordered))\n\n if ordered is False:\n # dtype='category' defaults to ordered=False, so only test once\n with pytest.raises(NotImplementedError, match=msg):\n idx.astype("category")\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_astype.py
test_astype.py
Python
924
0.95
0.1
0.090909
react-lib
131
2025-01-19T06:10:26.231360
GPL-3.0
true
1c2cbaf88cb2d2f9275efcf0b7f8b418
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import MultiIndex\nimport pandas._testing as tm\n\n\ndef test_numeric_compat(idx):\n with pytest.raises(TypeError, match="cannot perform __mul__"):\n idx * 1\n\n with pytest.raises(TypeError, match="cannot perform __rmul__"):\n 1 * idx\n\n div_err = "cannot perform __truediv__"\n with pytest.raises(TypeError, match=div_err):\n idx / 1\n\n div_err = div_err.replace(" __", " __r")\n with pytest.raises(TypeError, match=div_err):\n 1 / idx\n\n with pytest.raises(TypeError, match="cannot perform __floordiv__"):\n idx // 1\n\n with pytest.raises(TypeError, match="cannot perform __rfloordiv__"):\n 1 // idx\n\n\n@pytest.mark.parametrize("method", ["all", "any", "__invert__"])\ndef test_logical_compat(idx, method):\n msg = f"cannot perform {method}"\n\n with pytest.raises(TypeError, match=msg):\n getattr(idx, method)()\n\n\ndef test_inplace_mutation_resets_values():\n levels = [["a", "b", "c"], [4]]\n levels2 = [[1, 2, 3], ["a"]]\n codes = [[0, 1, 0, 2, 2, 0], [0, 0, 0, 0, 0, 0]]\n\n mi1 = MultiIndex(levels=levels, codes=codes)\n mi2 = MultiIndex(levels=levels2, codes=codes)\n\n # instantiating MultiIndex should not access/cache _.values\n assert "_values" not in mi1._cache\n assert "_values" not in mi2._cache\n\n vals = mi1.values.copy()\n vals2 = mi2.values.copy()\n\n # accessing .values should cache ._values\n assert mi1._values is mi1._cache["_values"]\n assert mi1.values is mi1._cache["_values"]\n assert isinstance(mi1._cache["_values"], np.ndarray)\n\n # Make sure level setting works\n new_vals = mi1.set_levels(levels2).values\n tm.assert_almost_equal(vals2, new_vals)\n\n # Doesn't drop _values from _cache [implementation detail]\n tm.assert_almost_equal(mi1._cache["_values"], vals)\n\n # ...and values is still same too\n tm.assert_almost_equal(mi1.values, vals)\n\n # Make sure label setting works too\n codes2 = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]\n exp_values = np.empty((6,), dtype=object)\n exp_values[:] = [(1, "a")] * 6\n\n # Must be 1d array of tuples\n assert exp_values.shape == (6,)\n\n new_mi = mi2.set_codes(codes2)\n assert "_values" not in new_mi._cache\n new_values = new_mi.values\n assert "_values" in new_mi._cache\n\n # Shouldn't change cache\n tm.assert_almost_equal(mi2._cache["_values"], vals2)\n\n # Should have correct values\n tm.assert_almost_equal(exp_values, new_values)\n\n\ndef test_boxable_categorical_values():\n cat = pd.Categorical(pd.date_range("2012-01-01", periods=3, freq="h"))\n result = MultiIndex.from_product([["a", "b", "c"], cat]).values\n expected = pd.Series(\n [\n ("a", pd.Timestamp("2012-01-01 00:00:00")),\n ("a", pd.Timestamp("2012-01-01 01:00:00")),\n ("a", pd.Timestamp("2012-01-01 02:00:00")),\n ("b", pd.Timestamp("2012-01-01 00:00:00")),\n ("b", pd.Timestamp("2012-01-01 01:00:00")),\n ("b", pd.Timestamp("2012-01-01 02:00:00")),\n ("c", pd.Timestamp("2012-01-01 00:00:00")),\n ("c", pd.Timestamp("2012-01-01 01:00:00")),\n ("c", pd.Timestamp("2012-01-01 02:00:00")),\n ]\n ).values\n tm.assert_numpy_array_equal(result, expected)\n result = pd.DataFrame({"a": ["a", "b", "c"], "b": cat, "c": np.array(cat)}).values\n expected = pd.DataFrame(\n {\n "a": ["a", "b", "c"],\n "b": [\n pd.Timestamp("2012-01-01 00:00:00"),\n pd.Timestamp("2012-01-01 01:00:00"),\n pd.Timestamp("2012-01-01 02:00:00"),\n ],\n "c": [\n pd.Timestamp("2012-01-01 00:00:00"),\n pd.Timestamp("2012-01-01 01:00:00"),\n pd.Timestamp("2012-01-01 02:00:00"),\n ],\n }\n ).values\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_compat.py
test_compat.py
Python
3,918
0.95
0.032787
0.094737
react-lib
685
2023-11-11T07:15:23.361981
Apache-2.0
true
2f8da18ad3bae464194bb40702e6c98c
from datetime import (\n date,\n datetime,\n)\nimport itertools\n\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.cast import construct_1d_object_array_from_listlike\n\nimport pandas as pd\nfrom pandas import (\n Index,\n MultiIndex,\n Series,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\n\n\ndef test_constructor_single_level():\n result = MultiIndex(\n levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"]\n )\n assert isinstance(result, MultiIndex)\n expected = Index(["foo", "bar", "baz", "qux"], name="first")\n tm.assert_index_equal(result.levels[0], expected)\n assert result.names == ["first"]\n\n\ndef test_constructor_no_levels():\n msg = "non-zero number of levels/codes"\n with pytest.raises(ValueError, match=msg):\n MultiIndex(levels=[], codes=[])\n\n msg = "Must pass both levels and codes"\n with pytest.raises(TypeError, match=msg):\n MultiIndex(levels=[])\n with pytest.raises(TypeError, match=msg):\n MultiIndex(codes=[])\n\n\ndef test_constructor_nonhashable_names():\n # GH 20527\n levels = [[1, 2], ["one", "two"]]\n codes = [[0, 0, 1, 1], [0, 1, 0, 1]]\n names = (["foo"], ["bar"])\n msg = r"MultiIndex\.name must be a hashable type"\n with pytest.raises(TypeError, match=msg):\n MultiIndex(levels=levels, codes=codes, names=names)\n\n # With .rename()\n mi = MultiIndex(\n levels=[[1, 2], ["one", "two"]],\n codes=[[0, 0, 1, 1], [0, 1, 0, 1]],\n names=("foo", "bar"),\n )\n renamed = [["fooo"], ["barr"]]\n with pytest.raises(TypeError, match=msg):\n mi.rename(names=renamed)\n\n # With .set_names()\n with pytest.raises(TypeError, match=msg):\n mi.set_names(names=renamed)\n\n\ndef test_constructor_mismatched_codes_levels(idx):\n codes = [np.array([1]), np.array([2]), np.array([3])]\n levels = ["a"]\n\n msg = "Length of levels and codes must be the same"\n with pytest.raises(ValueError, match=msg):\n MultiIndex(levels=levels, codes=codes)\n\n length_error = (\n r"On level 0, code max \(3\) >= length of level \(1\)\. "\n "NOTE: this index is in an inconsistent state"\n )\n label_error = r"Unequal code lengths: \[4, 2\]"\n code_value_error = r"On level 0, code value \(-2\) < -1"\n\n # important to check that it's looking at the right thing.\n with pytest.raises(ValueError, match=length_error):\n MultiIndex(levels=[["a"], ["b"]], codes=[[0, 1, 2, 3], [0, 3, 4, 1]])\n\n with pytest.raises(ValueError, match=label_error):\n MultiIndex(levels=[["a"], ["b"]], codes=[[0, 0, 0, 0], [0, 0]])\n\n # external API\n with pytest.raises(ValueError, match=length_error):\n idx.copy().set_levels([["a"], ["b"]])\n\n with pytest.raises(ValueError, match=label_error):\n idx.copy().set_codes([[0, 0, 0, 0], [0, 0]])\n\n # test set_codes with verify_integrity=False\n # the setting should not raise any value error\n idx.copy().set_codes(codes=[[0, 0, 0, 0], [0, 0]], verify_integrity=False)\n\n # code value smaller than -1\n with pytest.raises(ValueError, match=code_value_error):\n MultiIndex(levels=[["a"], ["b"]], codes=[[0, -2], [0, 0]])\n\n\ndef test_na_levels():\n # GH26408\n # test if codes are re-assigned value -1 for levels\n # with missing values (NaN, NaT, None)\n result = MultiIndex(\n levels=[[np.nan, None, pd.NaT, 128, 2]], codes=[[0, -1, 1, 2, 3, 4]]\n )\n expected = MultiIndex(\n levels=[[np.nan, None, pd.NaT, 128, 2]], codes=[[-1, -1, -1, -1, 3, 4]]\n )\n tm.assert_index_equal(result, expected)\n\n result = MultiIndex(\n levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[0, -1, 1, 2, 3, 4]]\n )\n expected = MultiIndex(\n levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[-1, -1, 1, -1, 3, -1]]\n )\n tm.assert_index_equal(result, expected)\n\n # verify set_levels and set_codes\n result = MultiIndex(\n levels=[[1, 2, 3, 4, 5]], codes=[[0, -1, 1, 2, 3, 4]]\n ).set_levels([[np.nan, "s", pd.NaT, 128, None]])\n tm.assert_index_equal(result, expected)\n\n result = MultiIndex(\n levels=[[np.nan, "s", pd.NaT, 128, None]], codes=[[1, 2, 2, 2, 2, 2]]\n ).set_codes([[0, -1, 1, 2, 3, 4]])\n tm.assert_index_equal(result, expected)\n\n\ndef test_copy_in_constructor():\n levels = np.array(["a", "b", "c"])\n codes = np.array([1, 1, 2, 0, 0, 1, 1])\n val = codes[0]\n mi = MultiIndex(levels=[levels, levels], codes=[codes, codes], copy=True)\n assert mi.codes[0][0] == val\n codes[0] = 15\n assert mi.codes[0][0] == val\n val = levels[0]\n levels[0] = "PANDA"\n assert mi.levels[0][0] == val\n\n\n# ----------------------------------------------------------------------------\n# from_arrays\n# ----------------------------------------------------------------------------\ndef test_from_arrays(idx):\n arrays = [\n np.asarray(lev).take(level_codes)\n for lev, level_codes in zip(idx.levels, idx.codes)\n ]\n\n # list of arrays as input\n result = MultiIndex.from_arrays(arrays, names=idx.names)\n tm.assert_index_equal(result, idx)\n\n # infer correctly\n result = MultiIndex.from_arrays([[pd.NaT, Timestamp("20130101")], ["a", "b"]])\n assert result.levels[0].equals(Index([Timestamp("20130101")]))\n assert result.levels[1].equals(Index(["a", "b"]))\n\n\ndef test_from_arrays_iterator(idx):\n # GH 18434\n arrays = [\n np.asarray(lev).take(level_codes)\n for lev, level_codes in zip(idx.levels, idx.codes)\n ]\n\n # iterator as input\n result = MultiIndex.from_arrays(iter(arrays), names=idx.names)\n tm.assert_index_equal(result, idx)\n\n # invalid iterator input\n msg = "Input must be a list / sequence of array-likes."\n with pytest.raises(TypeError, match=msg):\n MultiIndex.from_arrays(0)\n\n\ndef test_from_arrays_tuples(idx):\n arrays = tuple(\n tuple(np.asarray(lev).take(level_codes))\n for lev, level_codes in zip(idx.levels, idx.codes)\n )\n\n # tuple of tuples as input\n result = MultiIndex.from_arrays(arrays, names=idx.names)\n tm.assert_index_equal(result, idx)\n\n\n@pytest.mark.parametrize(\n ("idx1", "idx2"),\n [\n (\n pd.period_range("2011-01-01", freq="D", periods=3),\n pd.period_range("2015-01-01", freq="h", periods=3),\n ),\n (\n date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern"),\n date_range("2015-01-01 10:00", freq="h", periods=3, tz="Asia/Tokyo"),\n ),\n (\n pd.timedelta_range("1 days", freq="D", periods=3),\n pd.timedelta_range("2 hours", freq="h", periods=3),\n ),\n ],\n)\ndef test_from_arrays_index_series_period_datetimetz_and_timedelta(idx1, idx2):\n result = MultiIndex.from_arrays([idx1, idx2])\n tm.assert_index_equal(result.get_level_values(0), idx1)\n tm.assert_index_equal(result.get_level_values(1), idx2)\n\n result2 = MultiIndex.from_arrays([Series(idx1), Series(idx2)])\n tm.assert_index_equal(result2.get_level_values(0), idx1)\n tm.assert_index_equal(result2.get_level_values(1), idx2)\n\n tm.assert_index_equal(result, result2)\n\n\ndef test_from_arrays_index_datetimelike_mixed():\n idx1 = date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern")\n idx2 = date_range("2015-01-01 10:00", freq="h", periods=3)\n idx3 = pd.timedelta_range("1 days", freq="D", periods=3)\n idx4 = pd.period_range("2011-01-01", freq="D", periods=3)\n\n result = MultiIndex.from_arrays([idx1, idx2, idx3, idx4])\n tm.assert_index_equal(result.get_level_values(0), idx1)\n tm.assert_index_equal(result.get_level_values(1), idx2)\n tm.assert_index_equal(result.get_level_values(2), idx3)\n tm.assert_index_equal(result.get_level_values(3), idx4)\n\n result2 = MultiIndex.from_arrays(\n [Series(idx1), Series(idx2), Series(idx3), Series(idx4)]\n )\n tm.assert_index_equal(result2.get_level_values(0), idx1)\n tm.assert_index_equal(result2.get_level_values(1), idx2)\n tm.assert_index_equal(result2.get_level_values(2), idx3)\n tm.assert_index_equal(result2.get_level_values(3), idx4)\n\n tm.assert_index_equal(result, result2)\n\n\ndef test_from_arrays_index_series_categorical():\n # GH13743\n idx1 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=False)\n idx2 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=True)\n\n result = MultiIndex.from_arrays([idx1, idx2])\n tm.assert_index_equal(result.get_level_values(0), idx1)\n tm.assert_index_equal(result.get_level_values(1), idx2)\n\n result2 = MultiIndex.from_arrays([Series(idx1), Series(idx2)])\n tm.assert_index_equal(result2.get_level_values(0), idx1)\n tm.assert_index_equal(result2.get_level_values(1), idx2)\n\n result3 = MultiIndex.from_arrays([idx1.values, idx2.values])\n tm.assert_index_equal(result3.get_level_values(0), idx1)\n tm.assert_index_equal(result3.get_level_values(1), idx2)\n\n\ndef test_from_arrays_empty():\n # 0 levels\n msg = "Must pass non-zero number of levels/codes"\n with pytest.raises(ValueError, match=msg):\n MultiIndex.from_arrays(arrays=[])\n\n # 1 level\n result = MultiIndex.from_arrays(arrays=[[]], names=["A"])\n assert isinstance(result, MultiIndex)\n expected = Index([], name="A")\n tm.assert_index_equal(result.levels[0], expected)\n assert result.names == ["A"]\n\n # N levels\n for N in [2, 3]:\n arrays = [[]] * N\n names = list("ABC")[:N]\n result = MultiIndex.from_arrays(arrays=arrays, names=names)\n expected = MultiIndex(levels=[[]] * N, codes=[[]] * N, names=names)\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "invalid_sequence_of_arrays",\n [\n 1,\n [1],\n [1, 2],\n [[1], 2],\n [1, [2]],\n "a",\n ["a"],\n ["a", "b"],\n [["a"], "b"],\n (1,),\n (1, 2),\n ([1], 2),\n (1, [2]),\n "a",\n ("a",),\n ("a", "b"),\n (["a"], "b"),\n [(1,), 2],\n [1, (2,)],\n [("a",), "b"],\n ((1,), 2),\n (1, (2,)),\n (("a",), "b"),\n ],\n)\ndef test_from_arrays_invalid_input(invalid_sequence_of_arrays):\n msg = "Input must be a list / sequence of array-likes"\n with pytest.raises(TypeError, match=msg):\n MultiIndex.from_arrays(arrays=invalid_sequence_of_arrays)\n\n\n@pytest.mark.parametrize(\n "idx1, idx2", [([1, 2, 3], ["a", "b"]), ([], ["a", "b"]), ([1, 2, 3], [])]\n)\ndef test_from_arrays_different_lengths(idx1, idx2):\n # see gh-13599\n msg = "^all arrays must be same length$"\n with pytest.raises(ValueError, match=msg):\n MultiIndex.from_arrays([idx1, idx2])\n\n\ndef test_from_arrays_respects_none_names():\n # GH27292\n a = Series([1, 2, 3], name="foo")\n b = Series(["a", "b", "c"], name="bar")\n\n result = MultiIndex.from_arrays([a, b], names=None)\n expected = MultiIndex(\n levels=[[1, 2, 3], ["a", "b", "c"]], codes=[[0, 1, 2], [0, 1, 2]], names=None\n )\n\n tm.assert_index_equal(result, expected)\n\n\n# ----------------------------------------------------------------------------\n# from_tuples\n# ----------------------------------------------------------------------------\ndef test_from_tuples():\n msg = "Cannot infer number of levels from empty list"\n with pytest.raises(TypeError, match=msg):\n MultiIndex.from_tuples([])\n\n expected = MultiIndex(\n levels=[[1, 3], [2, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"]\n )\n\n # input tuples\n result = MultiIndex.from_tuples(((1, 2), (3, 4)), names=["a", "b"])\n tm.assert_index_equal(result, expected)\n\n\ndef test_from_tuples_iterator():\n # GH 18434\n # input iterator for tuples\n expected = MultiIndex(\n levels=[[1, 3], [2, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"]\n )\n\n result = MultiIndex.from_tuples(zip([1, 3], [2, 4]), names=["a", "b"])\n tm.assert_index_equal(result, expected)\n\n # input non-iterables\n msg = "Input must be a list / sequence of tuple-likes."\n with pytest.raises(TypeError, match=msg):\n MultiIndex.from_tuples(0)\n\n\ndef test_from_tuples_empty():\n # GH 16777\n result = MultiIndex.from_tuples([], names=["a", "b"])\n expected = MultiIndex.from_arrays(arrays=[[], []], names=["a", "b"])\n tm.assert_index_equal(result, expected)\n\n\ndef test_from_tuples_index_values(idx):\n result = MultiIndex.from_tuples(idx)\n assert (result.values == idx.values).all()\n\n\ndef test_tuples_with_name_string():\n # GH 15110 and GH 14848\n\n li = [(0, 0, 1), (0, 1, 0), (1, 0, 0)]\n msg = "Names should be list-like for a MultiIndex"\n with pytest.raises(ValueError, match=msg):\n Index(li, name="abc")\n with pytest.raises(ValueError, match=msg):\n Index(li, name="a")\n\n\ndef test_from_tuples_with_tuple_label():\n # GH 15457\n expected = pd.DataFrame(\n [[2, 1, 2], [4, (1, 2), 3]], columns=["a", "b", "c"]\n ).set_index(["a", "b"])\n idx = MultiIndex.from_tuples([(2, 1), (4, (1, 2))], names=("a", "b"))\n result = pd.DataFrame([2, 3], columns=["c"], index=idx)\n tm.assert_frame_equal(expected, result)\n\n\n# ----------------------------------------------------------------------------\n# from_product\n# ----------------------------------------------------------------------------\ndef test_from_product_empty_zero_levels():\n # 0 levels\n msg = "Must pass non-zero number of levels/codes"\n with pytest.raises(ValueError, match=msg):\n MultiIndex.from_product([])\n\n\ndef test_from_product_empty_one_level():\n result = MultiIndex.from_product([[]], names=["A"])\n expected = Index([], name="A")\n tm.assert_index_equal(result.levels[0], expected)\n assert result.names == ["A"]\n\n\n@pytest.mark.parametrize(\n "first, second", [([], []), (["foo", "bar", "baz"], []), ([], ["a", "b", "c"])]\n)\ndef test_from_product_empty_two_levels(first, second):\n names = ["A", "B"]\n result = MultiIndex.from_product([first, second], names=names)\n expected = MultiIndex(levels=[first, second], codes=[[], []], names=names)\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("N", list(range(4)))\ndef test_from_product_empty_three_levels(N):\n # GH12258\n names = ["A", "B", "C"]\n lvl2 = list(range(N))\n result = MultiIndex.from_product([[], lvl2, []], names=names)\n expected = MultiIndex(levels=[[], lvl2, []], codes=[[], [], []], names=names)\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "invalid_input", [1, [1], [1, 2], [[1], 2], "a", ["a"], ["a", "b"], [["a"], "b"]]\n)\ndef test_from_product_invalid_input(invalid_input):\n msg = r"Input must be a list / sequence of iterables|Input must be list-like"\n with pytest.raises(TypeError, match=msg):\n MultiIndex.from_product(iterables=invalid_input)\n\n\ndef test_from_product_datetimeindex():\n dt_index = date_range("2000-01-01", periods=2)\n mi = MultiIndex.from_product([[1, 2], dt_index])\n etalon = construct_1d_object_array_from_listlike(\n [\n (1, Timestamp("2000-01-01")),\n (1, Timestamp("2000-01-02")),\n (2, Timestamp("2000-01-01")),\n (2, Timestamp("2000-01-02")),\n ]\n )\n tm.assert_numpy_array_equal(mi.values, etalon)\n\n\ndef test_from_product_rangeindex():\n # RangeIndex is preserved by factorize, so preserved in levels\n rng = Index(range(5))\n other = ["a", "b"]\n mi = MultiIndex.from_product([rng, other])\n tm.assert_index_equal(mi._levels[0], rng, exact=True)\n\n\n@pytest.mark.parametrize("ordered", [False, True])\n@pytest.mark.parametrize("f", [lambda x: x, lambda x: Series(x), lambda x: x.values])\ndef test_from_product_index_series_categorical(ordered, f):\n # GH13743\n first = ["foo", "bar"]\n\n idx = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=ordered)\n expected = pd.CategoricalIndex(\n list("abcaab") + list("abcaab"), categories=list("bac"), ordered=ordered\n )\n\n result = MultiIndex.from_product([first, f(idx)])\n tm.assert_index_equal(result.get_level_values(1), expected)\n\n\ndef test_from_product():\n first = ["foo", "bar", "buz"]\n second = ["a", "b", "c"]\n names = ["first", "second"]\n result = MultiIndex.from_product([first, second], names=names)\n\n tuples = [\n ("foo", "a"),\n ("foo", "b"),\n ("foo", "c"),\n ("bar", "a"),\n ("bar", "b"),\n ("bar", "c"),\n ("buz", "a"),\n ("buz", "b"),\n ("buz", "c"),\n ]\n expected = MultiIndex.from_tuples(tuples, names=names)\n\n tm.assert_index_equal(result, expected)\n\n\ndef test_from_product_iterator():\n # GH 18434\n first = ["foo", "bar", "buz"]\n second = ["a", "b", "c"]\n names = ["first", "second"]\n tuples = [\n ("foo", "a"),\n ("foo", "b"),\n ("foo", "c"),\n ("bar", "a"),\n ("bar", "b"),\n ("bar", "c"),\n ("buz", "a"),\n ("buz", "b"),\n ("buz", "c"),\n ]\n expected = MultiIndex.from_tuples(tuples, names=names)\n\n # iterator as input\n result = MultiIndex.from_product(iter([first, second]), names=names)\n tm.assert_index_equal(result, expected)\n\n # Invalid non-iterable input\n msg = "Input must be a list / sequence of iterables."\n with pytest.raises(TypeError, match=msg):\n MultiIndex.from_product(0)\n\n\n@pytest.mark.parametrize(\n "a, b, expected_names",\n [\n (\n Series([1, 2, 3], name="foo"),\n Series(["a", "b"], name="bar"),\n ["foo", "bar"],\n ),\n (Series([1, 2, 3], name="foo"), ["a", "b"], ["foo", None]),\n ([1, 2, 3], ["a", "b"], None),\n ],\n)\ndef test_from_product_infer_names(a, b, expected_names):\n # GH27292\n result = MultiIndex.from_product([a, b])\n expected = MultiIndex(\n levels=[[1, 2, 3], ["a", "b"]],\n codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],\n names=expected_names,\n )\n tm.assert_index_equal(result, expected)\n\n\ndef test_from_product_respects_none_names():\n # GH27292\n a = Series([1, 2, 3], name="foo")\n b = Series(["a", "b"], name="bar")\n\n result = MultiIndex.from_product([a, b], names=None)\n expected = MultiIndex(\n levels=[[1, 2, 3], ["a", "b"]],\n codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],\n names=None,\n )\n tm.assert_index_equal(result, expected)\n\n\ndef test_from_product_readonly():\n # GH#15286 passing read-only array to from_product\n a = np.array(range(3))\n b = ["a", "b"]\n expected = MultiIndex.from_product([a, b])\n\n a.setflags(write=False)\n result = MultiIndex.from_product([a, b])\n tm.assert_index_equal(result, expected)\n\n\ndef test_create_index_existing_name(idx):\n # GH11193, when an existing index is passed, and a new name is not\n # specified, the new index should inherit the previous object name\n index = idx\n index.names = ["foo", "bar"]\n result = Index(index)\n expected = Index(\n Index(\n [\n ("foo", "one"),\n ("foo", "two"),\n ("bar", "one"),\n ("baz", "two"),\n ("qux", "one"),\n ("qux", "two"),\n ],\n dtype="object",\n )\n )\n tm.assert_index_equal(result, expected)\n\n result = Index(index, name="A")\n expected = Index(\n Index(\n [\n ("foo", "one"),\n ("foo", "two"),\n ("bar", "one"),\n ("baz", "two"),\n ("qux", "one"),\n ("qux", "two"),\n ],\n dtype="object",\n ),\n name="A",\n )\n tm.assert_index_equal(result, expected)\n\n\n# ----------------------------------------------------------------------------\n# from_frame\n# ----------------------------------------------------------------------------\ndef test_from_frame():\n # GH 22420\n df = pd.DataFrame(\n [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], columns=["L1", "L2"]\n )\n expected = MultiIndex.from_tuples(\n [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")], names=["L1", "L2"]\n )\n result = MultiIndex.from_frame(df)\n tm.assert_index_equal(expected, result)\n\n\ndef test_from_frame_missing_values_multiIndex():\n # GH 39984\n pa = pytest.importorskip("pyarrow")\n\n df = pd.DataFrame(\n {\n "a": Series([1, 2, None], dtype="Int64"),\n "b": pd.Float64Dtype().__from_arrow__(pa.array([0.2, np.nan, None])),\n }\n )\n multi_indexed = MultiIndex.from_frame(df)\n expected = MultiIndex.from_arrays(\n [\n Series([1, 2, None]).astype("Int64"),\n pd.Float64Dtype().__from_arrow__(pa.array([0.2, np.nan, None])),\n ],\n names=["a", "b"],\n )\n tm.assert_index_equal(multi_indexed, expected)\n\n\n@pytest.mark.parametrize(\n "non_frame",\n [\n Series([1, 2, 3, 4]),\n [1, 2, 3, 4],\n [[1, 2], [3, 4], [5, 6]],\n Index([1, 2, 3, 4]),\n np.array([[1, 2], [3, 4], [5, 6]]),\n 27,\n ],\n)\ndef test_from_frame_error(non_frame):\n # GH 22420\n with pytest.raises(TypeError, match="Input must be a DataFrame"):\n MultiIndex.from_frame(non_frame)\n\n\ndef test_from_frame_dtype_fidelity():\n # GH 22420\n df = pd.DataFrame(\n {\n "dates": date_range("19910905", periods=6, tz="US/Eastern"),\n "a": [1, 1, 1, 2, 2, 2],\n "b": pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True),\n "c": ["x", "x", "y", "z", "x", "y"],\n }\n )\n original_dtypes = df.dtypes.to_dict()\n\n expected_mi = MultiIndex.from_arrays(\n [\n date_range("19910905", periods=6, tz="US/Eastern"),\n [1, 1, 1, 2, 2, 2],\n pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True),\n ["x", "x", "y", "z", "x", "y"],\n ],\n names=["dates", "a", "b", "c"],\n )\n mi = MultiIndex.from_frame(df)\n mi_dtypes = {name: mi.levels[i].dtype for i, name in enumerate(mi.names)}\n\n tm.assert_index_equal(expected_mi, mi)\n assert original_dtypes == mi_dtypes\n\n\n@pytest.mark.parametrize(\n "names_in,names_out", [(None, [("L1", "x"), ("L2", "y")]), (["x", "y"], ["x", "y"])]\n)\ndef test_from_frame_valid_names(names_in, names_out):\n # GH 22420\n df = pd.DataFrame(\n [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]],\n columns=MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]),\n )\n mi = MultiIndex.from_frame(df, names=names_in)\n assert mi.names == names_out\n\n\n@pytest.mark.parametrize(\n "names,expected_error_msg",\n [\n ("bad_input", "Names should be list-like for a MultiIndex"),\n (["a", "b", "c"], "Length of names must match number of levels in MultiIndex"),\n ],\n)\ndef test_from_frame_invalid_names(names, expected_error_msg):\n # GH 22420\n df = pd.DataFrame(\n [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]],\n columns=MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]),\n )\n with pytest.raises(ValueError, match=expected_error_msg):\n MultiIndex.from_frame(df, names=names)\n\n\ndef test_index_equal_empty_iterable():\n # #16844\n a = MultiIndex(levels=[[], []], codes=[[], []], names=["a", "b"])\n b = MultiIndex.from_arrays(arrays=[[], []], names=["a", "b"])\n tm.assert_index_equal(a, b)\n\n\ndef test_raise_invalid_sortorder():\n # Test that the MultiIndex constructor raise when a incorrect sortorder is given\n # GH#28518\n\n levels = [[0, 1], [0, 1, 2]]\n\n # Correct sortorder\n MultiIndex(\n levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], sortorder=2\n )\n\n with pytest.raises(ValueError, match=r".* sortorder 2 with lexsort_depth 1.*"):\n MultiIndex(\n levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=2\n )\n\n with pytest.raises(ValueError, match=r".* sortorder 1 with lexsort_depth 0.*"):\n MultiIndex(\n levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=1\n )\n\n\ndef test_datetimeindex():\n idx1 = pd.DatetimeIndex(\n ["2013-04-01 9:00", "2013-04-02 9:00", "2013-04-03 9:00"] * 2, tz="Asia/Tokyo"\n )\n idx2 = date_range("2010/01/01", periods=6, freq="ME", tz="US/Eastern")\n idx = MultiIndex.from_arrays([idx1, idx2])\n\n expected1 = pd.DatetimeIndex(\n ["2013-04-01 9:00", "2013-04-02 9:00", "2013-04-03 9:00"], tz="Asia/Tokyo"\n )\n\n tm.assert_index_equal(idx.levels[0], expected1)\n tm.assert_index_equal(idx.levels[1], idx2)\n\n # from datetime combos\n # GH 7888\n date1 = np.datetime64("today")\n date2 = datetime.today()\n date3 = Timestamp.today()\n\n for d1, d2 in itertools.product([date1, date2, date3], [date1, date2, date3]):\n index = MultiIndex.from_product([[d1], [d2]])\n assert isinstance(index.levels[0], pd.DatetimeIndex)\n assert isinstance(index.levels[1], pd.DatetimeIndex)\n\n # but NOT date objects, matching Index behavior\n date4 = date.today()\n index = MultiIndex.from_product([[date4], [date2]])\n assert not isinstance(index.levels[0], pd.DatetimeIndex)\n assert isinstance(index.levels[1], pd.DatetimeIndex)\n\n\ndef test_constructor_with_tz():\n index = pd.DatetimeIndex(\n ["2013/01/01 09:00", "2013/01/02 09:00"], name="dt1", tz="US/Pacific"\n )\n columns = pd.DatetimeIndex(\n ["2014/01/01 09:00", "2014/01/02 09:00"], name="dt2", tz="Asia/Tokyo"\n )\n\n result = MultiIndex.from_arrays([index, columns])\n\n assert result.names == ["dt1", "dt2"]\n tm.assert_index_equal(result.levels[0], index)\n tm.assert_index_equal(result.levels[1], columns)\n\n result = MultiIndex.from_arrays([Series(index), Series(columns)])\n\n assert result.names == ["dt1", "dt2"]\n tm.assert_index_equal(result.levels[0], index)\n tm.assert_index_equal(result.levels[1], columns)\n\n\ndef test_multiindex_inference_consistency():\n # check that inference behavior matches the base class\n\n v = date.today()\n\n arr = [v, v]\n\n idx = Index(arr)\n assert idx.dtype == object\n\n mi = MultiIndex.from_arrays([arr])\n lev = mi.levels[0]\n assert lev.dtype == object\n\n mi = MultiIndex.from_product([arr])\n lev = mi.levels[0]\n assert lev.dtype == object\n\n mi = MultiIndex.from_tuples([(x,) for x in arr])\n lev = mi.levels[0]\n assert lev.dtype == object\n\n\ndef test_dtype_representation(using_infer_string):\n # GH#46900\n pmidx = MultiIndex.from_arrays([[1], ["a"]], names=[("a", "b"), ("c", "d")])\n result = pmidx.dtypes\n exp = "object" if not using_infer_string else pd.StringDtype(na_value=np.nan)\n expected = Series(\n ["int64", exp],\n index=MultiIndex.from_tuples([("a", "b"), ("c", "d")]),\n dtype=object,\n )\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_constructors.py
test_constructors.py
Python
26,798
0.95
0.072093
0.100865
awesome-app
674
2024-09-12T08:36:28.329674
MIT
true
ac132415a4fed6d2cf9b1297d73f7ff8
import numpy as np\nimport pytest\n\nfrom pandas.compat.numpy import np_version_gt2\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n MultiIndex,\n)\nimport pandas._testing as tm\n\n\ndef test_to_numpy(idx):\n result = idx.to_numpy()\n exp = idx.values\n tm.assert_numpy_array_equal(result, exp)\n\n\ndef test_array_interface(idx):\n # https://github.com/pandas-dev/pandas/pull/60046\n result = np.asarray(idx)\n expected = np.empty((6,), dtype=object)\n expected[:] = [\n ("foo", "one"),\n ("foo", "two"),\n ("bar", "one"),\n ("baz", "two"),\n ("qux", "one"),\n ("qux", "two"),\n ]\n tm.assert_numpy_array_equal(result, expected)\n\n # it always gives a copy by default, but the values are cached, so results\n # are still sharing memory\n result_copy1 = np.asarray(idx)\n result_copy2 = np.asarray(idx)\n assert np.may_share_memory(result_copy1, result_copy2)\n\n # with explicit copy=True, then it is an actual copy\n result_copy1 = np.array(idx, copy=True)\n result_copy2 = np.array(idx, copy=True)\n assert not np.may_share_memory(result_copy1, result_copy2)\n\n if not np_version_gt2:\n # copy=False semantics are only supported in NumPy>=2.\n return\n\n # for MultiIndex, copy=False is never allowed\n msg = "Starting with NumPy 2.0, the behavior of the 'copy' keyword has changed"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n np.array(idx, copy=False)\n\n\ndef test_to_frame():\n tuples = [(1, "one"), (1, "two"), (2, "one"), (2, "two")]\n\n index = MultiIndex.from_tuples(tuples)\n result = index.to_frame(index=False)\n expected = DataFrame(tuples)\n tm.assert_frame_equal(result, expected)\n\n result = index.to_frame()\n expected.index = index\n tm.assert_frame_equal(result, expected)\n\n tuples = [(1, "one"), (1, "two"), (2, "one"), (2, "two")]\n index = MultiIndex.from_tuples(tuples, names=["first", "second"])\n result = index.to_frame(index=False)\n expected = DataFrame(tuples)\n expected.columns = ["first", "second"]\n tm.assert_frame_equal(result, expected)\n\n result = index.to_frame()\n expected.index = index\n tm.assert_frame_equal(result, expected)\n\n # See GH-22580\n index = MultiIndex.from_tuples(tuples)\n result = index.to_frame(index=False, name=["first", "second"])\n expected = DataFrame(tuples)\n expected.columns = ["first", "second"]\n tm.assert_frame_equal(result, expected)\n\n result = index.to_frame(name=["first", "second"])\n expected.index = index\n expected.columns = ["first", "second"]\n tm.assert_frame_equal(result, expected)\n\n msg = "'name' must be a list / sequence of column names."\n with pytest.raises(TypeError, match=msg):\n index.to_frame(name="first")\n\n msg = "'name' should have same length as number of levels on index."\n with pytest.raises(ValueError, match=msg):\n index.to_frame(name=["first"])\n\n # Tests for datetime index\n index = MultiIndex.from_product([range(5), pd.date_range("20130101", periods=3)])\n result = index.to_frame(index=False)\n expected = DataFrame(\n {\n 0: np.repeat(np.arange(5, dtype="int64"), 3),\n 1: np.tile(pd.date_range("20130101", periods=3), 5),\n }\n )\n tm.assert_frame_equal(result, expected)\n\n result = index.to_frame()\n expected.index = index\n tm.assert_frame_equal(result, expected)\n\n # See GH-22580\n result = index.to_frame(index=False, name=["first", "second"])\n expected = DataFrame(\n {\n "first": np.repeat(np.arange(5, dtype="int64"), 3),\n "second": np.tile(pd.date_range("20130101", periods=3), 5),\n }\n )\n tm.assert_frame_equal(result, expected)\n\n result = index.to_frame(name=["first", "second"])\n expected.index = index\n tm.assert_frame_equal(result, expected)\n\n\ndef test_to_frame_dtype_fidelity():\n # GH 22420\n mi = MultiIndex.from_arrays(\n [\n pd.date_range("19910905", periods=6, tz="US/Eastern"),\n [1, 1, 1, 2, 2, 2],\n pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True),\n ["x", "x", "y", "z", "x", "y"],\n ],\n names=["dates", "a", "b", "c"],\n )\n original_dtypes = {name: mi.levels[i].dtype for i, name in enumerate(mi.names)}\n\n expected_df = DataFrame(\n {\n "dates": pd.date_range("19910905", periods=6, tz="US/Eastern"),\n "a": [1, 1, 1, 2, 2, 2],\n "b": pd.Categorical(["a", "a", "b", "b", "c", "c"], ordered=True),\n "c": ["x", "x", "y", "z", "x", "y"],\n }\n )\n df = mi.to_frame(index=False)\n df_dtypes = df.dtypes.to_dict()\n\n tm.assert_frame_equal(df, expected_df)\n assert original_dtypes == df_dtypes\n\n\ndef test_to_frame_resulting_column_order():\n # GH 22420\n expected = ["z", 0, "a"]\n mi = MultiIndex.from_arrays(\n [["a", "b", "c"], ["x", "y", "z"], ["q", "w", "e"]], names=expected\n )\n result = mi.to_frame().columns.tolist()\n assert result == expected\n\n\ndef test_to_frame_duplicate_labels():\n # GH 45245\n data = [(1, 2), (3, 4)]\n names = ["a", "a"]\n index = MultiIndex.from_tuples(data, names=names)\n with pytest.raises(ValueError, match="Cannot create duplicate column labels"):\n index.to_frame()\n\n result = index.to_frame(allow_duplicates=True)\n expected = DataFrame(data, index=index, columns=names)\n tm.assert_frame_equal(result, expected)\n\n names = [None, 0]\n index = MultiIndex.from_tuples(data, names=names)\n with pytest.raises(ValueError, match="Cannot create duplicate column labels"):\n index.to_frame()\n\n result = index.to_frame(allow_duplicates=True)\n expected = DataFrame(data, index=index, columns=[0, 0])\n tm.assert_frame_equal(result, expected)\n\n\ndef test_to_flat_index(idx):\n expected = pd.Index(\n (\n ("foo", "one"),\n ("foo", "two"),\n ("bar", "one"),\n ("baz", "two"),\n ("qux", "one"),\n ("qux", "two"),\n ),\n tupleize_cols=False,\n )\n result = idx.to_flat_index()\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_conversion.py
test_conversion.py
Python
6,172
0.95
0.054726
0.073171
awesome-app
871
2024-04-04T01:32:11.578069
GPL-3.0
true
cda3df965c7eac8a3055437540f24126
from copy import (\n copy,\n deepcopy,\n)\n\nimport pytest\n\nfrom pandas import MultiIndex\nimport pandas._testing as tm\n\n\ndef assert_multiindex_copied(copy, original):\n # Levels should be (at least, shallow copied)\n tm.assert_copy(copy.levels, original.levels)\n tm.assert_almost_equal(copy.codes, original.codes)\n\n # Labels doesn't matter which way copied\n tm.assert_almost_equal(copy.codes, original.codes)\n assert copy.codes is not original.codes\n\n # Names doesn't matter which way copied\n assert copy.names == original.names\n assert copy.names is not original.names\n\n # Sort order should be copied\n assert copy.sortorder == original.sortorder\n\n\ndef test_copy(idx):\n i_copy = idx.copy()\n\n assert_multiindex_copied(i_copy, idx)\n\n\ndef test_shallow_copy(idx):\n i_copy = idx._view()\n\n assert_multiindex_copied(i_copy, idx)\n\n\ndef test_view(idx):\n i_view = idx.view()\n assert_multiindex_copied(i_view, idx)\n\n\n@pytest.mark.parametrize("func", [copy, deepcopy])\ndef test_copy_and_deepcopy(func):\n idx = MultiIndex(\n levels=[["foo", "bar"], ["fizz", "buzz"]],\n codes=[[0, 0, 0, 1], [0, 0, 1, 1]],\n names=["first", "second"],\n )\n idx_copy = func(idx)\n assert idx_copy is not idx\n assert idx_copy.equals(idx)\n\n\n@pytest.mark.parametrize("deep", [True, False])\ndef test_copy_method(deep):\n idx = MultiIndex(\n levels=[["foo", "bar"], ["fizz", "buzz"]],\n codes=[[0, 0, 0, 1], [0, 0, 1, 1]],\n names=["first", "second"],\n )\n idx_copy = idx.copy(deep=deep)\n assert idx_copy.equals(idx)\n\n\n@pytest.mark.parametrize("deep", [True, False])\n@pytest.mark.parametrize(\n "kwarg, value",\n [\n ("names", ["third", "fourth"]),\n ],\n)\ndef test_copy_method_kwargs(deep, kwarg, value):\n # gh-12309: Check that the "name" argument as well other kwargs are honored\n idx = MultiIndex(\n levels=[["foo", "bar"], ["fizz", "buzz"]],\n codes=[[0, 0, 0, 1], [0, 0, 1, 1]],\n names=["first", "second"],\n )\n idx_copy = idx.copy(**{kwarg: value, "deep": deep})\n assert getattr(idx_copy, kwarg) == value\n\n\ndef test_copy_deep_false_retains_id():\n # GH#47878\n idx = MultiIndex(\n levels=[["foo", "bar"], ["fizz", "buzz"]],\n codes=[[0, 0, 0, 1], [0, 0, 1, 1]],\n names=["first", "second"],\n )\n\n res = idx.copy(deep=False)\n assert res._id is idx._id\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_copy.py
test_copy.py
Python
2,405
0.95
0.083333
0.083333
python-kit
421
2023-07-24T21:24:38.354064
BSD-3-Clause
true
b8d9c219c3314ff7604ee0b724015657
import numpy as np\nimport pytest\n\nfrom pandas.errors import PerformanceWarning\n\nimport pandas as pd\nfrom pandas import (\n Index,\n MultiIndex,\n)\nimport pandas._testing as tm\n\n\ndef test_drop(idx):\n dropped = idx.drop([("foo", "two"), ("qux", "one")])\n\n index = MultiIndex.from_tuples([("foo", "two"), ("qux", "one")])\n dropped2 = idx.drop(index)\n\n expected = idx[[0, 2, 3, 5]]\n tm.assert_index_equal(dropped, expected)\n tm.assert_index_equal(dropped2, expected)\n\n dropped = idx.drop(["bar"])\n expected = idx[[0, 1, 3, 4, 5]]\n tm.assert_index_equal(dropped, expected)\n\n dropped = idx.drop("foo")\n expected = idx[[2, 3, 4, 5]]\n tm.assert_index_equal(dropped, expected)\n\n index = MultiIndex.from_tuples([("bar", "two")])\n with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"):\n idx.drop([("bar", "two")])\n with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"):\n idx.drop(index)\n with pytest.raises(KeyError, match=r"^'two'$"):\n idx.drop(["foo", "two"])\n\n # partially correct argument\n mixed_index = MultiIndex.from_tuples([("qux", "one"), ("bar", "two")])\n with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"):\n idx.drop(mixed_index)\n\n # error='ignore'\n dropped = idx.drop(index, errors="ignore")\n expected = idx[[0, 1, 2, 3, 4, 5]]\n tm.assert_index_equal(dropped, expected)\n\n dropped = idx.drop(mixed_index, errors="ignore")\n expected = idx[[0, 1, 2, 3, 5]]\n tm.assert_index_equal(dropped, expected)\n\n dropped = idx.drop(["foo", "two"], errors="ignore")\n expected = idx[[2, 3, 4, 5]]\n tm.assert_index_equal(dropped, expected)\n\n # mixed partial / full drop\n dropped = idx.drop(["foo", ("qux", "one")])\n expected = idx[[2, 3, 5]]\n tm.assert_index_equal(dropped, expected)\n\n # mixed partial / full drop / error='ignore'\n mixed_index = ["foo", ("qux", "one"), "two"]\n with pytest.raises(KeyError, match=r"^'two'$"):\n idx.drop(mixed_index)\n dropped = idx.drop(mixed_index, errors="ignore")\n expected = idx[[2, 3, 5]]\n tm.assert_index_equal(dropped, expected)\n\n\ndef test_droplevel_with_names(idx):\n index = idx[idx.get_loc("foo")]\n dropped = index.droplevel(0)\n assert dropped.name == "second"\n\n index = MultiIndex(\n levels=[Index(range(4)), Index(range(4)), Index(range(4))],\n codes=[\n np.array([0, 0, 1, 2, 2, 2, 3, 3]),\n np.array([0, 1, 0, 0, 0, 1, 0, 1]),\n np.array([1, 0, 1, 1, 0, 0, 1, 0]),\n ],\n names=["one", "two", "three"],\n )\n dropped = index.droplevel(0)\n assert dropped.names == ("two", "three")\n\n dropped = index.droplevel("two")\n expected = index.droplevel(1)\n assert dropped.equals(expected)\n\n\ndef test_droplevel_list():\n index = MultiIndex(\n levels=[Index(range(4)), Index(range(4)), Index(range(4))],\n codes=[\n np.array([0, 0, 1, 2, 2, 2, 3, 3]),\n np.array([0, 1, 0, 0, 0, 1, 0, 1]),\n np.array([1, 0, 1, 1, 0, 0, 1, 0]),\n ],\n names=["one", "two", "three"],\n )\n\n dropped = index[:2].droplevel(["three", "one"])\n expected = index[:2].droplevel(2).droplevel(0)\n assert dropped.equals(expected)\n\n dropped = index[:2].droplevel([])\n expected = index[:2]\n assert dropped.equals(expected)\n\n msg = (\n "Cannot remove 3 levels from an index with 3 levels: "\n "at least one level must be left"\n )\n with pytest.raises(ValueError, match=msg):\n index[:2].droplevel(["one", "two", "three"])\n\n with pytest.raises(KeyError, match="'Level four not found'"):\n index[:2].droplevel(["one", "four"])\n\n\ndef test_drop_not_lexsorted():\n # GH 12078\n\n # define the lexsorted version of the multi-index\n tuples = [("a", ""), ("b1", "c1"), ("b2", "c2")]\n lexsorted_mi = MultiIndex.from_tuples(tuples, names=["b", "c"])\n assert lexsorted_mi._is_lexsorted()\n\n # and the not-lexsorted version\n df = pd.DataFrame(\n columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]]\n )\n df = df.pivot_table(index="a", columns=["b", "c"], values="d")\n df = df.reset_index()\n not_lexsorted_mi = df.columns\n assert not not_lexsorted_mi._is_lexsorted()\n\n # compare the results\n tm.assert_index_equal(lexsorted_mi, not_lexsorted_mi)\n with tm.assert_produces_warning(PerformanceWarning):\n tm.assert_index_equal(lexsorted_mi.drop("a"), not_lexsorted_mi.drop("a"))\n\n\ndef test_drop_with_nan_in_index(nulls_fixture):\n # GH#18853\n mi = MultiIndex.from_tuples([("blah", nulls_fixture)], names=["name", "date"])\n msg = r"labels \[Timestamp\('2001-01-01 00:00:00'\)\] not found in level"\n with pytest.raises(KeyError, match=msg):\n mi.drop(pd.Timestamp("2001"), level="date")\n\n\n@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning")\ndef test_drop_with_non_monotonic_duplicates():\n # GH#33494\n mi = MultiIndex.from_tuples([(1, 2), (2, 3), (1, 2)])\n result = mi.drop((1, 2))\n expected = MultiIndex.from_tuples([(2, 3)])\n tm.assert_index_equal(result, expected)\n\n\ndef test_single_level_drop_partially_missing_elements():\n # GH 37820\n\n mi = MultiIndex.from_tuples([(1, 2), (2, 2), (3, 2)])\n msg = r"labels \[4\] not found in level"\n with pytest.raises(KeyError, match=msg):\n mi.drop(4, level=0)\n with pytest.raises(KeyError, match=msg):\n mi.drop([1, 4], level=0)\n msg = r"labels \[nan\] not found in level"\n with pytest.raises(KeyError, match=msg):\n mi.drop([np.nan], level=0)\n with pytest.raises(KeyError, match=msg):\n mi.drop([np.nan, 1, 2, 3], level=0)\n\n mi = MultiIndex.from_tuples([(np.nan, 1), (1, 2)])\n msg = r"labels \['a'\] not found in level"\n with pytest.raises(KeyError, match=msg):\n mi.drop([np.nan, 1, "a"], level=0)\n\n\ndef test_droplevel_multiindex_one_level():\n # GH#37208\n index = MultiIndex.from_tuples([(2,)], names=("b",))\n result = index.droplevel([])\n expected = Index([2], name="b")\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_drop.py
test_drop.py
Python
6,089
0.95
0.042105
0.08
awesome-app
382
2023-09-14T16:05:45.819872
GPL-3.0
true
1724c2c4e2099a33d37038377abe18d6
from itertools import product\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs import (\n hashtable,\n index as libindex,\n)\n\nfrom pandas import (\n NA,\n DatetimeIndex,\n Index,\n MultiIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture\ndef idx_dup():\n # compare tests/indexes/multi/conftest.py\n major_axis = Index(["foo", "bar", "baz", "qux"])\n minor_axis = Index(["one", "two"])\n\n major_codes = np.array([0, 0, 1, 0, 1, 1])\n minor_codes = np.array([0, 1, 0, 1, 0, 1])\n index_names = ["first", "second"]\n mi = MultiIndex(\n levels=[major_axis, minor_axis],\n codes=[major_codes, minor_codes],\n names=index_names,\n verify_integrity=False,\n )\n return mi\n\n\n@pytest.mark.parametrize("names", [None, ["first", "second"]])\ndef test_unique(names):\n mi = MultiIndex.from_arrays([[1, 2, 1, 2], [1, 1, 1, 2]], names=names)\n\n res = mi.unique()\n exp = MultiIndex.from_arrays([[1, 2, 2], [1, 1, 2]], names=mi.names)\n tm.assert_index_equal(res, exp)\n\n mi = MultiIndex.from_arrays([list("aaaa"), list("abab")], names=names)\n res = mi.unique()\n exp = MultiIndex.from_arrays([list("aa"), list("ab")], names=mi.names)\n tm.assert_index_equal(res, exp)\n\n mi = MultiIndex.from_arrays([list("aaaa"), list("aaaa")], names=names)\n res = mi.unique()\n exp = MultiIndex.from_arrays([["a"], ["a"]], names=mi.names)\n tm.assert_index_equal(res, exp)\n\n # GH #20568 - empty MI\n mi = MultiIndex.from_arrays([[], []], names=names)\n res = mi.unique()\n tm.assert_index_equal(mi, res)\n\n\ndef test_unique_datetimelike():\n idx1 = DatetimeIndex(\n ["2015-01-01", "2015-01-01", "2015-01-01", "2015-01-01", "NaT", "NaT"]\n )\n idx2 = DatetimeIndex(\n ["2015-01-01", "2015-01-01", "2015-01-02", "2015-01-02", "NaT", "2015-01-01"],\n tz="Asia/Tokyo",\n )\n result = MultiIndex.from_arrays([idx1, idx2]).unique()\n\n eidx1 = DatetimeIndex(["2015-01-01", "2015-01-01", "NaT", "NaT"])\n eidx2 = DatetimeIndex(\n ["2015-01-01", "2015-01-02", "NaT", "2015-01-01"], tz="Asia/Tokyo"\n )\n exp = MultiIndex.from_arrays([eidx1, eidx2])\n tm.assert_index_equal(result, exp)\n\n\n@pytest.mark.parametrize("level", [0, "first", 1, "second"])\ndef test_unique_level(idx, level):\n # GH #17896 - with level= argument\n result = idx.unique(level=level)\n expected = idx.get_level_values(level).unique()\n tm.assert_index_equal(result, expected)\n\n # With already unique level\n mi = MultiIndex.from_arrays([[1, 3, 2, 4], [1, 3, 2, 5]], names=["first", "second"])\n result = mi.unique(level=level)\n expected = mi.get_level_values(level)\n tm.assert_index_equal(result, expected)\n\n # With empty MI\n mi = MultiIndex.from_arrays([[], []], names=["first", "second"])\n result = mi.unique(level=level)\n expected = mi.get_level_values(level)\n tm.assert_index_equal(result, expected)\n\n\ndef test_duplicate_multiindex_codes():\n # GH 17464\n # Make sure that a MultiIndex with duplicate levels throws a ValueError\n msg = r"Level values must be unique: \[[A', ]+\] on level 0"\n with pytest.raises(ValueError, match=msg):\n mi = MultiIndex([["A"] * 10, range(10)], [[0] * 10, range(10)])\n\n # And that using set_levels with duplicate levels fails\n mi = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]])\n msg = r"Level values must be unique: \[[AB', ]+\] on level 0"\n with pytest.raises(ValueError, match=msg):\n mi.set_levels([["A", "B", "A", "A", "B"], [2, 1, 3, -2, 5]])\n\n\n@pytest.mark.parametrize("names", [["a", "b", "a"], [1, 1, 2], [1, "a", 1]])\ndef test_duplicate_level_names(names):\n # GH18872, GH19029\n mi = MultiIndex.from_product([[0, 1]] * 3, names=names)\n assert mi.names == names\n\n # With .rename()\n mi = MultiIndex.from_product([[0, 1]] * 3)\n mi = mi.rename(names)\n assert mi.names == names\n\n # With .rename(., level=)\n mi.rename(names[1], level=1, inplace=True)\n mi = mi.rename([names[0], names[2]], level=[0, 2])\n assert mi.names == names\n\n\ndef test_duplicate_meta_data():\n # GH 10115\n mi = MultiIndex(\n levels=[[0, 1], [0, 1, 2]], codes=[[0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]]\n )\n\n for idx in [\n mi,\n mi.set_names([None, None]),\n mi.set_names([None, "Num"]),\n mi.set_names(["Upper", "Num"]),\n ]:\n assert idx.has_duplicates\n assert idx.drop_duplicates().names == idx.names\n\n\ndef test_has_duplicates(idx, idx_dup):\n # see fixtures\n assert idx.is_unique is True\n assert idx.has_duplicates is False\n assert idx_dup.is_unique is False\n assert idx_dup.has_duplicates is True\n\n mi = MultiIndex(\n levels=[[0, 1], [0, 1, 2]], codes=[[0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]]\n )\n assert mi.is_unique is False\n assert mi.has_duplicates is True\n\n # single instance of NaN\n mi_nan = MultiIndex(\n levels=[["a", "b"], [0, 1]], codes=[[-1, 0, 0, 1, 1], [-1, 0, 1, 0, 1]]\n )\n assert mi_nan.is_unique is True\n assert mi_nan.has_duplicates is False\n\n # multiple instances of NaN\n mi_nan_dup = MultiIndex(\n levels=[["a", "b"], [0, 1]], codes=[[-1, -1, 0, 0, 1, 1], [-1, -1, 0, 1, 0, 1]]\n )\n assert mi_nan_dup.is_unique is False\n assert mi_nan_dup.has_duplicates is True\n\n\ndef test_has_duplicates_from_tuples():\n # GH 9075\n t = [\n ("x", "out", "z", 5, "y", "in", "z", 169),\n ("x", "out", "z", 7, "y", "in", "z", 119),\n ("x", "out", "z", 9, "y", "in", "z", 135),\n ("x", "out", "z", 13, "y", "in", "z", 145),\n ("x", "out", "z", 14, "y", "in", "z", 158),\n ("x", "out", "z", 16, "y", "in", "z", 122),\n ("x", "out", "z", 17, "y", "in", "z", 160),\n ("x", "out", "z", 18, "y", "in", "z", 180),\n ("x", "out", "z", 20, "y", "in", "z", 143),\n ("x", "out", "z", 21, "y", "in", "z", 128),\n ("x", "out", "z", 22, "y", "in", "z", 129),\n ("x", "out", "z", 25, "y", "in", "z", 111),\n ("x", "out", "z", 28, "y", "in", "z", 114),\n ("x", "out", "z", 29, "y", "in", "z", 121),\n ("x", "out", "z", 31, "y", "in", "z", 126),\n ("x", "out", "z", 32, "y", "in", "z", 155),\n ("x", "out", "z", 33, "y", "in", "z", 123),\n ("x", "out", "z", 12, "y", "in", "z", 144),\n ]\n\n mi = MultiIndex.from_tuples(t)\n assert not mi.has_duplicates\n\n\n@pytest.mark.parametrize("nlevels", [4, 8])\n@pytest.mark.parametrize("with_nulls", [True, False])\ndef test_has_duplicates_overflow(nlevels, with_nulls):\n # handle int64 overflow if possible\n # no overflow with 4\n # overflow possible with 8\n codes = np.tile(np.arange(500), 2)\n level = np.arange(500)\n\n if with_nulls: # inject some null values\n codes[500] = -1 # common nan value\n codes = [codes.copy() for i in range(nlevels)]\n for i in range(nlevels):\n codes[i][500 + i - nlevels // 2] = -1\n\n codes += [np.array([-1, 1]).repeat(500)]\n else:\n codes = [codes] * nlevels + [np.arange(2).repeat(500)]\n\n levels = [level] * nlevels + [[0, 1]]\n\n # no dups\n mi = MultiIndex(levels=levels, codes=codes)\n assert not mi.has_duplicates\n\n # with a dup\n if with_nulls:\n\n def f(a):\n return np.insert(a, 1000, a[0])\n\n codes = list(map(f, codes))\n mi = MultiIndex(levels=levels, codes=codes)\n else:\n values = mi.values.tolist()\n mi = MultiIndex.from_tuples(values + [values[0]])\n\n assert mi.has_duplicates\n\n\n@pytest.mark.parametrize(\n "keep, expected",\n [\n ("first", np.array([False, False, False, True, True, False])),\n ("last", np.array([False, True, True, False, False, False])),\n (False, np.array([False, True, True, True, True, False])),\n ],\n)\ndef test_duplicated(idx_dup, keep, expected):\n result = idx_dup.duplicated(keep=keep)\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.arm_slow\ndef test_duplicated_hashtable_impl(keep, monkeypatch):\n # GH 9125\n n, k = 6, 10\n levels = [np.arange(n), [str(i) for i in range(n)], 1000 + np.arange(n)]\n codes = [np.random.default_rng(2).choice(n, k * n) for _ in levels]\n with monkeypatch.context() as m:\n m.setattr(libindex, "_SIZE_CUTOFF", 50)\n mi = MultiIndex(levels=levels, codes=codes)\n\n result = mi.duplicated(keep=keep)\n expected = hashtable.duplicated(mi.values, keep=keep)\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("val", [101, 102])\ndef test_duplicated_with_nan(val):\n # GH5873\n mi = MultiIndex.from_arrays([[101, val], [3.5, np.nan]])\n assert not mi.has_duplicates\n\n tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(2, dtype="bool"))\n\n\n@pytest.mark.parametrize("n", range(1, 6))\n@pytest.mark.parametrize("m", range(1, 5))\ndef test_duplicated_with_nan_multi_shape(n, m):\n # GH5873\n # all possible unique combinations, including nan\n codes = product(range(-1, n), range(-1, m))\n mi = MultiIndex(\n levels=[list("abcde")[:n], list("WXYZ")[:m]],\n codes=np.random.default_rng(2).permutation(list(codes)).T,\n )\n assert len(mi) == (n + 1) * (m + 1)\n assert not mi.has_duplicates\n\n tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(len(mi), dtype="bool"))\n\n\ndef test_duplicated_drop_duplicates():\n # GH#4060\n idx = MultiIndex.from_arrays(([1, 2, 3, 1, 2, 3], [1, 1, 1, 1, 2, 2]))\n\n expected = np.array([False, False, False, True, False, False], dtype=bool)\n duplicated = idx.duplicated()\n tm.assert_numpy_array_equal(duplicated, expected)\n assert duplicated.dtype == bool\n expected = MultiIndex.from_arrays(([1, 2, 3, 2, 3], [1, 1, 1, 2, 2]))\n tm.assert_index_equal(idx.drop_duplicates(), expected)\n\n expected = np.array([True, False, False, False, False, False])\n duplicated = idx.duplicated(keep="last")\n tm.assert_numpy_array_equal(duplicated, expected)\n assert duplicated.dtype == bool\n expected = MultiIndex.from_arrays(([2, 3, 1, 2, 3], [1, 1, 1, 2, 2]))\n tm.assert_index_equal(idx.drop_duplicates(keep="last"), expected)\n\n expected = np.array([True, False, False, True, False, False])\n duplicated = idx.duplicated(keep=False)\n tm.assert_numpy_array_equal(duplicated, expected)\n assert duplicated.dtype == bool\n expected = MultiIndex.from_arrays(([2, 3, 2, 3], [1, 1, 2, 2]))\n tm.assert_index_equal(idx.drop_duplicates(keep=False), expected)\n\n\n@pytest.mark.parametrize(\n "dtype",\n [\n np.complex64,\n np.complex128,\n ],\n)\ndef test_duplicated_series_complex_numbers(dtype):\n # GH 17927\n expected = Series(\n [False, False, False, True, False, False, False, True, False, True],\n dtype=bool,\n )\n result = Series(\n [\n np.nan + np.nan * 1j,\n 0,\n 1j,\n 1j,\n 1,\n 1 + 1j,\n 1 + 2j,\n 1 + 1j,\n np.nan,\n np.nan + np.nan * 1j,\n ],\n dtype=dtype,\n ).duplicated()\n tm.assert_series_equal(result, expected)\n\n\ndef test_midx_unique_ea_dtype():\n # GH#48335\n vals_a = Series([1, 2, NA, NA], dtype="Int64")\n vals_b = np.array([1, 2, 3, 3])\n midx = MultiIndex.from_arrays([vals_a, vals_b], names=["a", "b"])\n result = midx.unique()\n\n exp_vals_a = Series([1, 2, NA], dtype="Int64")\n exp_vals_b = np.array([1, 2, 3])\n expected = MultiIndex.from_arrays([exp_vals_a, exp_vals_b], names=["a", "b"])\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_duplicates.py
test_duplicates.py
Python
11,559
0.95
0.071625
0.094915
react-lib
151
2023-11-02T21:31:25.362189
BSD-3-Clause
true
551a5ec4183513ac77ea05c6150ee4ca
import numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.common import is_any_real_numeric_dtype\n\nimport pandas as pd\nfrom pandas import (\n Index,\n MultiIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\ndef test_equals(idx):\n assert idx.equals(idx)\n assert idx.equals(idx.copy())\n assert idx.equals(idx.astype(object))\n assert idx.equals(idx.to_flat_index())\n assert idx.equals(idx.to_flat_index().astype("category"))\n\n assert not idx.equals(list(idx))\n assert not idx.equals(np.array(idx))\n\n same_values = Index(idx, dtype=object)\n assert idx.equals(same_values)\n assert same_values.equals(idx)\n\n if idx.nlevels == 1:\n # do not test MultiIndex\n assert not idx.equals(Series(idx))\n\n\ndef test_equals_op(idx):\n # GH9947, GH10637\n index_a = idx\n\n n = len(index_a)\n index_b = index_a[0:-1]\n index_c = index_a[0:-1].append(index_a[-2:-1])\n index_d = index_a[0:1]\n with pytest.raises(ValueError, match="Lengths must match"):\n index_a == index_b\n expected1 = np.array([True] * n)\n expected2 = np.array([True] * (n - 1) + [False])\n tm.assert_numpy_array_equal(index_a == index_a, expected1)\n tm.assert_numpy_array_equal(index_a == index_c, expected2)\n\n # test comparisons with numpy arrays\n array_a = np.array(index_a)\n array_b = np.array(index_a[0:-1])\n array_c = np.array(index_a[0:-1].append(index_a[-2:-1]))\n array_d = np.array(index_a[0:1])\n with pytest.raises(ValueError, match="Lengths must match"):\n index_a == array_b\n tm.assert_numpy_array_equal(index_a == array_a, expected1)\n tm.assert_numpy_array_equal(index_a == array_c, expected2)\n\n # test comparisons with Series\n series_a = Series(array_a)\n series_b = Series(array_b)\n series_c = Series(array_c)\n series_d = Series(array_d)\n with pytest.raises(ValueError, match="Lengths must match"):\n index_a == series_b\n\n tm.assert_numpy_array_equal(index_a == series_a, expected1)\n tm.assert_numpy_array_equal(index_a == series_c, expected2)\n\n # cases where length is 1 for one of them\n with pytest.raises(ValueError, match="Lengths must match"):\n index_a == index_d\n with pytest.raises(ValueError, match="Lengths must match"):\n index_a == series_d\n with pytest.raises(ValueError, match="Lengths must match"):\n index_a == array_d\n msg = "Can only compare identically-labeled Series objects"\n with pytest.raises(ValueError, match=msg):\n series_a == series_d\n with pytest.raises(ValueError, match="Lengths must match"):\n series_a == array_d\n\n # comparing with a scalar should broadcast; note that we are excluding\n # MultiIndex because in this case each item in the index is a tuple of\n # length 2, and therefore is considered an array of length 2 in the\n # comparison instead of a scalar\n if not isinstance(index_a, MultiIndex):\n expected3 = np.array([False] * (len(index_a) - 2) + [True, False])\n # assuming the 2nd to last item is unique in the data\n item = index_a[-2]\n tm.assert_numpy_array_equal(index_a == item, expected3)\n tm.assert_series_equal(series_a == item, Series(expected3))\n\n\ndef test_compare_tuple():\n # GH#21517\n mi = MultiIndex.from_product([[1, 2]] * 2)\n\n all_false = np.array([False, False, False, False])\n\n result = mi == mi[0]\n expected = np.array([True, False, False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n result = mi != mi[0]\n tm.assert_numpy_array_equal(result, ~expected)\n\n result = mi < mi[0]\n tm.assert_numpy_array_equal(result, all_false)\n\n result = mi <= mi[0]\n tm.assert_numpy_array_equal(result, expected)\n\n result = mi > mi[0]\n tm.assert_numpy_array_equal(result, ~expected)\n\n result = mi >= mi[0]\n tm.assert_numpy_array_equal(result, ~all_false)\n\n\ndef test_compare_tuple_strs():\n # GH#34180\n\n mi = MultiIndex.from_tuples([("a", "b"), ("b", "c"), ("c", "a")])\n\n result = mi == ("c", "a")\n expected = np.array([False, False, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = mi == ("c",)\n expected = np.array([False, False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_equals_multi(idx):\n assert idx.equals(idx)\n assert not idx.equals(idx.values)\n assert idx.equals(Index(idx.values))\n\n assert idx.equal_levels(idx)\n assert not idx.equals(idx[:-1])\n assert not idx.equals(idx[-1])\n\n # different number of levels\n index = MultiIndex(\n levels=[Index(list(range(4))), Index(list(range(4))), Index(list(range(4)))],\n codes=[\n np.array([0, 0, 1, 2, 2, 2, 3, 3]),\n np.array([0, 1, 0, 0, 0, 1, 0, 1]),\n np.array([1, 0, 1, 1, 0, 0, 1, 0]),\n ],\n )\n\n index2 = MultiIndex(levels=index.levels[:-1], codes=index.codes[:-1])\n assert not index.equals(index2)\n assert not index.equal_levels(index2)\n\n # levels are different\n major_axis = Index(list(range(4)))\n minor_axis = Index(list(range(2)))\n\n major_codes = np.array([0, 0, 1, 2, 2, 3])\n minor_codes = np.array([0, 1, 0, 0, 1, 0])\n\n index = MultiIndex(\n levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]\n )\n assert not idx.equals(index)\n assert not idx.equal_levels(index)\n\n # some of the labels are different\n major_axis = Index(["foo", "bar", "baz", "qux"])\n minor_axis = Index(["one", "two"])\n\n major_codes = np.array([0, 0, 2, 2, 3, 3])\n minor_codes = np.array([0, 1, 0, 1, 0, 1])\n\n index = MultiIndex(\n levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]\n )\n assert not idx.equals(index)\n\n\ndef test_identical(idx):\n mi = idx.copy()\n mi2 = idx.copy()\n assert mi.identical(mi2)\n\n mi = mi.set_names(["new1", "new2"])\n assert mi.equals(mi2)\n assert not mi.identical(mi2)\n\n mi2 = mi2.set_names(["new1", "new2"])\n assert mi.identical(mi2)\n\n mi4 = Index(mi.tolist(), tupleize_cols=False)\n assert not mi.identical(mi4)\n assert mi.equals(mi4)\n\n\ndef test_equals_operator(idx):\n # GH9785\n assert (idx == idx).all()\n\n\ndef test_equals_missing_values():\n # make sure take is not using -1\n i = MultiIndex.from_tuples([(0, pd.NaT), (0, pd.Timestamp("20130101"))])\n result = i[0:1].equals(i[0])\n assert not result\n result = i[1:2].equals(i[1])\n assert not result\n\n\ndef test_equals_missing_values_differently_sorted():\n # GH#38439\n mi1 = MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)])\n mi2 = MultiIndex.from_tuples([(np.nan, np.nan), (81.0, np.nan)])\n assert not mi1.equals(mi2)\n\n mi2 = MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)])\n assert mi1.equals(mi2)\n\n\ndef test_is_():\n mi = MultiIndex.from_tuples(zip(range(10), range(10)))\n assert mi.is_(mi)\n assert mi.is_(mi.view())\n assert mi.is_(mi.view().view().view().view())\n mi2 = mi.view()\n # names are metadata, they don't change id\n mi2.names = ["A", "B"]\n assert mi2.is_(mi)\n assert mi.is_(mi2)\n\n assert not mi.is_(mi.set_names(["C", "D"]))\n # levels are inherent properties, they change identity\n mi3 = mi2.set_levels([list(range(10)), list(range(10))])\n assert not mi3.is_(mi2)\n # shouldn't change\n assert mi2.is_(mi)\n mi4 = mi3.view()\n\n # GH 17464 - Remove duplicate MultiIndex levels\n mi4 = mi4.set_levels([list(range(10)), list(range(10))])\n assert not mi4.is_(mi3)\n mi5 = mi.view()\n mi5 = mi5.set_levels(mi5.levels)\n assert not mi5.is_(mi)\n\n\ndef test_is_all_dates(idx):\n assert not idx._is_all_dates\n\n\ndef test_is_numeric(idx):\n # MultiIndex is never numeric\n assert not is_any_real_numeric_dtype(idx)\n\n\ndef test_multiindex_compare():\n # GH 21149\n # Ensure comparison operations for MultiIndex with nlevels == 1\n # behave consistently with those for MultiIndex with nlevels > 1\n\n midx = MultiIndex.from_product([[0, 1]])\n\n # Equality self-test: MultiIndex object vs self\n expected = Series([True, True])\n result = Series(midx == midx)\n tm.assert_series_equal(result, expected)\n\n # Greater than comparison: MultiIndex object vs self\n expected = Series([False, False])\n result = Series(midx > midx)\n tm.assert_series_equal(result, expected)\n\n\ndef test_equals_ea_int_regular_int():\n # GH#46026\n mi1 = MultiIndex.from_arrays([Index([1, 2], dtype="Int64"), [3, 4]])\n mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]])\n assert not mi1.equals(mi2)\n assert not mi2.equals(mi1)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_equivalence.py
test_equivalence.py
Python
8,530
0.95
0.066901
0.133641
vue-tools
595
2024-07-10T13:28:17.291991
GPL-3.0
true
df8690a3dcf96f69e7e3ef474fb0b0ef
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Index,\n MultiIndex,\n)\nimport pandas._testing as tm\n\n\ndef test_format(idx):\n msg = "MultiIndex.format is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n idx.format()\n idx[:0].format()\n\n\ndef test_format_integer_names():\n index = MultiIndex(\n levels=[[0, 1], [0, 1]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[0, 1]\n )\n msg = "MultiIndex.format is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n index.format(names=True)\n\n\ndef test_format_sparse_config(idx):\n # GH1538\n msg = "MultiIndex.format is deprecated"\n with pd.option_context("display.multi_sparse", False):\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = idx.format()\n assert result[1] == "foo two"\n\n\ndef test_format_sparse_display():\n index = MultiIndex(\n levels=[[0, 1], [0, 1], [0, 1], [0]],\n codes=[\n [0, 0, 0, 1, 1, 1],\n [0, 0, 1, 0, 0, 1],\n [0, 1, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 0],\n ],\n )\n msg = "MultiIndex.format is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = index.format()\n assert result[3] == "1 0 0 0"\n\n\ndef test_repr_with_unicode_data():\n with pd.option_context("display.encoding", "UTF-8"):\n d = {"a": ["\u05d0", 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}\n index = pd.DataFrame(d).set_index(["a", "b"]).index\n assert "\\" not in repr(index) # we don't want unicode-escaped\n\n\ndef test_repr_roundtrip_raises():\n mi = MultiIndex.from_product([list("ab"), range(3)], names=["first", "second"])\n msg = "Must pass both levels and codes"\n with pytest.raises(TypeError, match=msg):\n eval(repr(mi))\n\n\ndef test_unicode_string_with_unicode():\n d = {"a": ["\u05d0", 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}\n idx = pd.DataFrame(d).set_index(["a", "b"]).index\n str(idx)\n\n\ndef test_repr_max_seq_item_setting(idx):\n # GH10182\n idx = idx.repeat(50)\n with pd.option_context("display.max_seq_items", None):\n repr(idx)\n assert "..." not in str(idx)\n\n\nclass TestRepr:\n def test_unicode_repr_issues(self):\n levels = [Index(["a/\u03c3", "b/\u03c3", "c/\u03c3"]), Index([0, 1])]\n codes = [np.arange(3).repeat(2), np.tile(np.arange(2), 3)]\n index = MultiIndex(levels=levels, codes=codes)\n\n repr(index.levels)\n repr(index.get_level_values(1))\n\n def test_repr_max_seq_items_equal_to_n(self, idx):\n # display.max_seq_items == n\n with pd.option_context("display.max_seq_items", 6):\n result = idx.__repr__()\n expected = """\\nMultiIndex([('foo', 'one'),\n ('foo', 'two'),\n ('bar', 'one'),\n ('baz', 'two'),\n ('qux', 'one'),\n ('qux', 'two')],\n names=['first', 'second'])"""\n assert result == expected\n\n def test_repr(self, idx):\n result = idx[:1].__repr__()\n expected = """\\nMultiIndex([('foo', 'one')],\n names=['first', 'second'])"""\n assert result == expected\n\n result = idx.__repr__()\n expected = """\\nMultiIndex([('foo', 'one'),\n ('foo', 'two'),\n ('bar', 'one'),\n ('baz', 'two'),\n ('qux', 'one'),\n ('qux', 'two')],\n names=['first', 'second'])"""\n assert result == expected\n\n with pd.option_context("display.max_seq_items", 5):\n result = idx.__repr__()\n expected = """\\nMultiIndex([('foo', 'one'),\n ('foo', 'two'),\n ...\n ('qux', 'one'),\n ('qux', 'two')],\n names=['first', 'second'], length=6)"""\n assert result == expected\n\n # display.max_seq_items == 1\n with pd.option_context("display.max_seq_items", 1):\n result = idx.__repr__()\n expected = """\\nMultiIndex([...\n ('qux', 'two')],\n names=['first', ...], length=6)"""\n assert result == expected\n\n def test_rjust(self):\n n = 1000\n ci = pd.CategoricalIndex(list("a" * n) + (["abc"] * n))\n dti = pd.date_range("2000-01-01", freq="s", periods=n * 2)\n mi = MultiIndex.from_arrays([ci, ci.codes + 9, dti], names=["a", "b", "dti"])\n result = mi[:1].__repr__()\n expected = """\\nMultiIndex([('a', 9, '2000-01-01 00:00:00')],\n names=['a', 'b', 'dti'])"""\n assert result == expected\n\n result = mi[::500].__repr__()\n expected = """\\nMultiIndex([( 'a', 9, '2000-01-01 00:00:00'),\n ( 'a', 9, '2000-01-01 00:08:20'),\n ('abc', 10, '2000-01-01 00:16:40'),\n ('abc', 10, '2000-01-01 00:25:00')],\n names=['a', 'b', 'dti'])"""\n assert result == expected\n\n result = mi.__repr__()\n expected = """\\nMultiIndex([( 'a', 9, '2000-01-01 00:00:00'),\n ( 'a', 9, '2000-01-01 00:00:01'),\n ( 'a', 9, '2000-01-01 00:00:02'),\n ( 'a', 9, '2000-01-01 00:00:03'),\n ( 'a', 9, '2000-01-01 00:00:04'),\n ( 'a', 9, '2000-01-01 00:00:05'),\n ( 'a', 9, '2000-01-01 00:00:06'),\n ( 'a', 9, '2000-01-01 00:00:07'),\n ( 'a', 9, '2000-01-01 00:00:08'),\n ( 'a', 9, '2000-01-01 00:00:09'),\n ...\n ('abc', 10, '2000-01-01 00:33:10'),\n ('abc', 10, '2000-01-01 00:33:11'),\n ('abc', 10, '2000-01-01 00:33:12'),\n ('abc', 10, '2000-01-01 00:33:13'),\n ('abc', 10, '2000-01-01 00:33:14'),\n ('abc', 10, '2000-01-01 00:33:15'),\n ('abc', 10, '2000-01-01 00:33:16'),\n ('abc', 10, '2000-01-01 00:33:17'),\n ('abc', 10, '2000-01-01 00:33:18'),\n ('abc', 10, '2000-01-01 00:33:19')],\n names=['a', 'b', 'dti'], length=2000)"""\n assert result == expected\n\n def test_tuple_width(self):\n n = 1000\n ci = pd.CategoricalIndex(list("a" * n) + (["abc"] * n))\n dti = pd.date_range("2000-01-01", freq="s", periods=n * 2)\n levels = [ci, ci.codes + 9, dti, dti, dti]\n names = ["a", "b", "dti_1", "dti_2", "dti_3"]\n mi = MultiIndex.from_arrays(levels, names=names)\n result = mi[:1].__repr__()\n expected = """MultiIndex([('a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...)],\n names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])""" # noqa: E501\n assert result == expected\n\n result = mi[:10].__repr__()\n expected = """\\nMultiIndex([('a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...),\n ('a', 9, '2000-01-01 00:00:01', '2000-01-01 00:00:01', ...),\n ('a', 9, '2000-01-01 00:00:02', '2000-01-01 00:00:02', ...),\n ('a', 9, '2000-01-01 00:00:03', '2000-01-01 00:00:03', ...),\n ('a', 9, '2000-01-01 00:00:04', '2000-01-01 00:00:04', ...),\n ('a', 9, '2000-01-01 00:00:05', '2000-01-01 00:00:05', ...),\n ('a', 9, '2000-01-01 00:00:06', '2000-01-01 00:00:06', ...),\n ('a', 9, '2000-01-01 00:00:07', '2000-01-01 00:00:07', ...),\n ('a', 9, '2000-01-01 00:00:08', '2000-01-01 00:00:08', ...),\n ('a', 9, '2000-01-01 00:00:09', '2000-01-01 00:00:09', ...)],\n names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])"""\n assert result == expected\n\n result = mi.__repr__()\n expected = """\\nMultiIndex([( 'a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...),\n ( 'a', 9, '2000-01-01 00:00:01', '2000-01-01 00:00:01', ...),\n ( 'a', 9, '2000-01-01 00:00:02', '2000-01-01 00:00:02', ...),\n ( 'a', 9, '2000-01-01 00:00:03', '2000-01-01 00:00:03', ...),\n ( 'a', 9, '2000-01-01 00:00:04', '2000-01-01 00:00:04', ...),\n ( 'a', 9, '2000-01-01 00:00:05', '2000-01-01 00:00:05', ...),\n ( 'a', 9, '2000-01-01 00:00:06', '2000-01-01 00:00:06', ...),\n ( 'a', 9, '2000-01-01 00:00:07', '2000-01-01 00:00:07', ...),\n ( 'a', 9, '2000-01-01 00:00:08', '2000-01-01 00:00:08', ...),\n ( 'a', 9, '2000-01-01 00:00:09', '2000-01-01 00:00:09', ...),\n ...\n ('abc', 10, '2000-01-01 00:33:10', '2000-01-01 00:33:10', ...),\n ('abc', 10, '2000-01-01 00:33:11', '2000-01-01 00:33:11', ...),\n ('abc', 10, '2000-01-01 00:33:12', '2000-01-01 00:33:12', ...),\n ('abc', 10, '2000-01-01 00:33:13', '2000-01-01 00:33:13', ...),\n ('abc', 10, '2000-01-01 00:33:14', '2000-01-01 00:33:14', ...),\n ('abc', 10, '2000-01-01 00:33:15', '2000-01-01 00:33:15', ...),\n ('abc', 10, '2000-01-01 00:33:16', '2000-01-01 00:33:16', ...),\n ('abc', 10, '2000-01-01 00:33:17', '2000-01-01 00:33:17', ...),\n ('abc', 10, '2000-01-01 00:33:18', '2000-01-01 00:33:18', ...),\n ('abc', 10, '2000-01-01 00:33:19', '2000-01-01 00:33:19', ...)],\n names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'], length=2000)"""\n assert result == expected\n\n def test_multiindex_long_element(self):\n # Non-regression test towards GH#52960\n data = MultiIndex.from_tuples([("c" * 62,)])\n\n expected = (\n "MultiIndex([('cccccccccccccccccccccccccccccccccccccccc"\n "cccccccccccccccccccccc',)],\n )"\n )\n assert str(data) == expected\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_formats.py
test_formats.py
Python
9,538
0.95
0.060241
0.023148
python-kit
320
2025-02-06T12:05:12.731277
Apache-2.0
true
a7111b1ce4717dbc32aab5b2358db741
import numpy as np\n\nimport pandas as pd\nfrom pandas import (\n CategoricalIndex,\n Index,\n MultiIndex,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestGetLevelValues:\n def test_get_level_values_box_datetime64(self):\n dates = date_range("1/1/2000", periods=4)\n levels = [dates, [0, 1]]\n codes = [[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]]\n\n index = MultiIndex(levels=levels, codes=codes)\n\n assert isinstance(index.get_level_values(0)[0], Timestamp)\n\n\ndef test_get_level_values(idx):\n result = idx.get_level_values(0)\n expected = Index(["foo", "foo", "bar", "baz", "qux", "qux"], name="first")\n tm.assert_index_equal(result, expected)\n assert result.name == "first"\n\n result = idx.get_level_values("first")\n expected = idx.get_level_values(0)\n tm.assert_index_equal(result, expected)\n\n # GH 10460\n index = MultiIndex(\n levels=[CategoricalIndex(["A", "B"]), CategoricalIndex([1, 2, 3])],\n codes=[np.array([0, 0, 0, 1, 1, 1]), np.array([0, 1, 2, 0, 1, 2])],\n )\n\n exp = CategoricalIndex(["A", "A", "A", "B", "B", "B"])\n tm.assert_index_equal(index.get_level_values(0), exp)\n exp = CategoricalIndex([1, 2, 3, 1, 2, 3])\n tm.assert_index_equal(index.get_level_values(1), exp)\n\n\ndef test_get_level_values_all_na():\n # GH#17924 when level entirely consists of nan\n arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]]\n index = MultiIndex.from_arrays(arrays)\n result = index.get_level_values(0)\n expected = Index([np.nan, np.nan, np.nan], dtype=np.float64)\n tm.assert_index_equal(result, expected)\n\n result = index.get_level_values(1)\n expected = Index(["a", np.nan, 1], dtype=object)\n tm.assert_index_equal(result, expected)\n\n\ndef test_get_level_values_int_with_na():\n # GH#17924\n arrays = [["a", "b", "b"], [1, np.nan, 2]]\n index = MultiIndex.from_arrays(arrays)\n result = index.get_level_values(1)\n expected = Index([1, np.nan, 2])\n tm.assert_index_equal(result, expected)\n\n arrays = [["a", "b", "b"], [np.nan, np.nan, 2]]\n index = MultiIndex.from_arrays(arrays)\n result = index.get_level_values(1)\n expected = Index([np.nan, np.nan, 2])\n tm.assert_index_equal(result, expected)\n\n\ndef test_get_level_values_na():\n arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]]\n index = MultiIndex.from_arrays(arrays)\n result = index.get_level_values(0)\n expected = Index([np.nan, np.nan, np.nan])\n tm.assert_index_equal(result, expected)\n\n result = index.get_level_values(1)\n expected = Index(["a", np.nan, 1])\n tm.assert_index_equal(result, expected)\n\n arrays = [["a", "b", "b"], pd.DatetimeIndex([0, 1, pd.NaT])]\n index = MultiIndex.from_arrays(arrays)\n result = index.get_level_values(1)\n expected = pd.DatetimeIndex([0, 1, pd.NaT])\n tm.assert_index_equal(result, expected)\n\n arrays = [[], []]\n index = MultiIndex.from_arrays(arrays)\n result = index.get_level_values(0)\n expected = Index([], dtype=object)\n tm.assert_index_equal(result, expected)\n\n\ndef test_get_level_values_when_periods():\n # GH33131. See also discussion in GH32669.\n # This test can probably be removed when PeriodIndex._engine is removed.\n from pandas import (\n Period,\n PeriodIndex,\n )\n\n idx = MultiIndex.from_arrays(\n [PeriodIndex([Period("2019Q1"), Period("2019Q2")], name="b")]\n )\n idx2 = MultiIndex.from_arrays(\n [idx._get_level_values(level) for level in range(idx.nlevels)]\n )\n assert all(x.is_monotonic_increasing for x in idx2.levels)\n\n\ndef test_values_loses_freq_of_underlying_index():\n # GH#49054\n idx = pd.DatetimeIndex(date_range("20200101", periods=3, freq="BME"))\n expected = idx.copy(deep=True)\n idx2 = Index([1, 2, 3])\n midx = MultiIndex(levels=[idx, idx2], codes=[[0, 1, 2], [0, 1, 2]])\n midx.values\n assert idx.freq is not None\n tm.assert_index_equal(idx, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_get_level_values.py
test_get_level_values.py
Python
3,971
0.95
0.080645
0.061224
awesome-app
676
2024-08-28T20:56:48.391855
BSD-3-Clause
true
bf911db6bcac5456a0454372ed3a60ef
import numpy as np\nimport pytest\n\nfrom pandas.compat import PY311\n\nfrom pandas.core.dtypes.dtypes import DatetimeTZDtype\n\nimport pandas as pd\nfrom pandas import (\n CategoricalIndex,\n MultiIndex,\n)\nimport pandas._testing as tm\n\n\ndef assert_matching(actual, expected, check_dtype=False):\n # avoid specifying internal representation\n # as much as possible\n assert len(actual) == len(expected)\n for act, exp in zip(actual, expected):\n act = np.asarray(act)\n exp = np.asarray(exp)\n tm.assert_numpy_array_equal(act, exp, check_dtype=check_dtype)\n\n\ndef test_get_level_number_integer(idx):\n idx.names = [1, 0]\n assert idx._get_level_number(1) == 0\n assert idx._get_level_number(0) == 1\n msg = "Too many levels: Index has only 2 levels, not 3"\n with pytest.raises(IndexError, match=msg):\n idx._get_level_number(2)\n with pytest.raises(KeyError, match="Level fourth not found"):\n idx._get_level_number("fourth")\n\n\ndef test_get_dtypes(using_infer_string):\n # Test MultiIndex.dtypes (# Gh37062)\n idx_multitype = MultiIndex.from_product(\n [[1, 2, 3], ["a", "b", "c"], pd.date_range("20200101", periods=2, tz="UTC")],\n names=["int", "string", "dt"],\n )\n\n exp = "object" if not using_infer_string else pd.StringDtype(na_value=np.nan)\n expected = pd.Series(\n {\n "int": np.dtype("int64"),\n "string": exp,\n "dt": DatetimeTZDtype(tz="utc"),\n }\n )\n tm.assert_series_equal(expected, idx_multitype.dtypes)\n\n\ndef test_get_dtypes_no_level_name(using_infer_string):\n # Test MultiIndex.dtypes (# GH38580 )\n idx_multitype = MultiIndex.from_product(\n [\n [1, 2, 3],\n ["a", "b", "c"],\n pd.date_range("20200101", periods=2, tz="UTC"),\n ],\n )\n exp = "object" if not using_infer_string else pd.StringDtype(na_value=np.nan)\n expected = pd.Series(\n {\n "level_0": np.dtype("int64"),\n "level_1": exp,\n "level_2": DatetimeTZDtype(tz="utc"),\n }\n )\n tm.assert_series_equal(expected, idx_multitype.dtypes)\n\n\ndef test_get_dtypes_duplicate_level_names(using_infer_string):\n # Test MultiIndex.dtypes with non-unique level names (# GH45174)\n result = MultiIndex.from_product(\n [\n [1, 2, 3],\n ["a", "b", "c"],\n pd.date_range("20200101", periods=2, tz="UTC"),\n ],\n names=["A", "A", "A"],\n ).dtypes\n exp = "object" if not using_infer_string else pd.StringDtype(na_value=np.nan)\n expected = pd.Series(\n [np.dtype("int64"), exp, DatetimeTZDtype(tz="utc")],\n index=["A", "A", "A"],\n )\n tm.assert_series_equal(result, expected)\n\n\ndef test_get_level_number_out_of_bounds(multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n\n with pytest.raises(IndexError, match="Too many levels"):\n frame.index._get_level_number(2)\n with pytest.raises(IndexError, match="not a valid level number"):\n frame.index._get_level_number(-3)\n\n\ndef test_set_name_methods(idx):\n # so long as these are synonyms, we don't need to test set_names\n index_names = ["first", "second"]\n assert idx.rename == idx.set_names\n new_names = [name + "SUFFIX" for name in index_names]\n ind = idx.set_names(new_names)\n assert idx.names == index_names\n assert ind.names == new_names\n msg = "Length of names must match number of levels in MultiIndex"\n with pytest.raises(ValueError, match=msg):\n ind.set_names(new_names + new_names)\n new_names2 = [name + "SUFFIX2" for name in new_names]\n res = ind.set_names(new_names2, inplace=True)\n assert res is None\n assert ind.names == new_names2\n\n # set names for specific level (# GH7792)\n ind = idx.set_names(new_names[0], level=0)\n assert idx.names == index_names\n assert ind.names == [new_names[0], index_names[1]]\n\n res = ind.set_names(new_names2[0], level=0, inplace=True)\n assert res is None\n assert ind.names == [new_names2[0], index_names[1]]\n\n # set names for multiple levels\n ind = idx.set_names(new_names, level=[0, 1])\n assert idx.names == index_names\n assert ind.names == new_names\n\n res = ind.set_names(new_names2, level=[0, 1], inplace=True)\n assert res is None\n assert ind.names == new_names2\n\n\ndef test_set_levels_codes_directly(idx):\n # setting levels/codes directly raises AttributeError\n\n levels = idx.levels\n new_levels = [[lev + "a" for lev in level] for level in levels]\n\n codes = idx.codes\n major_codes, minor_codes = codes\n major_codes = [(x + 1) % 3 for x in major_codes]\n minor_codes = [(x + 1) % 1 for x in minor_codes]\n new_codes = [major_codes, minor_codes]\n\n msg = "Can't set attribute"\n with pytest.raises(AttributeError, match=msg):\n idx.levels = new_levels\n\n msg = (\n "property 'codes' of 'MultiIndex' object has no setter"\n if PY311\n else "can't set attribute"\n )\n with pytest.raises(AttributeError, match=msg):\n idx.codes = new_codes\n\n\ndef test_set_levels(idx):\n # side note - you probably wouldn't want to use levels and codes\n # directly like this - but it is possible.\n levels = idx.levels\n new_levels = [[lev + "a" for lev in level] for level in levels]\n\n # level changing [w/o mutation]\n ind2 = idx.set_levels(new_levels)\n assert_matching(ind2.levels, new_levels)\n assert_matching(idx.levels, levels)\n\n # level changing specific level [w/o mutation]\n ind2 = idx.set_levels(new_levels[0], level=0)\n assert_matching(ind2.levels, [new_levels[0], levels[1]])\n assert_matching(idx.levels, levels)\n\n ind2 = idx.set_levels(new_levels[1], level=1)\n assert_matching(ind2.levels, [levels[0], new_levels[1]])\n assert_matching(idx.levels, levels)\n\n # level changing multiple levels [w/o mutation]\n ind2 = idx.set_levels(new_levels, level=[0, 1])\n assert_matching(ind2.levels, new_levels)\n assert_matching(idx.levels, levels)\n\n # illegal level changing should not change levels\n # GH 13754\n original_index = idx.copy()\n with pytest.raises(ValueError, match="^On"):\n idx.set_levels(["c"], level=0)\n assert_matching(idx.levels, original_index.levels, check_dtype=True)\n\n with pytest.raises(ValueError, match="^On"):\n idx.set_codes([0, 1, 2, 3, 4, 5], level=0)\n assert_matching(idx.codes, original_index.codes, check_dtype=True)\n\n with pytest.raises(TypeError, match="^Levels"):\n idx.set_levels("c", level=0)\n assert_matching(idx.levels, original_index.levels, check_dtype=True)\n\n with pytest.raises(TypeError, match="^Codes"):\n idx.set_codes(1, level=0)\n assert_matching(idx.codes, original_index.codes, check_dtype=True)\n\n\ndef test_set_codes(idx):\n # side note - you probably wouldn't want to use levels and codes\n # directly like this - but it is possible.\n codes = idx.codes\n major_codes, minor_codes = codes\n major_codes = [(x + 1) % 3 for x in major_codes]\n minor_codes = [(x + 1) % 1 for x in minor_codes]\n new_codes = [major_codes, minor_codes]\n\n # changing codes w/o mutation\n ind2 = idx.set_codes(new_codes)\n assert_matching(ind2.codes, new_codes)\n assert_matching(idx.codes, codes)\n\n # codes changing specific level w/o mutation\n ind2 = idx.set_codes(new_codes[0], level=0)\n assert_matching(ind2.codes, [new_codes[0], codes[1]])\n assert_matching(idx.codes, codes)\n\n ind2 = idx.set_codes(new_codes[1], level=1)\n assert_matching(ind2.codes, [codes[0], new_codes[1]])\n assert_matching(idx.codes, codes)\n\n # codes changing multiple levels w/o mutation\n ind2 = idx.set_codes(new_codes, level=[0, 1])\n assert_matching(ind2.codes, new_codes)\n assert_matching(idx.codes, codes)\n\n # label changing for levels of different magnitude of categories\n ind = MultiIndex.from_tuples([(0, i) for i in range(130)])\n new_codes = range(129, -1, -1)\n expected = MultiIndex.from_tuples([(0, i) for i in new_codes])\n\n # [w/o mutation]\n result = ind.set_codes(codes=new_codes, level=1)\n assert result.equals(expected)\n\n\ndef test_set_levels_codes_names_bad_input(idx):\n levels, codes = idx.levels, idx.codes\n names = idx.names\n\n with pytest.raises(ValueError, match="Length of levels"):\n idx.set_levels([levels[0]])\n\n with pytest.raises(ValueError, match="Length of codes"):\n idx.set_codes([codes[0]])\n\n with pytest.raises(ValueError, match="Length of names"):\n idx.set_names([names[0]])\n\n # shouldn't scalar data error, instead should demand list-like\n with pytest.raises(TypeError, match="list of lists-like"):\n idx.set_levels(levels[0])\n\n # shouldn't scalar data error, instead should demand list-like\n with pytest.raises(TypeError, match="list of lists-like"):\n idx.set_codes(codes[0])\n\n # shouldn't scalar data error, instead should demand list-like\n with pytest.raises(TypeError, match="list-like"):\n idx.set_names(names[0])\n\n # should have equal lengths\n with pytest.raises(TypeError, match="list of lists-like"):\n idx.set_levels(levels[0], level=[0, 1])\n\n with pytest.raises(TypeError, match="list-like"):\n idx.set_levels(levels, level=0)\n\n # should have equal lengths\n with pytest.raises(TypeError, match="list of lists-like"):\n idx.set_codes(codes[0], level=[0, 1])\n\n with pytest.raises(TypeError, match="list-like"):\n idx.set_codes(codes, level=0)\n\n # should have equal lengths\n with pytest.raises(ValueError, match="Length of names"):\n idx.set_names(names[0], level=[0, 1])\n\n with pytest.raises(TypeError, match="Names must be a"):\n idx.set_names(names, level=0)\n\n\n@pytest.mark.parametrize("inplace", [True, False])\ndef test_set_names_with_nlevel_1(inplace):\n # GH 21149\n # Ensure that .set_names for MultiIndex with\n # nlevels == 1 does not raise any errors\n expected = MultiIndex(levels=[[0, 1]], codes=[[0, 1]], names=["first"])\n m = MultiIndex.from_product([[0, 1]])\n result = m.set_names("first", level=0, inplace=inplace)\n\n if inplace:\n result = m\n\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("ordered", [True, False])\ndef test_set_levels_categorical(ordered):\n # GH13854\n index = MultiIndex.from_arrays([list("xyzx"), [0, 1, 2, 3]])\n\n cidx = CategoricalIndex(list("bac"), ordered=ordered)\n result = index.set_levels(cidx, level=0)\n expected = MultiIndex(levels=[cidx, [0, 1, 2, 3]], codes=index.codes)\n tm.assert_index_equal(result, expected)\n\n result_lvl = result.get_level_values(0)\n expected_lvl = CategoricalIndex(\n list("bacb"), categories=cidx.categories, ordered=cidx.ordered\n )\n tm.assert_index_equal(result_lvl, expected_lvl)\n\n\ndef test_set_value_keeps_names():\n # motivating example from #3742\n lev1 = ["hans", "hans", "hans", "grethe", "grethe", "grethe"]\n lev2 = ["1", "2", "3"] * 2\n idx = MultiIndex.from_arrays([lev1, lev2], names=["Name", "Number"])\n df = pd.DataFrame(\n np.random.default_rng(2).standard_normal((6, 4)),\n columns=["one", "two", "three", "four"],\n index=idx,\n )\n df = df.sort_index()\n assert df._is_copy is None\n assert df.index.names == ("Name", "Number")\n df.at[("grethe", "4"), "one"] = 99.34\n assert df._is_copy is None\n assert df.index.names == ("Name", "Number")\n\n\ndef test_set_levels_with_iterable():\n # GH23273\n sizes = [1, 2, 3]\n colors = ["black"] * 3\n index = MultiIndex.from_arrays([sizes, colors], names=["size", "color"])\n\n result = index.set_levels(map(int, ["3", "2", "1"]), level="size")\n\n expected_sizes = [3, 2, 1]\n expected = MultiIndex.from_arrays([expected_sizes, colors], names=["size", "color"])\n tm.assert_index_equal(result, expected)\n\n\ndef test_set_empty_level():\n # GH#48636\n midx = MultiIndex.from_arrays([[]], names=["A"])\n result = midx.set_levels(pd.DatetimeIndex([]), level=0)\n expected = MultiIndex.from_arrays([pd.DatetimeIndex([])], names=["A"])\n tm.assert_index_equal(result, expected)\n\n\ndef test_set_levels_pos_args_removal():\n # https://github.com/pandas-dev/pandas/issues/41485\n idx = MultiIndex.from_tuples(\n [\n (1, "one"),\n (3, "one"),\n ],\n names=["foo", "bar"],\n )\n with pytest.raises(TypeError, match="positional arguments"):\n idx.set_levels(["a", "b", "c"], 0)\n\n with pytest.raises(TypeError, match="positional arguments"):\n idx.set_codes([[0, 1], [1, 0]], 0)\n\n\ndef test_set_levels_categorical_keep_dtype():\n # GH#52125\n midx = MultiIndex.from_arrays([[5, 6]])\n result = midx.set_levels(levels=pd.Categorical([1, 2]), level=0)\n expected = MultiIndex.from_arrays([pd.Categorical([1, 2])])\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_get_set.py
test_get_set.py
Python
12,870
0.95
0.104167
0.125828
node-utils
917
2025-02-02T03:26:20.822133
Apache-2.0
true
2d1a59ae5a2577c9c7ee9fa6990e2d6e
from datetime import timedelta\nimport re\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs import index as libindex\nfrom pandas.errors import (\n InvalidIndexError,\n PerformanceWarning,\n)\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n Index,\n MultiIndex,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestSliceLocs:\n def test_slice_locs_partial(self, idx):\n sorted_idx, _ = idx.sortlevel(0)\n\n result = sorted_idx.slice_locs(("foo", "two"), ("qux", "one"))\n assert result == (1, 5)\n\n result = sorted_idx.slice_locs(None, ("qux", "one"))\n assert result == (0, 5)\n\n result = sorted_idx.slice_locs(("foo", "two"), None)\n assert result == (1, len(sorted_idx))\n\n result = sorted_idx.slice_locs("bar", "baz")\n assert result == (2, 4)\n\n def test_slice_locs(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((50, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=date_range("2000-01-01", periods=50, freq="B"),\n )\n stacked = df.stack(future_stack=True)\n idx = stacked.index\n\n slob = slice(*idx.slice_locs(df.index[5], df.index[15]))\n sliced = stacked[slob]\n expected = df[5:16].stack(future_stack=True)\n tm.assert_almost_equal(sliced.values, expected.values)\n\n slob = slice(\n *idx.slice_locs(\n df.index[5] + timedelta(seconds=30),\n df.index[15] - timedelta(seconds=30),\n )\n )\n sliced = stacked[slob]\n expected = df[6:15].stack(future_stack=True)\n tm.assert_almost_equal(sliced.values, expected.values)\n\n def test_slice_locs_with_type_mismatch(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=date_range("2000-01-01", periods=10, freq="B"),\n )\n stacked = df.stack(future_stack=True)\n idx = stacked.index\n with pytest.raises(TypeError, match="^Level type mismatch"):\n idx.slice_locs((1, 3))\n with pytest.raises(TypeError, match="^Level type mismatch"):\n idx.slice_locs(df.index[5] + timedelta(seconds=30), (5, 2))\n df = DataFrame(\n np.ones((5, 5)),\n index=Index([f"i-{i}" for i in range(5)], name="a"),\n columns=Index([f"i-{i}" for i in range(5)], name="a"),\n )\n stacked = df.stack(future_stack=True)\n idx = stacked.index\n with pytest.raises(TypeError, match="^Level type mismatch"):\n idx.slice_locs(timedelta(seconds=30))\n # TODO: Try creating a UnicodeDecodeError in exception message\n with pytest.raises(TypeError, match="^Level type mismatch"):\n idx.slice_locs(df.index[1], (16, "a"))\n\n def test_slice_locs_not_sorted(self):\n index = MultiIndex(\n levels=[Index(np.arange(4)), Index(np.arange(4)), Index(np.arange(4))],\n codes=[\n np.array([0, 0, 1, 2, 2, 2, 3, 3]),\n np.array([0, 1, 0, 0, 0, 1, 0, 1]),\n np.array([1, 0, 1, 1, 0, 0, 1, 0]),\n ],\n )\n msg = "[Kk]ey length.*greater than MultiIndex lexsort depth"\n with pytest.raises(KeyError, match=msg):\n index.slice_locs((1, 0, 1), (2, 1, 0))\n\n # works\n sorted_index, _ = index.sortlevel(0)\n # should there be a test case here???\n sorted_index.slice_locs((1, 0, 1), (2, 1, 0))\n\n def test_slice_locs_not_contained(self):\n # some searchsorted action\n\n index = MultiIndex(\n levels=[[0, 2, 4, 6], [0, 2, 4]],\n codes=[[0, 0, 0, 1, 1, 2, 3, 3, 3], [0, 1, 2, 1, 2, 2, 0, 1, 2]],\n )\n\n result = index.slice_locs((1, 0), (5, 2))\n assert result == (3, 6)\n\n result = index.slice_locs(1, 5)\n assert result == (3, 6)\n\n result = index.slice_locs((2, 2), (5, 2))\n assert result == (3, 6)\n\n result = index.slice_locs(2, 5)\n assert result == (3, 6)\n\n result = index.slice_locs((1, 0), (6, 3))\n assert result == (3, 8)\n\n result = index.slice_locs(-1, 10)\n assert result == (0, len(index))\n\n @pytest.mark.parametrize(\n "index_arr,expected,start_idx,end_idx",\n [\n ([[np.nan, "a", "b"], ["c", "d", "e"]], (0, 3), np.nan, None),\n ([[np.nan, "a", "b"], ["c", "d", "e"]], (0, 3), np.nan, "b"),\n ([[np.nan, "a", "b"], ["c", "d", "e"]], (0, 3), np.nan, ("b", "e")),\n ([["a", "b", "c"], ["d", np.nan, "e"]], (1, 3), ("b", np.nan), None),\n ([["a", "b", "c"], ["d", np.nan, "e"]], (1, 3), ("b", np.nan), "c"),\n ([["a", "b", "c"], ["d", np.nan, "e"]], (1, 3), ("b", np.nan), ("c", "e")),\n ],\n )\n def test_slice_locs_with_missing_value(\n self, index_arr, expected, start_idx, end_idx\n ):\n # issue 19132\n idx = MultiIndex.from_arrays(index_arr)\n result = idx.slice_locs(start=start_idx, end=end_idx)\n assert result == expected\n\n\nclass TestPutmask:\n def test_putmask_with_wrong_mask(self, idx):\n # GH18368\n\n msg = "putmask: mask and data must be the same size"\n with pytest.raises(ValueError, match=msg):\n idx.putmask(np.ones(len(idx) + 1, np.bool_), 1)\n\n with pytest.raises(ValueError, match=msg):\n idx.putmask(np.ones(len(idx) - 1, np.bool_), 1)\n\n with pytest.raises(ValueError, match=msg):\n idx.putmask("foo", 1)\n\n def test_putmask_multiindex_other(self):\n # GH#43212 `value` is also a MultiIndex\n\n left = MultiIndex.from_tuples([(np.nan, 6), (np.nan, 6), ("a", 4)])\n right = MultiIndex.from_tuples([("a", 1), ("a", 1), ("d", 1)])\n mask = np.array([True, True, False])\n\n result = left.putmask(mask, right)\n\n expected = MultiIndex.from_tuples([right[0], right[1], left[2]])\n tm.assert_index_equal(result, expected)\n\n def test_putmask_keep_dtype(self, any_numeric_ea_dtype):\n # GH#49830\n midx = MultiIndex.from_arrays(\n [pd.Series([1, 2, 3], dtype=any_numeric_ea_dtype), [10, 11, 12]]\n )\n midx2 = MultiIndex.from_arrays(\n [pd.Series([5, 6, 7], dtype=any_numeric_ea_dtype), [-1, -2, -3]]\n )\n result = midx.putmask([True, False, False], midx2)\n expected = MultiIndex.from_arrays(\n [pd.Series([5, 2, 3], dtype=any_numeric_ea_dtype), [-1, 11, 12]]\n )\n tm.assert_index_equal(result, expected)\n\n def test_putmask_keep_dtype_shorter_value(self, any_numeric_ea_dtype):\n # GH#49830\n midx = MultiIndex.from_arrays(\n [pd.Series([1, 2, 3], dtype=any_numeric_ea_dtype), [10, 11, 12]]\n )\n midx2 = MultiIndex.from_arrays(\n [pd.Series([5], dtype=any_numeric_ea_dtype), [-1]]\n )\n result = midx.putmask([True, False, False], midx2)\n expected = MultiIndex.from_arrays(\n [pd.Series([5, 2, 3], dtype=any_numeric_ea_dtype), [-1, 11, 12]]\n )\n tm.assert_index_equal(result, expected)\n\n\nclass TestGetIndexer:\n def test_get_indexer(self):\n major_axis = Index(np.arange(4))\n minor_axis = Index(np.arange(2))\n\n major_codes = np.array([0, 0, 1, 2, 2, 3, 3], dtype=np.intp)\n minor_codes = np.array([0, 1, 0, 0, 1, 0, 1], dtype=np.intp)\n\n index = MultiIndex(\n levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]\n )\n idx1 = index[:5]\n idx2 = index[[1, 3, 5]]\n\n r1 = idx1.get_indexer(idx2)\n tm.assert_almost_equal(r1, np.array([1, 3, -1], dtype=np.intp))\n\n r1 = idx2.get_indexer(idx1, method="pad")\n e1 = np.array([-1, 0, 0, 1, 1], dtype=np.intp)\n tm.assert_almost_equal(r1, e1)\n\n r2 = idx2.get_indexer(idx1[::-1], method="pad")\n tm.assert_almost_equal(r2, e1[::-1])\n\n rffill1 = idx2.get_indexer(idx1, method="ffill")\n tm.assert_almost_equal(r1, rffill1)\n\n r1 = idx2.get_indexer(idx1, method="backfill")\n e1 = np.array([0, 0, 1, 1, 2], dtype=np.intp)\n tm.assert_almost_equal(r1, e1)\n\n r2 = idx2.get_indexer(idx1[::-1], method="backfill")\n tm.assert_almost_equal(r2, e1[::-1])\n\n rbfill1 = idx2.get_indexer(idx1, method="bfill")\n tm.assert_almost_equal(r1, rbfill1)\n\n # pass non-MultiIndex\n r1 = idx1.get_indexer(idx2.values)\n rexp1 = idx1.get_indexer(idx2)\n tm.assert_almost_equal(r1, rexp1)\n\n r1 = idx1.get_indexer([1, 2, 3])\n assert (r1 == [-1, -1, -1]).all()\n\n # create index with duplicates\n idx1 = Index(list(range(10)) + list(range(10)))\n idx2 = Index(list(range(20)))\n\n msg = "Reindexing only valid with uniquely valued Index objects"\n with pytest.raises(InvalidIndexError, match=msg):\n idx1.get_indexer(idx2)\n\n def test_get_indexer_nearest(self):\n midx = MultiIndex.from_tuples([("a", 1), ("b", 2)])\n msg = (\n "method='nearest' not implemented yet for MultiIndex; "\n "see GitHub issue 9365"\n )\n with pytest.raises(NotImplementedError, match=msg):\n midx.get_indexer(["a"], method="nearest")\n msg = "tolerance not implemented yet for MultiIndex"\n with pytest.raises(NotImplementedError, match=msg):\n midx.get_indexer(["a"], method="pad", tolerance=2)\n\n def test_get_indexer_categorical_time(self):\n # https://github.com/pandas-dev/pandas/issues/21390\n midx = MultiIndex.from_product(\n [\n Categorical(["a", "b", "c"]),\n Categorical(date_range("2012-01-01", periods=3, freq="h")),\n ]\n )\n result = midx.get_indexer(midx)\n tm.assert_numpy_array_equal(result, np.arange(9, dtype=np.intp))\n\n @pytest.mark.parametrize(\n "index_arr,labels,expected",\n [\n (\n [[1, np.nan, 2], [3, 4, 5]],\n [1, np.nan, 2],\n np.array([-1, -1, -1], dtype=np.intp),\n ),\n ([[1, np.nan, 2], [3, 4, 5]], [(np.nan, 4)], np.array([1], dtype=np.intp)),\n ([[1, 2, 3], [np.nan, 4, 5]], [(1, np.nan)], np.array([0], dtype=np.intp)),\n (\n [[1, 2, 3], [np.nan, 4, 5]],\n [np.nan, 4, 5],\n np.array([-1, -1, -1], dtype=np.intp),\n ),\n ],\n )\n def test_get_indexer_with_missing_value(self, index_arr, labels, expected):\n # issue 19132\n idx = MultiIndex.from_arrays(index_arr)\n result = idx.get_indexer(labels)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_indexer_methods(self):\n # https://github.com/pandas-dev/pandas/issues/29896\n # test getting an indexer for another index with different methods\n # confirms that getting an indexer without a filling method, getting an\n # indexer and backfilling, and getting an indexer and padding all behave\n # correctly in the case where all of the target values fall in between\n # several levels in the MultiIndex into which they are getting an indexer\n #\n # visually, the MultiIndexes used in this test are:\n # mult_idx_1:\n # 0: -1 0\n # 1: 2\n # 2: 3\n # 3: 4\n # 4: 0 0\n # 5: 2\n # 6: 3\n # 7: 4\n # 8: 1 0\n # 9: 2\n # 10: 3\n # 11: 4\n #\n # mult_idx_2:\n # 0: 0 1\n # 1: 3\n # 2: 4\n mult_idx_1 = MultiIndex.from_product([[-1, 0, 1], [0, 2, 3, 4]])\n mult_idx_2 = MultiIndex.from_product([[0], [1, 3, 4]])\n\n indexer = mult_idx_1.get_indexer(mult_idx_2)\n expected = np.array([-1, 6, 7], dtype=indexer.dtype)\n tm.assert_almost_equal(expected, indexer)\n\n backfill_indexer = mult_idx_1.get_indexer(mult_idx_2, method="backfill")\n expected = np.array([5, 6, 7], dtype=backfill_indexer.dtype)\n tm.assert_almost_equal(expected, backfill_indexer)\n\n # ensure the legacy "bfill" option functions identically to "backfill"\n backfill_indexer = mult_idx_1.get_indexer(mult_idx_2, method="bfill")\n expected = np.array([5, 6, 7], dtype=backfill_indexer.dtype)\n tm.assert_almost_equal(expected, backfill_indexer)\n\n pad_indexer = mult_idx_1.get_indexer(mult_idx_2, method="pad")\n expected = np.array([4, 6, 7], dtype=pad_indexer.dtype)\n tm.assert_almost_equal(expected, pad_indexer)\n\n # ensure the legacy "ffill" option functions identically to "pad"\n pad_indexer = mult_idx_1.get_indexer(mult_idx_2, method="ffill")\n expected = np.array([4, 6, 7], dtype=pad_indexer.dtype)\n tm.assert_almost_equal(expected, pad_indexer)\n\n @pytest.mark.parametrize("method", ["pad", "ffill", "backfill", "bfill", "nearest"])\n def test_get_indexer_methods_raise_for_non_monotonic(self, method):\n # 53452\n mi = MultiIndex.from_arrays([[0, 4, 2], [0, 4, 2]])\n if method == "nearest":\n err = NotImplementedError\n msg = "not implemented yet for MultiIndex"\n else:\n err = ValueError\n msg = "index must be monotonic increasing or decreasing"\n with pytest.raises(err, match=msg):\n mi.get_indexer([(1, 1)], method=method)\n\n def test_get_indexer_three_or_more_levels(self):\n # https://github.com/pandas-dev/pandas/issues/29896\n # tests get_indexer() on MultiIndexes with 3+ levels\n # visually, these are\n # mult_idx_1:\n # 0: 1 2 5\n # 1: 7\n # 2: 4 5\n # 3: 7\n # 4: 6 5\n # 5: 7\n # 6: 3 2 5\n # 7: 7\n # 8: 4 5\n # 9: 7\n # 10: 6 5\n # 11: 7\n #\n # mult_idx_2:\n # 0: 1 1 8\n # 1: 1 5 9\n # 2: 1 6 7\n # 3: 2 1 6\n # 4: 2 7 6\n # 5: 2 7 8\n # 6: 3 6 8\n mult_idx_1 = MultiIndex.from_product([[1, 3], [2, 4, 6], [5, 7]])\n mult_idx_2 = MultiIndex.from_tuples(\n [\n (1, 1, 8),\n (1, 5, 9),\n (1, 6, 7),\n (2, 1, 6),\n (2, 7, 7),\n (2, 7, 8),\n (3, 6, 8),\n ]\n )\n # sanity check\n assert mult_idx_1.is_monotonic_increasing\n assert mult_idx_1.is_unique\n assert mult_idx_2.is_monotonic_increasing\n assert mult_idx_2.is_unique\n\n # show the relationships between the two\n assert mult_idx_2[0] < mult_idx_1[0]\n assert mult_idx_1[3] < mult_idx_2[1] < mult_idx_1[4]\n assert mult_idx_1[5] == mult_idx_2[2]\n assert mult_idx_1[5] < mult_idx_2[3] < mult_idx_1[6]\n assert mult_idx_1[5] < mult_idx_2[4] < mult_idx_1[6]\n assert mult_idx_1[5] < mult_idx_2[5] < mult_idx_1[6]\n assert mult_idx_1[-1] < mult_idx_2[6]\n\n indexer_no_fill = mult_idx_1.get_indexer(mult_idx_2)\n expected = np.array([-1, -1, 5, -1, -1, -1, -1], dtype=indexer_no_fill.dtype)\n tm.assert_almost_equal(expected, indexer_no_fill)\n\n # test with backfilling\n indexer_backfilled = mult_idx_1.get_indexer(mult_idx_2, method="backfill")\n expected = np.array([0, 4, 5, 6, 6, 6, -1], dtype=indexer_backfilled.dtype)\n tm.assert_almost_equal(expected, indexer_backfilled)\n\n # now, the same thing, but forward-filled (aka "padded")\n indexer_padded = mult_idx_1.get_indexer(mult_idx_2, method="pad")\n expected = np.array([-1, 3, 5, 5, 5, 5, 11], dtype=indexer_padded.dtype)\n tm.assert_almost_equal(expected, indexer_padded)\n\n # now, do the indexing in the other direction\n assert mult_idx_2[0] < mult_idx_1[0] < mult_idx_2[1]\n assert mult_idx_2[0] < mult_idx_1[1] < mult_idx_2[1]\n assert mult_idx_2[0] < mult_idx_1[2] < mult_idx_2[1]\n assert mult_idx_2[0] < mult_idx_1[3] < mult_idx_2[1]\n assert mult_idx_2[1] < mult_idx_1[4] < mult_idx_2[2]\n assert mult_idx_2[2] == mult_idx_1[5]\n assert mult_idx_2[5] < mult_idx_1[6] < mult_idx_2[6]\n assert mult_idx_2[5] < mult_idx_1[7] < mult_idx_2[6]\n assert mult_idx_2[5] < mult_idx_1[8] < mult_idx_2[6]\n assert mult_idx_2[5] < mult_idx_1[9] < mult_idx_2[6]\n assert mult_idx_2[5] < mult_idx_1[10] < mult_idx_2[6]\n assert mult_idx_2[5] < mult_idx_1[11] < mult_idx_2[6]\n\n indexer = mult_idx_2.get_indexer(mult_idx_1)\n expected = np.array(\n [-1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1], dtype=indexer.dtype\n )\n tm.assert_almost_equal(expected, indexer)\n\n backfill_indexer = mult_idx_2.get_indexer(mult_idx_1, method="bfill")\n expected = np.array(\n [1, 1, 1, 1, 2, 2, 6, 6, 6, 6, 6, 6], dtype=backfill_indexer.dtype\n )\n tm.assert_almost_equal(expected, backfill_indexer)\n\n pad_indexer = mult_idx_2.get_indexer(mult_idx_1, method="pad")\n expected = np.array(\n [0, 0, 0, 0, 1, 2, 5, 5, 5, 5, 5, 5], dtype=pad_indexer.dtype\n )\n tm.assert_almost_equal(expected, pad_indexer)\n\n def test_get_indexer_crossing_levels(self):\n # https://github.com/pandas-dev/pandas/issues/29896\n # tests a corner case with get_indexer() with MultiIndexes where, when we\n # need to "carry" across levels, proper tuple ordering is respected\n #\n # the MultiIndexes used in this test, visually, are:\n # mult_idx_1:\n # 0: 1 1 1 1\n # 1: 2\n # 2: 2 1\n # 3: 2\n # 4: 1 2 1 1\n # 5: 2\n # 6: 2 1\n # 7: 2\n # 8: 2 1 1 1\n # 9: 2\n # 10: 2 1\n # 11: 2\n # 12: 2 2 1 1\n # 13: 2\n # 14: 2 1\n # 15: 2\n #\n # mult_idx_2:\n # 0: 1 3 2 2\n # 1: 2 3 2 2\n mult_idx_1 = MultiIndex.from_product([[1, 2]] * 4)\n mult_idx_2 = MultiIndex.from_tuples([(1, 3, 2, 2), (2, 3, 2, 2)])\n\n # show the tuple orderings, which get_indexer() should respect\n assert mult_idx_1[7] < mult_idx_2[0] < mult_idx_1[8]\n assert mult_idx_1[-1] < mult_idx_2[1]\n\n indexer = mult_idx_1.get_indexer(mult_idx_2)\n expected = np.array([-1, -1], dtype=indexer.dtype)\n tm.assert_almost_equal(expected, indexer)\n\n backfill_indexer = mult_idx_1.get_indexer(mult_idx_2, method="bfill")\n expected = np.array([8, -1], dtype=backfill_indexer.dtype)\n tm.assert_almost_equal(expected, backfill_indexer)\n\n pad_indexer = mult_idx_1.get_indexer(mult_idx_2, method="ffill")\n expected = np.array([7, 15], dtype=pad_indexer.dtype)\n tm.assert_almost_equal(expected, pad_indexer)\n\n def test_get_indexer_kwarg_validation(self):\n # GH#41918\n mi = MultiIndex.from_product([range(3), ["A", "B"]])\n\n msg = "limit argument only valid if doing pad, backfill or nearest"\n with pytest.raises(ValueError, match=msg):\n mi.get_indexer(mi[:-1], limit=4)\n\n msg = "tolerance argument only valid if doing pad, backfill or nearest"\n with pytest.raises(ValueError, match=msg):\n mi.get_indexer(mi[:-1], tolerance="piano")\n\n def test_get_indexer_nan(self):\n # GH#37222\n idx1 = MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"])\n idx2 = MultiIndex.from_product([["A"], [np.nan, 2.0]], names=["id1", "id2"])\n expected = np.array([-1, 1])\n result = idx2.get_indexer(idx1)\n tm.assert_numpy_array_equal(result, expected, check_dtype=False)\n result = idx1.get_indexer(idx2)\n tm.assert_numpy_array_equal(result, expected, check_dtype=False)\n\n\ndef test_getitem(idx):\n # scalar\n assert idx[2] == ("bar", "one")\n\n # slice\n result = idx[2:5]\n expected = idx[[2, 3, 4]]\n assert result.equals(expected)\n\n # boolean\n result = idx[[True, False, True, False, True, True]]\n result2 = idx[np.array([True, False, True, False, True, True])]\n expected = idx[[0, 2, 4, 5]]\n assert result.equals(expected)\n assert result2.equals(expected)\n\n\ndef test_getitem_group_select(idx):\n sorted_idx, _ = idx.sortlevel(0)\n assert sorted_idx.get_loc("baz") == slice(3, 4)\n assert sorted_idx.get_loc("foo") == slice(0, 2)\n\n\n@pytest.mark.parametrize("ind1", [[True] * 5, Index([True] * 5)])\n@pytest.mark.parametrize(\n "ind2",\n [[True, False, True, False, False], Index([True, False, True, False, False])],\n)\ndef test_getitem_bool_index_all(ind1, ind2):\n # GH#22533\n idx = MultiIndex.from_tuples([(10, 1), (20, 2), (30, 3), (40, 4), (50, 5)])\n tm.assert_index_equal(idx[ind1], idx)\n\n expected = MultiIndex.from_tuples([(10, 1), (30, 3)])\n tm.assert_index_equal(idx[ind2], expected)\n\n\n@pytest.mark.parametrize("ind1", [[True], Index([True])])\n@pytest.mark.parametrize("ind2", [[False], Index([False])])\ndef test_getitem_bool_index_single(ind1, ind2):\n # GH#22533\n idx = MultiIndex.from_tuples([(10, 1)])\n tm.assert_index_equal(idx[ind1], idx)\n\n expected = MultiIndex(\n levels=[np.array([], dtype=np.int64), np.array([], dtype=np.int64)],\n codes=[[], []],\n )\n tm.assert_index_equal(idx[ind2], expected)\n\n\nclass TestGetLoc:\n def test_get_loc(self, idx):\n assert idx.get_loc(("foo", "two")) == 1\n assert idx.get_loc(("baz", "two")) == 3\n with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"):\n idx.get_loc(("bar", "two"))\n with pytest.raises(KeyError, match=r"^'quux'$"):\n idx.get_loc("quux")\n\n # 3 levels\n index = MultiIndex(\n levels=[Index(np.arange(4)), Index(np.arange(4)), Index(np.arange(4))],\n codes=[\n np.array([0, 0, 1, 2, 2, 2, 3, 3]),\n np.array([0, 1, 0, 0, 0, 1, 0, 1]),\n np.array([1, 0, 1, 1, 0, 0, 1, 0]),\n ],\n )\n with pytest.raises(KeyError, match=r"^\(1, 1\)$"):\n index.get_loc((1, 1))\n assert index.get_loc((2, 0)) == slice(3, 5)\n\n def test_get_loc_duplicates(self):\n index = Index([2, 2, 2, 2])\n result = index.get_loc(2)\n expected = slice(0, 4)\n assert result == expected\n\n index = Index(["c", "a", "a", "b", "b"])\n rs = index.get_loc("c")\n xp = 0\n assert rs == xp\n\n with pytest.raises(KeyError, match="2"):\n index.get_loc(2)\n\n def test_get_loc_level(self):\n index = MultiIndex(\n levels=[Index(np.arange(4)), Index(np.arange(4)), Index(np.arange(4))],\n codes=[\n np.array([0, 0, 1, 2, 2, 2, 3, 3]),\n np.array([0, 1, 0, 0, 0, 1, 0, 1]),\n np.array([1, 0, 1, 1, 0, 0, 1, 0]),\n ],\n )\n loc, new_index = index.get_loc_level((0, 1))\n expected = slice(1, 2)\n exp_index = index[expected].droplevel(0).droplevel(0)\n assert loc == expected\n assert new_index.equals(exp_index)\n\n loc, new_index = index.get_loc_level((0, 1, 0))\n expected = 1\n assert loc == expected\n assert new_index is None\n\n with pytest.raises(KeyError, match=r"^\(2, 2\)$"):\n index.get_loc_level((2, 2))\n # GH 22221: unused label\n with pytest.raises(KeyError, match=r"^2$"):\n index.drop(2).get_loc_level(2)\n # Unused label on unsorted level:\n with pytest.raises(KeyError, match=r"^2$"):\n index.drop(1, level=2).get_loc_level(2, level=2)\n\n index = MultiIndex(\n levels=[[2000], list(range(4))],\n codes=[np.array([0, 0, 0, 0]), np.array([0, 1, 2, 3])],\n )\n result, new_index = index.get_loc_level((2000, slice(None, None)))\n expected = slice(None, None)\n assert result == expected\n assert new_index.equals(index.droplevel(0))\n\n @pytest.mark.parametrize("dtype1", [int, float, bool, str])\n @pytest.mark.parametrize("dtype2", [int, float, bool, str])\n def test_get_loc_multiple_dtypes(self, dtype1, dtype2):\n # GH 18520\n levels = [np.array([0, 1]).astype(dtype1), np.array([0, 1]).astype(dtype2)]\n idx = MultiIndex.from_product(levels)\n assert idx.get_loc(idx[2]) == 2\n\n @pytest.mark.parametrize("level", [0, 1])\n @pytest.mark.parametrize("dtypes", [[int, float], [float, int]])\n def test_get_loc_implicit_cast(self, level, dtypes):\n # GH 18818, GH 15994 : as flat index, cast int to float and vice-versa\n levels = [["a", "b"], ["c", "d"]]\n key = ["b", "d"]\n lev_dtype, key_dtype = dtypes\n levels[level] = np.array([0, 1], dtype=lev_dtype)\n key[level] = key_dtype(1)\n idx = MultiIndex.from_product(levels)\n assert idx.get_loc(tuple(key)) == 3\n\n @pytest.mark.parametrize("dtype", [bool, object])\n def test_get_loc_cast_bool(self, dtype):\n # GH 19086 : int is casted to bool, but not vice-versa (for object dtype)\n # With bool dtype, we don't cast in either direction.\n levels = [Index([False, True], dtype=dtype), np.arange(2, dtype="int64")]\n idx = MultiIndex.from_product(levels)\n\n if dtype is bool:\n with pytest.raises(KeyError, match=r"^\(0, 1\)$"):\n assert idx.get_loc((0, 1)) == 1\n with pytest.raises(KeyError, match=r"^\(1, 0\)$"):\n assert idx.get_loc((1, 0)) == 2\n else:\n # We use python object comparisons, which treat 0 == False and 1 == True\n assert idx.get_loc((0, 1)) == 1\n assert idx.get_loc((1, 0)) == 2\n\n with pytest.raises(KeyError, match=r"^\(False, True\)$"):\n idx.get_loc((False, True))\n with pytest.raises(KeyError, match=r"^\(True, False\)$"):\n idx.get_loc((True, False))\n\n @pytest.mark.parametrize("level", [0, 1])\n def test_get_loc_nan(self, level, nulls_fixture):\n # GH 18485 : NaN in MultiIndex\n levels = [["a", "b"], ["c", "d"]]\n key = ["b", "d"]\n levels[level] = np.array([0, nulls_fixture], dtype=type(nulls_fixture))\n key[level] = nulls_fixture\n idx = MultiIndex.from_product(levels)\n assert idx.get_loc(tuple(key)) == 3\n\n def test_get_loc_missing_nan(self):\n # GH 8569\n idx = MultiIndex.from_arrays([[1.0, 2.0], [3.0, 4.0]])\n assert isinstance(idx.get_loc(1), slice)\n with pytest.raises(KeyError, match=r"^3$"):\n idx.get_loc(3)\n with pytest.raises(KeyError, match=r"^nan$"):\n idx.get_loc(np.nan)\n with pytest.raises(InvalidIndexError, match=r"\[nan\]"):\n # listlike/non-hashable raises TypeError\n idx.get_loc([np.nan])\n\n def test_get_loc_with_values_including_missing_values(self):\n # issue 19132\n idx = MultiIndex.from_product([[np.nan, 1]] * 2)\n expected = slice(0, 2, None)\n assert idx.get_loc(np.nan) == expected\n\n idx = MultiIndex.from_arrays([[np.nan, 1, 2, np.nan]])\n expected = np.array([True, False, False, True])\n tm.assert_numpy_array_equal(idx.get_loc(np.nan), expected)\n\n idx = MultiIndex.from_product([[np.nan, 1]] * 3)\n expected = slice(2, 4, None)\n assert idx.get_loc((np.nan, 1)) == expected\n\n def test_get_loc_duplicates2(self):\n # TODO: de-duplicate with test_get_loc_duplicates above?\n index = MultiIndex(\n levels=[["D", "B", "C"], [0, 26, 27, 37, 57, 67, 75, 82]],\n codes=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],\n names=["tag", "day"],\n )\n\n assert index.get_loc("D") == slice(0, 3)\n\n def test_get_loc_past_lexsort_depth(self):\n # GH#30053\n idx = MultiIndex(\n levels=[["a"], [0, 7], [1]],\n codes=[[0, 0], [1, 0], [0, 0]],\n names=["x", "y", "z"],\n sortorder=0,\n )\n key = ("a", 7)\n\n with tm.assert_produces_warning(PerformanceWarning):\n # PerformanceWarning: indexing past lexsort depth may impact performance\n result = idx.get_loc(key)\n\n assert result == slice(0, 1, None)\n\n def test_multiindex_get_loc_list_raises(self):\n # GH#35878\n idx = MultiIndex.from_tuples([("a", 1), ("b", 2)])\n msg = r"\[\]"\n with pytest.raises(InvalidIndexError, match=msg):\n idx.get_loc([])\n\n def test_get_loc_nested_tuple_raises_keyerror(self):\n # raise KeyError, not TypeError\n mi = MultiIndex.from_product([range(3), range(4), range(5), range(6)])\n key = ((2, 3, 4), "foo")\n\n with pytest.raises(KeyError, match=re.escape(str(key))):\n mi.get_loc(key)\n\n\nclass TestWhere:\n def test_where(self):\n i = MultiIndex.from_tuples([("A", 1), ("A", 2)])\n\n msg = r"\.where is not supported for MultiIndex operations"\n with pytest.raises(NotImplementedError, match=msg):\n i.where(True)\n\n def test_where_array_like(self, listlike_box):\n mi = MultiIndex.from_tuples([("A", 1), ("A", 2)])\n cond = [False, True]\n msg = r"\.where is not supported for MultiIndex operations"\n with pytest.raises(NotImplementedError, match=msg):\n mi.where(listlike_box(cond))\n\n\nclass TestContains:\n def test_contains_top_level(self):\n midx = MultiIndex.from_product([["A", "B"], [1, 2]])\n assert "A" in midx\n assert "A" not in midx._engine\n\n def test_contains_with_nat(self):\n # MI with a NaT\n mi = MultiIndex(\n levels=[["C"], date_range("2012-01-01", periods=5)],\n codes=[[0, 0, 0, 0, 0, 0], [-1, 0, 1, 2, 3, 4]],\n names=[None, "B"],\n )\n assert ("C", pd.Timestamp("2012-01-01")) in mi\n for val in mi.values:\n assert val in mi\n\n def test_contains(self, idx):\n assert ("foo", "two") in idx\n assert ("bar", "two") not in idx\n assert None not in idx\n\n def test_contains_with_missing_value(self):\n # GH#19132\n idx = MultiIndex.from_arrays([[1, np.nan, 2]])\n assert np.nan in idx\n\n idx = MultiIndex.from_arrays([[1, 2], [np.nan, 3]])\n assert np.nan not in idx\n assert (1, np.nan) in idx\n\n def test_multiindex_contains_dropped(self):\n # GH#19027\n # test that dropped MultiIndex levels are not in the MultiIndex\n # despite continuing to be in the MultiIndex's levels\n idx = MultiIndex.from_product([[1, 2], [3, 4]])\n assert 2 in idx\n idx = idx.drop(2)\n\n # drop implementation keeps 2 in the levels\n assert 2 in idx.levels[0]\n # but it should no longer be in the index itself\n assert 2 not in idx\n\n # also applies to strings\n idx = MultiIndex.from_product([["a", "b"], ["c", "d"]])\n assert "a" in idx\n idx = idx.drop("a")\n assert "a" in idx.levels[0]\n assert "a" not in idx\n\n def test_contains_td64_level(self):\n # GH#24570\n tx = pd.timedelta_range("09:30:00", "16:00:00", freq="30 min")\n idx = MultiIndex.from_arrays([tx, np.arange(len(tx))])\n assert tx[0] in idx\n assert "element_not_exit" not in idx\n assert "0 day 09:30:00" in idx\n\n def test_large_mi_contains(self, monkeypatch):\n # GH#10645\n with monkeypatch.context():\n monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 10)\n result = MultiIndex.from_arrays([range(10), range(10)])\n assert (10, 0) not in result\n\n\ndef test_timestamp_multiindex_indexer():\n # https://github.com/pandas-dev/pandas/issues/26944\n idx = MultiIndex.from_product(\n [\n date_range("2019-01-01T00:15:33", periods=100, freq="h", name="date"),\n ["x"],\n [3],\n ]\n )\n df = DataFrame({"foo": np.arange(len(idx))}, idx)\n result = df.loc[pd.IndexSlice["2019-1-2":, "x", :], "foo"]\n qidx = MultiIndex.from_product(\n [\n date_range(\n start="2019-01-02T00:15:33",\n end="2019-01-05T03:15:33",\n freq="h",\n name="date",\n ),\n ["x"],\n [3],\n ]\n )\n should_be = pd.Series(data=np.arange(24, len(qidx) + 24), index=qidx, name="foo")\n tm.assert_series_equal(result, should_be)\n\n\n@pytest.mark.parametrize(\n "index_arr,expected,target,algo",\n [\n ([[np.nan, "a", "b"], ["c", "d", "e"]], 0, np.nan, "left"),\n ([[np.nan, "a", "b"], ["c", "d", "e"]], 1, (np.nan, "c"), "right"),\n ([["a", "b", "c"], ["d", np.nan, "d"]], 1, ("b", np.nan), "left"),\n ],\n)\ndef test_get_slice_bound_with_missing_value(index_arr, expected, target, algo):\n # issue 19132\n idx = MultiIndex.from_arrays(index_arr)\n result = idx.get_slice_bound(target, side=algo)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "index_arr,expected,start_idx,end_idx",\n [\n ([[np.nan, 1, 2], [3, 4, 5]], slice(0, 2, None), np.nan, 1),\n ([[np.nan, 1, 2], [3, 4, 5]], slice(0, 3, None), np.nan, (2, 5)),\n ([[1, 2, 3], [4, np.nan, 5]], slice(1, 3, None), (2, np.nan), 3),\n ([[1, 2, 3], [4, np.nan, 5]], slice(1, 3, None), (2, np.nan), (3, 5)),\n ],\n)\ndef test_slice_indexer_with_missing_value(index_arr, expected, start_idx, end_idx):\n # issue 19132\n idx = MultiIndex.from_arrays(index_arr)\n result = idx.slice_indexer(start=start_idx, end=end_idx)\n assert result == expected\n\n\ndef test_pyint_engine():\n # GH#18519 : when combinations of codes cannot be represented in 64\n # bits, the index underlying the MultiIndex engine works with Python\n # integers, rather than uint64.\n N = 5\n keys = [\n tuple(arr)\n for arr in [\n [0] * 10 * N,\n [1] * 10 * N,\n [2] * 10 * N,\n [np.nan] * N + [2] * 9 * N,\n [0] * N + [2] * 9 * N,\n [np.nan] * N + [2] * 8 * N + [0] * N,\n ]\n ]\n # Each level contains 4 elements (including NaN), so it is represented\n # in 2 bits, for a total of 2*N*10 = 100 > 64 bits. If we were using a\n # 64 bit engine and truncating the first levels, the fourth and fifth\n # keys would collide; if truncating the last levels, the fifth and\n # sixth; if rotating bits rather than shifting, the third and fifth.\n\n for idx, key_value in enumerate(keys):\n index = MultiIndex.from_tuples(keys)\n assert index.get_loc(key_value) == idx\n\n expected = np.arange(idx + 1, dtype=np.intp)\n result = index.get_indexer([keys[i] for i in expected])\n tm.assert_numpy_array_equal(result, expected)\n\n # With missing key:\n idces = range(len(keys))\n expected = np.array([-1] + list(idces), dtype=np.intp)\n missing = tuple([0, 1] * 5 * N)\n result = index.get_indexer([missing] + [keys[i] for i in idces])\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "keys,expected",\n [\n ((slice(None), [5, 4]), [1, 0]),\n ((slice(None), [4, 5]), [0, 1]),\n (([True, False, True], [4, 6]), [0, 2]),\n (([True, False, True], [6, 4]), [0, 2]),\n ((2, [4, 5]), [0, 1]),\n ((2, [5, 4]), [1, 0]),\n (([2], [4, 5]), [0, 1]),\n (([2], [5, 4]), [1, 0]),\n ],\n)\ndef test_get_locs_reordering(keys, expected):\n # GH48384\n idx = MultiIndex.from_arrays(\n [\n [2, 2, 1],\n [4, 5, 6],\n ]\n )\n result = idx.get_locs(keys)\n expected = np.array(expected, dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_get_indexer_for_multiindex_with_nans(nulls_fixture):\n # GH37222\n idx1 = MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"])\n idx2 = MultiIndex.from_product([["A"], [nulls_fixture, 2.0]], names=["id1", "id2"])\n\n result = idx2.get_indexer(idx1)\n expected = np.array([-1, 1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1.get_indexer(idx2)\n expected = np.array([-1, 1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_indexing.py
test_indexing.py
Python
36,399
0.95
0.078921
0.173913
node-utils
103
2025-02-04T13:31:47.651878
GPL-3.0
true
8db9533fb3d93ab193938471d8161ecc
import re\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs import index as libindex\n\nfrom pandas.core.dtypes.cast import construct_1d_object_array_from_listlike\n\nimport pandas as pd\nfrom pandas import (\n Index,\n IntervalIndex,\n MultiIndex,\n RangeIndex,\n)\nimport pandas._testing as tm\n\n\ndef test_labels_dtypes():\n # GH 8456\n i = MultiIndex.from_tuples([("A", 1), ("A", 2)])\n assert i.codes[0].dtype == "int8"\n assert i.codes[1].dtype == "int8"\n\n i = MultiIndex.from_product([["a"], range(40)])\n assert i.codes[1].dtype == "int8"\n i = MultiIndex.from_product([["a"], range(400)])\n assert i.codes[1].dtype == "int16"\n i = MultiIndex.from_product([["a"], range(40000)])\n assert i.codes[1].dtype == "int32"\n\n i = MultiIndex.from_product([["a"], range(1000)])\n assert (i.codes[0] >= 0).all()\n assert (i.codes[1] >= 0).all()\n\n\ndef test_values_boxed():\n tuples = [\n (1, pd.Timestamp("2000-01-01")),\n (2, pd.NaT),\n (3, pd.Timestamp("2000-01-03")),\n (1, pd.Timestamp("2000-01-04")),\n (2, pd.Timestamp("2000-01-02")),\n (3, pd.Timestamp("2000-01-03")),\n ]\n result = MultiIndex.from_tuples(tuples)\n expected = construct_1d_object_array_from_listlike(tuples)\n tm.assert_numpy_array_equal(result.values, expected)\n # Check that code branches for boxed values produce identical results\n tm.assert_numpy_array_equal(result.values[:4], result[:4].values)\n\n\ndef test_values_multiindex_datetimeindex():\n # Test to ensure we hit the boxing / nobox part of MI.values\n ints = np.arange(10**18, 10**18 + 5)\n naive = pd.DatetimeIndex(ints)\n\n aware = pd.DatetimeIndex(ints, tz="US/Central")\n\n idx = MultiIndex.from_arrays([naive, aware])\n result = idx.values\n\n outer = pd.DatetimeIndex([x[0] for x in result])\n tm.assert_index_equal(outer, naive)\n\n inner = pd.DatetimeIndex([x[1] for x in result])\n tm.assert_index_equal(inner, aware)\n\n # n_lev > n_lab\n result = idx[:2].values\n\n outer = pd.DatetimeIndex([x[0] for x in result])\n tm.assert_index_equal(outer, naive[:2])\n\n inner = pd.DatetimeIndex([x[1] for x in result])\n tm.assert_index_equal(inner, aware[:2])\n\n\ndef test_values_multiindex_periodindex():\n # Test to ensure we hit the boxing / nobox part of MI.values\n ints = np.arange(2007, 2012)\n pidx = pd.PeriodIndex(ints, freq="D")\n\n idx = MultiIndex.from_arrays([ints, pidx])\n result = idx.values\n\n outer = Index([x[0] for x in result])\n tm.assert_index_equal(outer, Index(ints, dtype=np.int64))\n\n inner = pd.PeriodIndex([x[1] for x in result])\n tm.assert_index_equal(inner, pidx)\n\n # n_lev > n_lab\n result = idx[:2].values\n\n outer = Index([x[0] for x in result])\n tm.assert_index_equal(outer, Index(ints[:2], dtype=np.int64))\n\n inner = pd.PeriodIndex([x[1] for x in result])\n tm.assert_index_equal(inner, pidx[:2])\n\n\ndef test_consistency():\n # need to construct an overflow\n major_axis = list(range(70000))\n minor_axis = list(range(10))\n\n major_codes = np.arange(70000)\n minor_codes = np.repeat(range(10), 7000)\n\n # the fact that is works means it's consistent\n index = MultiIndex(\n levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]\n )\n\n # inconsistent\n major_codes = np.array([0, 0, 1, 1, 1, 2, 2, 3, 3])\n minor_codes = np.array([0, 1, 0, 1, 1, 0, 1, 0, 1])\n index = MultiIndex(\n levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]\n )\n\n assert index.is_unique is False\n\n\n@pytest.mark.slow\ndef test_hash_collisions(monkeypatch):\n # non-smoke test that we don't get hash collisions\n size_cutoff = 50\n with monkeypatch.context() as m:\n m.setattr(libindex, "_SIZE_CUTOFF", size_cutoff)\n index = MultiIndex.from_product(\n [np.arange(8), np.arange(8)], names=["one", "two"]\n )\n result = index.get_indexer(index.values)\n tm.assert_numpy_array_equal(result, np.arange(len(index), dtype="intp"))\n\n for i in [0, 1, len(index) - 2, len(index) - 1]:\n result = index.get_loc(index[i])\n assert result == i\n\n\ndef test_dims():\n pass\n\n\ndef test_take_invalid_kwargs():\n vals = [["A", "B"], [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")]]\n idx = MultiIndex.from_product(vals, names=["str", "dt"])\n indices = [1, 2]\n\n msg = r"take\(\) got an unexpected keyword argument 'foo'"\n with pytest.raises(TypeError, match=msg):\n idx.take(indices, foo=2)\n\n msg = "the 'out' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n idx.take(indices, out=indices)\n\n msg = "the 'mode' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n idx.take(indices, mode="clip")\n\n\ndef test_isna_behavior(idx):\n # should not segfault GH5123\n # NOTE: if MI representation changes, may make sense to allow\n # isna(MI)\n msg = "isna is not defined for MultiIndex"\n with pytest.raises(NotImplementedError, match=msg):\n pd.isna(idx)\n\n\ndef test_large_multiindex_error(monkeypatch):\n # GH12527\n size_cutoff = 50\n with monkeypatch.context() as m:\n m.setattr(libindex, "_SIZE_CUTOFF", size_cutoff)\n df_below_cutoff = pd.DataFrame(\n 1,\n index=MultiIndex.from_product([[1, 2], range(size_cutoff - 1)]),\n columns=["dest"],\n )\n with pytest.raises(KeyError, match=r"^\(-1, 0\)$"):\n df_below_cutoff.loc[(-1, 0), "dest"]\n with pytest.raises(KeyError, match=r"^\(3, 0\)$"):\n df_below_cutoff.loc[(3, 0), "dest"]\n df_above_cutoff = pd.DataFrame(\n 1,\n index=MultiIndex.from_product([[1, 2], range(size_cutoff + 1)]),\n columns=["dest"],\n )\n with pytest.raises(KeyError, match=r"^\(-1, 0\)$"):\n df_above_cutoff.loc[(-1, 0), "dest"]\n with pytest.raises(KeyError, match=r"^\(3, 0\)$"):\n df_above_cutoff.loc[(3, 0), "dest"]\n\n\ndef test_mi_hashtable_populated_attribute_error(monkeypatch):\n # GH 18165\n monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 50)\n r = range(50)\n df = pd.DataFrame({"a": r, "b": r}, index=MultiIndex.from_arrays([r, r]))\n\n msg = "'Series' object has no attribute 'foo'"\n with pytest.raises(AttributeError, match=msg):\n df["a"].foo()\n\n\ndef test_can_hold_identifiers(idx):\n key = idx[0]\n assert idx._can_hold_identifiers_and_holds_name(key) is True\n\n\ndef test_metadata_immutable(idx):\n levels, codes = idx.levels, idx.codes\n # shouldn't be able to set at either the top level or base level\n mutable_regex = re.compile("does not support mutable operations")\n with pytest.raises(TypeError, match=mutable_regex):\n levels[0] = levels[0]\n with pytest.raises(TypeError, match=mutable_regex):\n levels[0][0] = levels[0][0]\n # ditto for labels\n with pytest.raises(TypeError, match=mutable_regex):\n codes[0] = codes[0]\n with pytest.raises(ValueError, match="assignment destination is read-only"):\n codes[0][0] = codes[0][0]\n # and for names\n names = idx.names\n with pytest.raises(TypeError, match=mutable_regex):\n names[0] = names[0]\n\n\ndef test_level_setting_resets_attributes():\n ind = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]])\n assert ind.is_monotonic_increasing\n ind = ind.set_levels([["A", "B"], [1, 3, 2]])\n # if this fails, probably didn't reset the cache correctly.\n assert not ind.is_monotonic_increasing\n\n\ndef test_rangeindex_fallback_coercion_bug():\n # GH 12893\n df1 = pd.DataFrame(np.arange(100).reshape((10, 10)))\n df2 = pd.DataFrame(np.arange(100).reshape((10, 10)))\n df = pd.concat(\n {"df1": df1.stack(future_stack=True), "df2": df2.stack(future_stack=True)},\n axis=1,\n )\n df.index.names = ["fizz", "buzz"]\n\n expected = pd.DataFrame(\n {"df2": np.arange(100), "df1": np.arange(100)},\n index=MultiIndex.from_product([range(10), range(10)], names=["fizz", "buzz"]),\n )\n tm.assert_frame_equal(df, expected, check_like=True)\n\n result = df.index.get_level_values("fizz")\n expected = Index(np.arange(10, dtype=np.int64), name="fizz").repeat(10)\n tm.assert_index_equal(result, expected)\n\n result = df.index.get_level_values("buzz")\n expected = Index(np.tile(np.arange(10, dtype=np.int64), 10), name="buzz")\n tm.assert_index_equal(result, expected)\n\n\ndef test_memory_usage(idx):\n result = idx.memory_usage()\n if len(idx):\n idx.get_loc(idx[0])\n result2 = idx.memory_usage()\n result3 = idx.memory_usage(deep=True)\n\n # RangeIndex, IntervalIndex\n # don't have engines\n if not isinstance(idx, (RangeIndex, IntervalIndex)):\n assert result2 > result\n\n if idx.inferred_type == "object":\n assert result3 > result2\n\n else:\n # we report 0 for no-length\n assert result == 0\n\n\ndef test_nlevels(idx):\n assert idx.nlevels == 2\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_integrity.py
test_integrity.py
Python
9,031
0.95
0.124567
0.104072
python-kit
634
2024-05-01T11:13:32.087037
MIT
true
8e84c5a276e4b6a906b683081a044403
import numpy as np\nimport pytest\n\nfrom pandas import MultiIndex\nimport pandas._testing as tm\n\n\ndef test_isin_nan():\n idx = MultiIndex.from_arrays([["foo", "bar"], [1.0, np.nan]])\n tm.assert_numpy_array_equal(idx.isin([("bar", np.nan)]), np.array([False, True]))\n tm.assert_numpy_array_equal(\n idx.isin([("bar", float("nan"))]), np.array([False, True])\n )\n\n\ndef test_isin_missing(nulls_fixture):\n # GH48905\n mi1 = MultiIndex.from_tuples([(1, nulls_fixture)])\n mi2 = MultiIndex.from_tuples([(1, 1), (1, 2)])\n result = mi2.isin(mi1)\n expected = np.array([False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_isin():\n values = [("foo", 2), ("bar", 3), ("quux", 4)]\n\n idx = MultiIndex.from_arrays([["qux", "baz", "foo", "bar"], np.arange(4)])\n result = idx.isin(values)\n expected = np.array([False, False, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n # empty, return dtype bool\n idx = MultiIndex.from_arrays([[], []])\n result = idx.isin(values)\n assert len(result) == 0\n assert result.dtype == np.bool_\n\n\ndef test_isin_level_kwarg():\n idx = MultiIndex.from_arrays([["qux", "baz", "foo", "bar"], np.arange(4)])\n\n vals_0 = ["foo", "bar", "quux"]\n vals_1 = [2, 3, 10]\n\n expected = np.array([False, False, True, True])\n tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=0))\n tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=-2))\n\n tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=1))\n tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=-1))\n\n msg = "Too many levels: Index has only 2 levels, not 6"\n with pytest.raises(IndexError, match=msg):\n idx.isin(vals_0, level=5)\n msg = "Too many levels: Index has only 2 levels, -5 is not a valid level number"\n with pytest.raises(IndexError, match=msg):\n idx.isin(vals_0, level=-5)\n\n with pytest.raises(KeyError, match=r"'Level 1\.0 not found'"):\n idx.isin(vals_0, level=1.0)\n with pytest.raises(KeyError, match=r"'Level -1\.0 not found'"):\n idx.isin(vals_1, level=-1.0)\n with pytest.raises(KeyError, match="'Level A not found'"):\n idx.isin(vals_1, level="A")\n\n idx.names = ["A", "B"]\n tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level="A"))\n tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level="B"))\n\n with pytest.raises(KeyError, match="'Level C not found'"):\n idx.isin(vals_1, level="C")\n\n\n@pytest.mark.parametrize(\n "labels,expected,level",\n [\n ([("b", np.nan)], np.array([False, False, True]), None),\n ([np.nan, "a"], np.array([True, True, False]), 0),\n (["d", np.nan], np.array([False, True, True]), 1),\n ],\n)\ndef test_isin_multi_index_with_missing_value(labels, expected, level):\n # GH 19132\n midx = MultiIndex.from_arrays([[np.nan, "a", "b"], ["c", "d", np.nan]])\n result = midx.isin(labels, level=level)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_isin_empty():\n # GH#51599\n midx = MultiIndex.from_arrays([[1, 2], [3, 4]])\n result = midx.isin([])\n expected = np.array([False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_isin_generator():\n # GH#52568\n midx = MultiIndex.from_tuples([(1, 2)])\n result = midx.isin(x for x in [(1, 2)])\n expected = np.array([True])\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_isin.py
test_isin.py
Python
3,426
0.95
0.07767
0.063291
python-kit
763
2024-12-14T11:17:44.603079
GPL-3.0
true
fe137f15f39db32a23022fe0a45e0212
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n Interval,\n MultiIndex,\n Series,\n StringDtype,\n)\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize(\n "other", [Index(["three", "one", "two"]), Index(["one"]), Index(["one", "three"])]\n)\ndef test_join_level(idx, other, join_type):\n join_index, lidx, ridx = other.join(\n idx, how=join_type, level="second", return_indexers=True\n )\n\n exp_level = other.join(idx.levels[1], how=join_type)\n assert join_index.levels[0].equals(idx.levels[0])\n assert join_index.levels[1].equals(exp_level)\n\n # pare down levels\n mask = np.array([x[1] in exp_level for x in idx], dtype=bool)\n exp_values = idx.values[mask]\n tm.assert_numpy_array_equal(join_index.values, exp_values)\n\n if join_type in ("outer", "inner"):\n join_index2, ridx2, lidx2 = idx.join(\n other, how=join_type, level="second", return_indexers=True\n )\n\n assert join_index.equals(join_index2)\n tm.assert_numpy_array_equal(lidx, lidx2)\n tm.assert_numpy_array_equal(ridx, ridx2)\n tm.assert_numpy_array_equal(join_index2.values, exp_values)\n\n\ndef test_join_level_corner_case(idx):\n # some corner cases\n index = Index(["three", "one", "two"])\n result = index.join(idx, level="second")\n assert isinstance(result, MultiIndex)\n\n with pytest.raises(TypeError, match="Join.*MultiIndex.*ambiguous"):\n idx.join(idx, level=1)\n\n\ndef test_join_self(idx, join_type):\n result = idx.join(idx, how=join_type)\n expected = idx\n if join_type == "outer":\n expected = expected.sort_values()\n tm.assert_index_equal(result, expected)\n\n\ndef test_join_multi():\n # GH 10665\n midx = MultiIndex.from_product([np.arange(4), np.arange(4)], names=["a", "b"])\n idx = Index([1, 2, 5], name="b")\n\n # inner\n jidx, lidx, ridx = midx.join(idx, how="inner", return_indexers=True)\n exp_idx = MultiIndex.from_product([np.arange(4), [1, 2]], names=["a", "b"])\n exp_lidx = np.array([1, 2, 5, 6, 9, 10, 13, 14], dtype=np.intp)\n exp_ridx = np.array([0, 1, 0, 1, 0, 1, 0, 1], dtype=np.intp)\n tm.assert_index_equal(jidx, exp_idx)\n tm.assert_numpy_array_equal(lidx, exp_lidx)\n tm.assert_numpy_array_equal(ridx, exp_ridx)\n # flip\n jidx, ridx, lidx = idx.join(midx, how="inner", return_indexers=True)\n tm.assert_index_equal(jidx, exp_idx)\n tm.assert_numpy_array_equal(lidx, exp_lidx)\n tm.assert_numpy_array_equal(ridx, exp_ridx)\n\n # keep MultiIndex\n jidx, lidx, ridx = midx.join(idx, how="left", return_indexers=True)\n exp_ridx = np.array(\n [-1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1], dtype=np.intp\n )\n tm.assert_index_equal(jidx, midx)\n assert lidx is None\n tm.assert_numpy_array_equal(ridx, exp_ridx)\n # flip\n jidx, ridx, lidx = idx.join(midx, how="right", return_indexers=True)\n tm.assert_index_equal(jidx, midx)\n assert lidx is None\n tm.assert_numpy_array_equal(ridx, exp_ridx)\n\n\ndef test_join_multi_wrong_order():\n # GH 25760\n # GH 28956\n\n midx1 = MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"])\n midx2 = MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"])\n\n join_idx, lidx, ridx = midx1.join(midx2, return_indexers=True)\n\n exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp)\n\n tm.assert_index_equal(midx1, join_idx)\n assert lidx is None\n tm.assert_numpy_array_equal(ridx, exp_ridx)\n\n\ndef test_join_multi_return_indexers():\n # GH 34074\n\n midx1 = MultiIndex.from_product([[1, 2], [3, 4], [5, 6]], names=["a", "b", "c"])\n midx2 = MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"])\n\n result = midx1.join(midx2, return_indexers=False)\n tm.assert_index_equal(result, midx1)\n\n\ndef test_join_overlapping_interval_level():\n # GH 44096\n idx_1 = MultiIndex.from_tuples(\n [\n (1, Interval(0.0, 1.0)),\n (1, Interval(1.0, 2.0)),\n (1, Interval(2.0, 5.0)),\n (2, Interval(0.0, 1.0)),\n (2, Interval(1.0, 3.0)), # interval limit is here at 3.0, not at 2.0\n (2, Interval(3.0, 5.0)),\n ],\n names=["num", "interval"],\n )\n\n idx_2 = MultiIndex.from_tuples(\n [\n (1, Interval(2.0, 5.0)),\n (1, Interval(0.0, 1.0)),\n (1, Interval(1.0, 2.0)),\n (2, Interval(3.0, 5.0)),\n (2, Interval(0.0, 1.0)),\n (2, Interval(1.0, 3.0)),\n ],\n names=["num", "interval"],\n )\n\n expected = MultiIndex.from_tuples(\n [\n (1, Interval(0.0, 1.0)),\n (1, Interval(1.0, 2.0)),\n (1, Interval(2.0, 5.0)),\n (2, Interval(0.0, 1.0)),\n (2, Interval(1.0, 3.0)),\n (2, Interval(3.0, 5.0)),\n ],\n names=["num", "interval"],\n )\n result = idx_1.join(idx_2, how="outer")\n\n tm.assert_index_equal(result, expected)\n\n\ndef test_join_midx_ea():\n # GH#49277\n midx = MultiIndex.from_arrays(\n [Series([1, 1, 3], dtype="Int64"), Series([1, 2, 3], dtype="Int64")],\n names=["a", "b"],\n )\n midx2 = MultiIndex.from_arrays(\n [Series([1], dtype="Int64"), Series([3], dtype="Int64")], names=["a", "c"]\n )\n result = midx.join(midx2, how="inner")\n expected = MultiIndex.from_arrays(\n [\n Series([1, 1], dtype="Int64"),\n Series([1, 2], dtype="Int64"),\n Series([3, 3], dtype="Int64"),\n ],\n names=["a", "b", "c"],\n )\n tm.assert_index_equal(result, expected)\n\n\ndef test_join_midx_string():\n # GH#49277\n midx = MultiIndex.from_arrays(\n [\n Series(["a", "a", "c"], dtype=StringDtype()),\n Series(["a", "b", "c"], dtype=StringDtype()),\n ],\n names=["a", "b"],\n )\n midx2 = MultiIndex.from_arrays(\n [Series(["a"], dtype=StringDtype()), Series(["c"], dtype=StringDtype())],\n names=["a", "c"],\n )\n result = midx.join(midx2, how="inner")\n expected = MultiIndex.from_arrays(\n [\n Series(["a", "a"], dtype=StringDtype()),\n Series(["a", "b"], dtype=StringDtype()),\n Series(["c", "c"], dtype=StringDtype()),\n ],\n names=["a", "b", "c"],\n )\n tm.assert_index_equal(result, expected)\n\n\ndef test_join_multi_with_nan():\n # GH29252\n df1 = DataFrame(\n data={"col1": [1.1, 1.2]},\n index=MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"]),\n )\n df2 = DataFrame(\n data={"col2": [2.1, 2.2]},\n index=MultiIndex.from_product([["A"], [np.nan, 2.0]], names=["id1", "id2"]),\n )\n result = df1.join(df2)\n expected = DataFrame(\n data={"col1": [1.1, 1.2], "col2": [np.nan, 2.2]},\n index=MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"]),\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize("val", [0, 5])\ndef test_join_dtypes(any_numeric_ea_dtype, val):\n # GH#49830\n midx = MultiIndex.from_arrays([Series([1, 2], dtype=any_numeric_ea_dtype), [3, 4]])\n midx2 = MultiIndex.from_arrays(\n [Series([1, val, val], dtype=any_numeric_ea_dtype), [3, 4, 4]]\n )\n result = midx.join(midx2, how="outer")\n expected = MultiIndex.from_arrays(\n [Series([val, val, 1, 2], dtype=any_numeric_ea_dtype), [4, 4, 3, 4]]\n ).sort_values()\n tm.assert_index_equal(result, expected)\n\n\ndef test_join_dtypes_all_nan(any_numeric_ea_dtype):\n # GH#49830\n midx = MultiIndex.from_arrays(\n [Series([1, 2], dtype=any_numeric_ea_dtype), [np.nan, np.nan]]\n )\n midx2 = MultiIndex.from_arrays(\n [Series([1, 0, 0], dtype=any_numeric_ea_dtype), [np.nan, np.nan, np.nan]]\n )\n result = midx.join(midx2, how="outer")\n expected = MultiIndex.from_arrays(\n [\n Series([0, 0, 1, 2], dtype=any_numeric_ea_dtype),\n [np.nan, np.nan, np.nan, np.nan],\n ]\n )\n tm.assert_index_equal(result, expected)\n\n\ndef test_join_index_levels():\n # GH#53093\n midx = midx = MultiIndex.from_tuples([("a", "2019-02-01"), ("a", "2019-02-01")])\n midx2 = MultiIndex.from_tuples([("a", "2019-01-31")])\n result = midx.join(midx2, how="outer")\n expected = MultiIndex.from_tuples(\n [("a", "2019-01-31"), ("a", "2019-02-01"), ("a", "2019-02-01")]\n )\n tm.assert_index_equal(result.levels[1], expected.levels[1])\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_join.py
test_join.py
Python
8,440
0.95
0.059701
0.075556
react-lib
223
2024-10-01T10:31:14.501705
BSD-3-Clause
true
19f4785784fab870423f4f5b4d925a51
from pandas import MultiIndex\n\n\nclass TestIsLexsorted:\n def test_is_lexsorted(self):\n levels = [[0, 1], [0, 1, 2]]\n\n index = MultiIndex(\n levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]]\n )\n assert index._is_lexsorted()\n\n index = MultiIndex(\n levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]]\n )\n assert not index._is_lexsorted()\n\n index = MultiIndex(\n levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]]\n )\n assert not index._is_lexsorted()\n assert index._lexsort_depth == 0\n\n\nclass TestLexsortDepth:\n def test_lexsort_depth(self):\n # Test that lexsort_depth return the correct sortorder\n # when it was given to the MultiIndex const.\n # GH#28518\n\n levels = [[0, 1], [0, 1, 2]]\n\n index = MultiIndex(\n levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], sortorder=2\n )\n assert index._lexsort_depth == 2\n\n index = MultiIndex(\n levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=1\n )\n assert index._lexsort_depth == 1\n\n index = MultiIndex(\n levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=0\n )\n assert index._lexsort_depth == 0\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_lexsort.py
test_lexsort.py
Python
1,358
0.95
0.086957
0.085714
node-utils
408
2023-09-14T15:19:21.987882
MIT
true
db5c056157a203525fbb2f7c6622c744
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import MultiIndex\nimport pandas._testing as tm\n\n\ndef test_fillna(idx):\n # GH 11343\n msg = "isna is not defined for MultiIndex"\n with pytest.raises(NotImplementedError, match=msg):\n idx.fillna(idx[0])\n\n\ndef test_dropna():\n # GH 6194\n idx = MultiIndex.from_arrays(\n [\n [1, np.nan, 3, np.nan, 5],\n [1, 2, np.nan, np.nan, 5],\n ["a", "b", "c", np.nan, "e"],\n ]\n )\n\n exp = MultiIndex.from_arrays([[1, 5], [1, 5], ["a", "e"]])\n tm.assert_index_equal(idx.dropna(), exp)\n tm.assert_index_equal(idx.dropna(how="any"), exp)\n\n exp = MultiIndex.from_arrays(\n [[1, np.nan, 3, 5], [1, 2, np.nan, 5], ["a", "b", "c", "e"]]\n )\n tm.assert_index_equal(idx.dropna(how="all"), exp)\n\n msg = "invalid how option: xxx"\n with pytest.raises(ValueError, match=msg):\n idx.dropna(how="xxx")\n\n # GH26408\n # test if missing values are dropped for multiindex constructed\n # from codes and values\n idx = MultiIndex(\n levels=[[np.nan, None, pd.NaT, "128", 2], [np.nan, None, pd.NaT, "128", 2]],\n codes=[[0, -1, 1, 2, 3, 4], [0, -1, 3, 3, 3, 4]],\n )\n expected = MultiIndex.from_arrays([["128", 2], ["128", 2]])\n tm.assert_index_equal(idx.dropna(), expected)\n tm.assert_index_equal(idx.dropna(how="any"), expected)\n\n expected = MultiIndex.from_arrays(\n [[np.nan, np.nan, "128", 2], ["128", "128", "128", 2]]\n )\n tm.assert_index_equal(idx.dropna(how="all"), expected)\n\n\ndef test_nulls(idx):\n # this is really a smoke test for the methods\n # as these are adequately tested for function elsewhere\n\n msg = "isna is not defined for MultiIndex"\n with pytest.raises(NotImplementedError, match=msg):\n idx.isna()\n\n\n@pytest.mark.xfail(reason="isna is not defined for MultiIndex")\ndef test_hasnans_isnans(idx):\n # GH 11343, added tests for hasnans / isnans\n index = idx.copy()\n\n # cases in indices doesn't include NaN\n expected = np.array([False] * len(index), dtype=bool)\n tm.assert_numpy_array_equal(index._isnan, expected)\n assert index.hasnans is False\n\n index = idx.copy()\n values = index.values\n values[1] = np.nan\n\n index = type(idx)(values)\n\n expected = np.array([False] * len(index), dtype=bool)\n expected[1] = True\n tm.assert_numpy_array_equal(index._isnan, expected)\n assert index.hasnans is True\n\n\ndef test_nan_stays_float():\n # GH 7031\n idx0 = MultiIndex(levels=[["A", "B"], []], codes=[[1, 0], [-1, -1]], names=[0, 1])\n idx1 = MultiIndex(levels=[["C"], ["D"]], codes=[[0], [0]], names=[0, 1])\n idxm = idx0.join(idx1, how="outer")\n assert pd.isna(idx0.get_level_values(1)).all()\n # the following failed in 0.14.1\n assert pd.isna(idxm.get_level_values(1)[:-1]).all()\n\n df0 = pd.DataFrame([[1, 2]], index=idx0)\n df1 = pd.DataFrame([[3, 4]], index=idx1)\n dfm = df0 - df1\n assert pd.isna(df0.index.get_level_values(1)).all()\n # the following failed in 0.14.1\n assert pd.isna(dfm.index.get_level_values(1)[:-1]).all()\n\n\ndef test_tuples_have_na():\n index = MultiIndex(\n levels=[[1, 0], [0, 1, 2, 3]],\n codes=[[1, 1, 1, 1, -1, 0, 0, 0], [0, 1, 2, 3, 0, 1, 2, 3]],\n )\n\n assert pd.isna(index[4][0])\n assert pd.isna(index.values[4][0])\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_missing.py
test_missing.py
Python
3,348
0.95
0.135135
0.139535
awesome-app
889
2023-07-29T03:48:29.658534
Apache-2.0
true
253dcb309c62122ea6905c4221529329
import numpy as np\nimport pytest\n\nfrom pandas import (\n Index,\n MultiIndex,\n)\n\n\ndef test_is_monotonic_increasing_lexsorted(lexsorted_two_level_string_multiindex):\n # string ordering\n mi = lexsorted_two_level_string_multiindex\n assert mi.is_monotonic_increasing is False\n assert Index(mi.values).is_monotonic_increasing is False\n assert mi._is_strictly_monotonic_increasing is False\n assert Index(mi.values)._is_strictly_monotonic_increasing is False\n\n\ndef test_is_monotonic_increasing():\n i = MultiIndex.from_product([np.arange(10), np.arange(10)], names=["one", "two"])\n assert i.is_monotonic_increasing is True\n assert i._is_strictly_monotonic_increasing is True\n assert Index(i.values).is_monotonic_increasing is True\n assert i._is_strictly_monotonic_increasing is True\n\n i = MultiIndex.from_product(\n [np.arange(10, 0, -1), np.arange(10)], names=["one", "two"]\n )\n assert i.is_monotonic_increasing is False\n assert i._is_strictly_monotonic_increasing is False\n assert Index(i.values).is_monotonic_increasing is False\n assert Index(i.values)._is_strictly_monotonic_increasing is False\n\n i = MultiIndex.from_product(\n [np.arange(10), np.arange(10, 0, -1)], names=["one", "two"]\n )\n assert i.is_monotonic_increasing is False\n assert i._is_strictly_monotonic_increasing is False\n assert Index(i.values).is_monotonic_increasing is False\n assert Index(i.values)._is_strictly_monotonic_increasing is False\n\n i = MultiIndex.from_product([[1.0, np.nan, 2.0], ["a", "b", "c"]])\n assert i.is_monotonic_increasing is False\n assert i._is_strictly_monotonic_increasing is False\n assert Index(i.values).is_monotonic_increasing is False\n assert Index(i.values)._is_strictly_monotonic_increasing is False\n\n i = MultiIndex(\n levels=[["bar", "baz", "foo", "qux"], ["mom", "next", "zenith"]],\n codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],\n names=["first", "second"],\n )\n assert i.is_monotonic_increasing is True\n assert Index(i.values).is_monotonic_increasing is True\n assert i._is_strictly_monotonic_increasing is True\n assert Index(i.values)._is_strictly_monotonic_increasing is True\n\n # mixed levels, hits the TypeError\n i = MultiIndex(\n levels=[\n [1, 2, 3, 4],\n [\n "gb00b03mlx29",\n "lu0197800237",\n "nl0000289783",\n "nl0000289965",\n "nl0000301109",\n ],\n ],\n codes=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]],\n names=["household_id", "asset_id"],\n )\n\n assert i.is_monotonic_increasing is False\n assert i._is_strictly_monotonic_increasing is False\n\n # empty\n i = MultiIndex.from_arrays([[], []])\n assert i.is_monotonic_increasing is True\n assert Index(i.values).is_monotonic_increasing is True\n assert i._is_strictly_monotonic_increasing is True\n assert Index(i.values)._is_strictly_monotonic_increasing is True\n\n\ndef test_is_monotonic_decreasing():\n i = MultiIndex.from_product(\n [np.arange(9, -1, -1), np.arange(9, -1, -1)], names=["one", "two"]\n )\n assert i.is_monotonic_decreasing is True\n assert i._is_strictly_monotonic_decreasing is True\n assert Index(i.values).is_monotonic_decreasing is True\n assert i._is_strictly_monotonic_decreasing is True\n\n i = MultiIndex.from_product(\n [np.arange(10), np.arange(10, 0, -1)], names=["one", "two"]\n )\n assert i.is_monotonic_decreasing is False\n assert i._is_strictly_monotonic_decreasing is False\n assert Index(i.values).is_monotonic_decreasing is False\n assert Index(i.values)._is_strictly_monotonic_decreasing is False\n\n i = MultiIndex.from_product(\n [np.arange(10, 0, -1), np.arange(10)], names=["one", "two"]\n )\n assert i.is_monotonic_decreasing is False\n assert i._is_strictly_monotonic_decreasing is False\n assert Index(i.values).is_monotonic_decreasing is False\n assert Index(i.values)._is_strictly_monotonic_decreasing is False\n\n i = MultiIndex.from_product([[2.0, np.nan, 1.0], ["c", "b", "a"]])\n assert i.is_monotonic_decreasing is False\n assert i._is_strictly_monotonic_decreasing is False\n assert Index(i.values).is_monotonic_decreasing is False\n assert Index(i.values)._is_strictly_monotonic_decreasing is False\n\n # string ordering\n i = MultiIndex(\n levels=[["qux", "foo", "baz", "bar"], ["three", "two", "one"]],\n codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],\n names=["first", "second"],\n )\n assert i.is_monotonic_decreasing is False\n assert Index(i.values).is_monotonic_decreasing is False\n assert i._is_strictly_monotonic_decreasing is False\n assert Index(i.values)._is_strictly_monotonic_decreasing is False\n\n i = MultiIndex(\n levels=[["qux", "foo", "baz", "bar"], ["zenith", "next", "mom"]],\n codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],\n names=["first", "second"],\n )\n assert i.is_monotonic_decreasing is True\n assert Index(i.values).is_monotonic_decreasing is True\n assert i._is_strictly_monotonic_decreasing is True\n assert Index(i.values)._is_strictly_monotonic_decreasing is True\n\n # mixed levels, hits the TypeError\n i = MultiIndex(\n levels=[\n [4, 3, 2, 1],\n [\n "nl0000301109",\n "nl0000289965",\n "nl0000289783",\n "lu0197800237",\n "gb00b03mlx29",\n ],\n ],\n codes=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]],\n names=["household_id", "asset_id"],\n )\n\n assert i.is_monotonic_decreasing is False\n assert i._is_strictly_monotonic_decreasing is False\n\n # empty\n i = MultiIndex.from_arrays([[], []])\n assert i.is_monotonic_decreasing is True\n assert Index(i.values).is_monotonic_decreasing is True\n assert i._is_strictly_monotonic_decreasing is True\n assert Index(i.values)._is_strictly_monotonic_decreasing is True\n\n\ndef test_is_strictly_monotonic_increasing():\n idx = MultiIndex(\n levels=[["bar", "baz"], ["mom", "next"]], codes=[[0, 0, 1, 1], [0, 0, 0, 1]]\n )\n assert idx.is_monotonic_increasing is True\n assert idx._is_strictly_monotonic_increasing is False\n\n\ndef test_is_strictly_monotonic_decreasing():\n idx = MultiIndex(\n levels=[["baz", "bar"], ["next", "mom"]], codes=[[0, 0, 1, 1], [0, 0, 0, 1]]\n )\n assert idx.is_monotonic_decreasing is True\n assert idx._is_strictly_monotonic_decreasing is False\n\n\n@pytest.mark.parametrize("attr", ["is_monotonic_increasing", "is_monotonic_decreasing"])\n@pytest.mark.parametrize(\n "values",\n [[(np.nan,), (1,), (2,)], [(1,), (np.nan,), (2,)], [(1,), (2,), (np.nan,)]],\n)\ndef test_is_monotonic_with_nans(values, attr):\n # GH: 37220\n idx = MultiIndex.from_tuples(values, names=["test"])\n assert getattr(idx, attr) is False\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_monotonic.py
test_monotonic.py
Python
7,007
0.95
0.031915
0.04375
node-utils
61
2023-07-25T10:06:15.664580
BSD-3-Clause
true
6641485ec5d8cf64708f2e37e4503db9
import pytest\n\nimport pandas as pd\nfrom pandas import MultiIndex\nimport pandas._testing as tm\n\n\ndef check_level_names(index, names):\n assert [level.name for level in index.levels] == list(names)\n\n\ndef test_slice_keep_name():\n x = MultiIndex.from_tuples([("a", "b"), (1, 2), ("c", "d")], names=["x", "y"])\n assert x[1:].names == x.names\n\n\ndef test_index_name_retained():\n # GH9857\n result = pd.DataFrame({"x": [1, 2, 6], "y": [2, 2, 8], "z": [-5, 0, 5]})\n result = result.set_index("z")\n result.loc[10] = [9, 10]\n df_expected = pd.DataFrame(\n {"x": [1, 2, 6, 9], "y": [2, 2, 8, 10], "z": [-5, 0, 5, 10]}\n )\n df_expected = df_expected.set_index("z")\n tm.assert_frame_equal(result, df_expected)\n\n\ndef test_changing_names(idx):\n assert [level.name for level in idx.levels] == ["first", "second"]\n\n view = idx.view()\n copy = idx.copy()\n shallow_copy = idx._view()\n\n # changing names should not change level names on object\n new_names = [name + "a" for name in idx.names]\n idx.names = new_names\n check_level_names(idx, ["firsta", "seconda"])\n\n # and not on copies\n check_level_names(view, ["first", "second"])\n check_level_names(copy, ["first", "second"])\n check_level_names(shallow_copy, ["first", "second"])\n\n # and copies shouldn't change original\n shallow_copy.names = [name + "c" for name in shallow_copy.names]\n check_level_names(idx, ["firsta", "seconda"])\n\n\ndef test_take_preserve_name(idx):\n taken = idx.take([3, 0, 1])\n assert taken.names == idx.names\n\n\ndef test_copy_names():\n # Check that adding a "names" parameter to the copy is honored\n # GH14302\n multi_idx = MultiIndex.from_tuples([(1, 2), (3, 4)], names=["MyName1", "MyName2"])\n multi_idx1 = multi_idx.copy()\n\n assert multi_idx.equals(multi_idx1)\n assert multi_idx.names == ["MyName1", "MyName2"]\n assert multi_idx1.names == ["MyName1", "MyName2"]\n\n multi_idx2 = multi_idx.copy(names=["NewName1", "NewName2"])\n\n assert multi_idx.equals(multi_idx2)\n assert multi_idx.names == ["MyName1", "MyName2"]\n assert multi_idx2.names == ["NewName1", "NewName2"]\n\n multi_idx3 = multi_idx.copy(name=["NewName1", "NewName2"])\n\n assert multi_idx.equals(multi_idx3)\n assert multi_idx.names == ["MyName1", "MyName2"]\n assert multi_idx3.names == ["NewName1", "NewName2"]\n\n # gh-35592\n with pytest.raises(ValueError, match="Length of new names must be 2, got 1"):\n multi_idx.copy(names=["mario"])\n\n with pytest.raises(TypeError, match="MultiIndex.name must be a hashable type"):\n multi_idx.copy(names=[["mario"], ["luigi"]])\n\n\ndef test_names(idx):\n # names are assigned in setup\n assert idx.names == ["first", "second"]\n level_names = [level.name for level in idx.levels]\n assert level_names == idx.names\n\n # setting bad names on existing\n index = idx\n with pytest.raises(ValueError, match="^Length of names"):\n setattr(index, "names", list(index.names) + ["third"])\n with pytest.raises(ValueError, match="^Length of names"):\n setattr(index, "names", [])\n\n # initializing with bad names (should always be equivalent)\n major_axis, minor_axis = idx.levels\n major_codes, minor_codes = idx.codes\n with pytest.raises(ValueError, match="^Length of names"):\n MultiIndex(\n levels=[major_axis, minor_axis],\n codes=[major_codes, minor_codes],\n names=["first"],\n )\n with pytest.raises(ValueError, match="^Length of names"):\n MultiIndex(\n levels=[major_axis, minor_axis],\n codes=[major_codes, minor_codes],\n names=["first", "second", "third"],\n )\n\n # names are assigned on index, but not transferred to the levels\n index.names = ["a", "b"]\n level_names = [level.name for level in index.levels]\n assert level_names == ["a", "b"]\n\n\ndef test_duplicate_level_names_access_raises(idx):\n # GH19029\n idx.names = ["foo", "foo"]\n with pytest.raises(ValueError, match="name foo occurs multiple times"):\n idx._get_level_number("foo")\n\n\ndef test_get_names_from_levels():\n idx = MultiIndex.from_product([["a"], [1, 2]], names=["a", "b"])\n\n assert idx.levels[0].name == "a"\n assert idx.levels[1].name == "b"\n\n\ndef test_setting_names_from_levels_raises():\n idx = MultiIndex.from_product([["a"], [1, 2]], names=["a", "b"])\n with pytest.raises(RuntimeError, match="set_names"):\n idx.levels[0].name = "foo"\n\n with pytest.raises(RuntimeError, match="set_names"):\n idx.levels[1].name = "foo"\n\n new = pd.Series(1, index=idx.levels[0])\n with pytest.raises(RuntimeError, match="set_names"):\n new.index.name = "bar"\n\n assert pd.Index._no_setting_name is False\n assert pd.RangeIndex._no_setting_name is False\n\n\n@pytest.mark.parametrize("func", ["rename", "set_names"])\n@pytest.mark.parametrize(\n "rename_dict, exp_names",\n [\n ({"x": "z"}, ["z", "y", "z"]),\n ({"x": "z", "y": "x"}, ["z", "x", "z"]),\n ({"y": "z"}, ["x", "z", "x"]),\n ({}, ["x", "y", "x"]),\n ({"z": "a"}, ["x", "y", "x"]),\n ({"y": "z", "a": "b"}, ["x", "z", "x"]),\n ],\n)\ndef test_name_mi_with_dict_like_duplicate_names(func, rename_dict, exp_names):\n # GH#20421\n mi = MultiIndex.from_arrays([[1, 2], [3, 4], [5, 6]], names=["x", "y", "x"])\n result = getattr(mi, func)(rename_dict)\n expected = MultiIndex.from_arrays([[1, 2], [3, 4], [5, 6]], names=exp_names)\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("func", ["rename", "set_names"])\n@pytest.mark.parametrize(\n "rename_dict, exp_names",\n [\n ({"x": "z"}, ["z", "y"]),\n ({"x": "z", "y": "x"}, ["z", "x"]),\n ({"a": "z"}, ["x", "y"]),\n ({}, ["x", "y"]),\n ],\n)\ndef test_name_mi_with_dict_like(func, rename_dict, exp_names):\n # GH#20421\n mi = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["x", "y"])\n result = getattr(mi, func)(rename_dict)\n expected = MultiIndex.from_arrays([[1, 2], [3, 4]], names=exp_names)\n tm.assert_index_equal(result, expected)\n\n\ndef test_index_name_with_dict_like_raising():\n # GH#20421\n ix = pd.Index([1, 2])\n msg = "Can only pass dict-like as `names` for MultiIndex."\n with pytest.raises(TypeError, match=msg):\n ix.set_names({"x": "z"})\n\n\ndef test_multiindex_name_and_level_raising():\n # GH#20421\n mi = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["x", "y"])\n with pytest.raises(TypeError, match="Can not pass level for dictlike `names`."):\n mi.set_names(names={"x": "z"}, level={"x": "z"})\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_names.py
test_names.py
Python
6,601
0.95
0.109453
0.103896
python-kit
326
2024-09-20T06:48:00.862699
Apache-2.0
true
af9cf93156b200afeb6f69a869cd1e35
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n IndexSlice,\n MultiIndex,\n date_range,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture\ndef df():\n # c1\n # 2016-01-01 00:00:00 a 0\n # b 1\n # c 2\n # 2016-01-01 12:00:00 a 3\n # b 4\n # c 5\n # 2016-01-02 00:00:00 a 6\n # b 7\n # c 8\n # 2016-01-02 12:00:00 a 9\n # b 10\n # c 11\n # 2016-01-03 00:00:00 a 12\n # b 13\n # c 14\n dr = date_range("2016-01-01", "2016-01-03", freq="12h")\n abc = ["a", "b", "c"]\n mi = MultiIndex.from_product([dr, abc])\n frame = DataFrame({"c1": range(15)}, index=mi)\n return frame\n\n\ndef test_partial_string_matching_single_index(df):\n # partial string matching on a single index\n for df_swap in [df.swaplevel(), df.swaplevel(0), df.swaplevel(0, 1)]:\n df_swap = df_swap.sort_index()\n just_a = df_swap.loc["a"]\n result = just_a.loc["2016-01-01"]\n expected = df.loc[IndexSlice[:, "a"], :].iloc[0:2]\n expected.index = expected.index.droplevel(1)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_get_loc_partial_timestamp_multiindex(df):\n mi = df.index\n key = ("2016-01-01", "a")\n loc = mi.get_loc(key)\n\n expected = np.zeros(len(mi), dtype=bool)\n expected[[0, 3]] = True\n tm.assert_numpy_array_equal(loc, expected)\n\n key2 = ("2016-01-02", "a")\n loc2 = mi.get_loc(key2)\n expected2 = np.zeros(len(mi), dtype=bool)\n expected2[[6, 9]] = True\n tm.assert_numpy_array_equal(loc2, expected2)\n\n key3 = ("2016-01", "a")\n loc3 = mi.get_loc(key3)\n expected3 = np.zeros(len(mi), dtype=bool)\n expected3[mi.get_level_values(1).get_loc("a")] = True\n tm.assert_numpy_array_equal(loc3, expected3)\n\n key4 = ("2016", "a")\n loc4 = mi.get_loc(key4)\n expected4 = expected3\n tm.assert_numpy_array_equal(loc4, expected4)\n\n # non-monotonic\n taker = np.arange(len(mi), dtype=np.intp)\n taker[::2] = taker[::-2]\n mi2 = mi.take(taker)\n loc5 = mi2.get_loc(key)\n expected5 = np.zeros(len(mi2), dtype=bool)\n expected5[[3, 14]] = True\n tm.assert_numpy_array_equal(loc5, expected5)\n\n\ndef test_partial_string_timestamp_multiindex(df):\n # GH10331\n df_swap = df.swaplevel(0, 1).sort_index()\n SLC = IndexSlice\n\n # indexing with IndexSlice\n result = df.loc[SLC["2016-01-01":"2016-02-01", :], :]\n expected = df\n tm.assert_frame_equal(result, expected)\n\n # match on secondary index\n result = df_swap.loc[SLC[:, "2016-01-01":"2016-01-01"], :]\n expected = df_swap.iloc[[0, 1, 5, 6, 10, 11]]\n tm.assert_frame_equal(result, expected)\n\n # partial string match on year only\n result = df.loc["2016"]\n expected = df\n tm.assert_frame_equal(result, expected)\n\n # partial string match on date\n result = df.loc["2016-01-01"]\n expected = df.iloc[0:6]\n tm.assert_frame_equal(result, expected)\n\n # partial string match on date and hour, from middle\n result = df.loc["2016-01-02 12"]\n # hourly resolution, same as index.levels[0], so we are _not_ slicing on\n # that level, so that level gets dropped\n expected = df.iloc[9:12].droplevel(0)\n tm.assert_frame_equal(result, expected)\n\n # partial string match on secondary index\n result = df_swap.loc[SLC[:, "2016-01-02"], :]\n expected = df_swap.iloc[[2, 3, 7, 8, 12, 13]]\n tm.assert_frame_equal(result, expected)\n\n # tuple selector with partial string match on date\n # "2016-01-01" has daily resolution, so _is_ a slice on the first level.\n result = df.loc[("2016-01-01", "a"), :]\n expected = df.iloc[[0, 3]]\n expected = df.iloc[[0, 3]].droplevel(1)\n tm.assert_frame_equal(result, expected)\n\n # Slicing date on first level should break (of course) bc the DTI is the\n # second level on df_swap\n with pytest.raises(KeyError, match="'2016-01-01'"):\n df_swap.loc["2016-01-01"]\n\n\ndef test_partial_string_timestamp_multiindex_str_key_raises(df):\n # Even though this syntax works on a single index, this is somewhat\n # ambiguous and we don't want to extend this behavior forward to work\n # in multi-indexes. This would amount to selecting a scalar from a\n # column.\n with pytest.raises(KeyError, match="'2016-01-01'"):\n df["2016-01-01"]\n\n\ndef test_partial_string_timestamp_multiindex_daily_resolution(df):\n # GH12685 (partial string with daily resolution or below)\n result = df.loc[IndexSlice["2013-03":"2013-03", :], :]\n expected = df.iloc[118:180]\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_partial_indexing.py
test_partial_indexing.py
Python
4,765
0.95
0.047297
0.295082
python-kit
864
2025-04-30T11:53:30.508015
MIT
true
56543733827b4a2a81c992ad0665d274
import pytest\n\nfrom pandas import MultiIndex\n\n\ndef test_pickle_compat_construction():\n # this is testing for pickle compat\n # need an object to create with\n with pytest.raises(TypeError, match="Must pass both levels and codes"):\n MultiIndex()\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_pickle.py
test_pickle.py
Python
259
0.95
0.2
0.285714
node-utils
929
2023-11-26T12:26:32.163665
BSD-3-Clause
true
fa1ef317367ab39e7ee7f94f9696bd2e
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Index,\n MultiIndex,\n)\nimport pandas._testing as tm\n\n\ndef test_reindex(idx):\n result, indexer = idx.reindex(list(idx[:4]))\n assert isinstance(result, MultiIndex)\n assert result.names == ["first", "second"]\n assert [level.name for level in result.levels] == ["first", "second"]\n\n result, indexer = idx.reindex(list(idx))\n assert isinstance(result, MultiIndex)\n assert indexer is None\n assert result.names == ["first", "second"]\n assert [level.name for level in result.levels] == ["first", "second"]\n\n\ndef test_reindex_level(idx):\n index = Index(["one"])\n\n target, indexer = idx.reindex(index, level="second")\n target2, indexer2 = index.reindex(idx, level="second")\n\n exp_index = idx.join(index, level="second", how="right")\n exp_index2 = idx.join(index, level="second", how="left")\n\n assert target.equals(exp_index)\n exp_indexer = np.array([0, 2, 4])\n tm.assert_numpy_array_equal(indexer, exp_indexer, check_dtype=False)\n\n assert target2.equals(exp_index2)\n exp_indexer2 = np.array([0, -1, 0, -1, 0, -1])\n tm.assert_numpy_array_equal(indexer2, exp_indexer2, check_dtype=False)\n\n with pytest.raises(TypeError, match="Fill method not supported"):\n idx.reindex(idx, method="pad", level="second")\n\n\ndef test_reindex_preserves_names_when_target_is_list_or_ndarray(idx):\n # GH6552\n idx = idx.copy()\n target = idx.copy()\n idx.names = target.names = [None, None]\n\n other_dtype = MultiIndex.from_product([[1, 2], [3, 4]])\n\n # list & ndarray cases\n assert idx.reindex([])[0].names == [None, None]\n assert idx.reindex(np.array([]))[0].names == [None, None]\n assert idx.reindex(target.tolist())[0].names == [None, None]\n assert idx.reindex(target.values)[0].names == [None, None]\n assert idx.reindex(other_dtype.tolist())[0].names == [None, None]\n assert idx.reindex(other_dtype.values)[0].names == [None, None]\n\n idx.names = ["foo", "bar"]\n assert idx.reindex([])[0].names == ["foo", "bar"]\n assert idx.reindex(np.array([]))[0].names == ["foo", "bar"]\n assert idx.reindex(target.tolist())[0].names == ["foo", "bar"]\n assert idx.reindex(target.values)[0].names == ["foo", "bar"]\n assert idx.reindex(other_dtype.tolist())[0].names == ["foo", "bar"]\n assert idx.reindex(other_dtype.values)[0].names == ["foo", "bar"]\n\n\ndef test_reindex_lvl_preserves_names_when_target_is_list_or_array():\n # GH7774\n idx = MultiIndex.from_product([[0, 1], ["a", "b"]], names=["foo", "bar"])\n assert idx.reindex([], level=0)[0].names == ["foo", "bar"]\n assert idx.reindex([], level=1)[0].names == ["foo", "bar"]\n\n\ndef test_reindex_lvl_preserves_type_if_target_is_empty_list_or_array(\n using_infer_string,\n):\n # GH7774\n idx = MultiIndex.from_product([[0, 1], ["a", "b"]])\n assert idx.reindex([], level=0)[0].levels[0].dtype.type == np.int64\n exp = np.object_ if not using_infer_string else str\n assert idx.reindex([], level=1)[0].levels[1].dtype.type == exp\n\n # case with EA levels\n cat = pd.Categorical(["foo", "bar"])\n dti = pd.date_range("2016-01-01", periods=2, tz="US/Pacific")\n mi = MultiIndex.from_product([cat, dti])\n assert mi.reindex([], level=0)[0].levels[0].dtype == cat.dtype\n assert mi.reindex([], level=1)[0].levels[1].dtype == dti.dtype\n\n\ndef test_reindex_base(idx):\n expected = np.arange(idx.size, dtype=np.intp)\n\n actual = idx.get_indexer(idx)\n tm.assert_numpy_array_equal(expected, actual)\n\n with pytest.raises(ValueError, match="Invalid fill method"):\n idx.get_indexer(idx, method="invalid")\n\n\ndef test_reindex_non_unique():\n idx = MultiIndex.from_tuples([(0, 0), (1, 1), (1, 1), (2, 2)])\n a = pd.Series(np.arange(4), index=idx)\n new_idx = MultiIndex.from_tuples([(0, 0), (1, 1), (2, 2)])\n\n msg = "cannot handle a non-unique multi-index!"\n with pytest.raises(ValueError, match=msg):\n a.reindex(new_idx)\n\n\n@pytest.mark.parametrize("values", [[["a"], ["x"]], [[], []]])\ndef test_reindex_empty_with_level(values):\n # GH41170\n idx = MultiIndex.from_arrays(values)\n result, result_indexer = idx.reindex(np.array(["b"]), level=0)\n expected = MultiIndex(levels=[["b"], values[1]], codes=[[], []])\n expected_indexer = np.array([], dtype=result_indexer.dtype)\n tm.assert_index_equal(result, expected)\n tm.assert_numpy_array_equal(result_indexer, expected_indexer)\n\n\ndef test_reindex_not_all_tuples():\n keys = [("i", "i"), ("i", "j"), ("j", "i"), "j"]\n mi = MultiIndex.from_tuples(keys[:-1])\n idx = Index(keys)\n res, indexer = mi.reindex(idx)\n\n tm.assert_index_equal(res, idx)\n expected = np.array([0, 1, 2, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n\ndef test_reindex_limit_arg_with_multiindex():\n # GH21247\n\n idx = MultiIndex.from_tuples([(3, "A"), (4, "A"), (4, "B")])\n\n df = pd.Series([0.02, 0.01, 0.012], index=idx)\n\n new_idx = MultiIndex.from_tuples(\n [\n (3, "A"),\n (3, "B"),\n (4, "A"),\n (4, "B"),\n (4, "C"),\n (5, "B"),\n (5, "C"),\n (6, "B"),\n (6, "C"),\n ]\n )\n\n with pytest.raises(\n ValueError,\n match="limit argument only valid if doing pad, backfill or nearest reindexing",\n ):\n df.reindex(new_idx, fill_value=0, limit=1)\n\n\ndef test_reindex_with_none_in_nested_multiindex():\n # GH42883\n index = MultiIndex.from_tuples([(("a", None), 1), (("b", None), 2)])\n index2 = MultiIndex.from_tuples([(("b", None), 2), (("a", None), 1)])\n df1_dtype = pd.DataFrame([1, 2], index=index)\n df2_dtype = pd.DataFrame([2, 1], index=index2)\n\n result = df1_dtype.reindex_like(df2_dtype)\n expected = df2_dtype\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_reindex.py
test_reindex.py
Python
5,856
0.95
0.086207
0.060606
vue-tools
917
2023-10-04T20:43:59.273289
Apache-2.0
true
bf8fdca9b5b43b4e1603d8460af823df
from datetime import datetime\n\nimport numpy as np\nimport pytest\nimport pytz\n\nimport pandas as pd\nfrom pandas import (\n Index,\n MultiIndex,\n)\nimport pandas._testing as tm\n\n\ndef test_insert(idx):\n # key contained in all levels\n new_index = idx.insert(0, ("bar", "two"))\n assert new_index.equal_levels(idx)\n assert new_index[0] == ("bar", "two")\n\n # key not contained in all levels\n new_index = idx.insert(0, ("abc", "three"))\n\n exp0 = Index(list(idx.levels[0]) + ["abc"], name="first")\n tm.assert_index_equal(new_index.levels[0], exp0)\n assert new_index.names == ["first", "second"]\n\n exp1 = Index(list(idx.levels[1]) + ["three"], name="second")\n tm.assert_index_equal(new_index.levels[1], exp1)\n assert new_index[0] == ("abc", "three")\n\n # key wrong length\n msg = "Item must have length equal to number of levels"\n with pytest.raises(ValueError, match=msg):\n idx.insert(0, ("foo2",))\n\n left = pd.DataFrame([["a", "b", 0], ["b", "d", 1]], columns=["1st", "2nd", "3rd"])\n left.set_index(["1st", "2nd"], inplace=True)\n ts = left["3rd"].copy(deep=True)\n\n left.loc[("b", "x"), "3rd"] = 2\n left.loc[("b", "a"), "3rd"] = -1\n left.loc[("b", "b"), "3rd"] = 3\n left.loc[("a", "x"), "3rd"] = 4\n left.loc[("a", "w"), "3rd"] = 5\n left.loc[("a", "a"), "3rd"] = 6\n\n ts.loc[("b", "x")] = 2\n ts.loc["b", "a"] = -1\n ts.loc[("b", "b")] = 3\n ts.loc["a", "x"] = 4\n ts.loc[("a", "w")] = 5\n ts.loc["a", "a"] = 6\n\n right = pd.DataFrame(\n [\n ["a", "b", 0],\n ["b", "d", 1],\n ["b", "x", 2],\n ["b", "a", -1],\n ["b", "b", 3],\n ["a", "x", 4],\n ["a", "w", 5],\n ["a", "a", 6],\n ],\n columns=["1st", "2nd", "3rd"],\n )\n right.set_index(["1st", "2nd"], inplace=True)\n # FIXME data types changes to float because\n # of intermediate nan insertion;\n tm.assert_frame_equal(left, right, check_dtype=False)\n tm.assert_series_equal(ts, right["3rd"])\n\n\ndef test_insert2():\n # GH9250\n idx = (\n [("test1", i) for i in range(5)]\n + [("test2", i) for i in range(6)]\n + [("test", 17), ("test", 18)]\n )\n\n left = pd.Series(np.linspace(0, 10, 11), MultiIndex.from_tuples(idx[:-2]))\n\n left.loc[("test", 17)] = 11\n left.loc[("test", 18)] = 12\n\n right = pd.Series(np.linspace(0, 12, 13), MultiIndex.from_tuples(idx))\n\n tm.assert_series_equal(left, right)\n\n\ndef test_append(idx):\n result = idx[:3].append(idx[3:])\n assert result.equals(idx)\n\n foos = [idx[:1], idx[1:3], idx[3:]]\n result = foos[0].append(foos[1:])\n assert result.equals(idx)\n\n # empty\n result = idx.append([])\n assert result.equals(idx)\n\n\ndef test_append_index():\n idx1 = Index([1.1, 1.2, 1.3])\n idx2 = pd.date_range("2011-01-01", freq="D", periods=3, tz="Asia/Tokyo")\n idx3 = Index(["A", "B", "C"])\n\n midx_lv2 = MultiIndex.from_arrays([idx1, idx2])\n midx_lv3 = MultiIndex.from_arrays([idx1, idx2, idx3])\n\n result = idx1.append(midx_lv2)\n\n # see gh-7112\n tz = pytz.timezone("Asia/Tokyo")\n expected_tuples = [\n (1.1, tz.localize(datetime(2011, 1, 1))),\n (1.2, tz.localize(datetime(2011, 1, 2))),\n (1.3, tz.localize(datetime(2011, 1, 3))),\n ]\n expected = Index([1.1, 1.2, 1.3] + expected_tuples)\n tm.assert_index_equal(result, expected)\n\n result = midx_lv2.append(idx1)\n expected = Index(expected_tuples + [1.1, 1.2, 1.3])\n tm.assert_index_equal(result, expected)\n\n result = midx_lv2.append(midx_lv2)\n expected = MultiIndex.from_arrays([idx1.append(idx1), idx2.append(idx2)])\n tm.assert_index_equal(result, expected)\n\n result = midx_lv2.append(midx_lv3)\n tm.assert_index_equal(result, expected)\n\n result = midx_lv3.append(midx_lv2)\n expected = Index._simple_new(\n np.array(\n [\n (1.1, tz.localize(datetime(2011, 1, 1)), "A"),\n (1.2, tz.localize(datetime(2011, 1, 2)), "B"),\n (1.3, tz.localize(datetime(2011, 1, 3)), "C"),\n ]\n + expected_tuples,\n dtype=object,\n ),\n None,\n )\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("name, exp", [("b", "b"), ("c", None)])\ndef test_append_names_match(name, exp):\n # GH#48288\n midx = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])\n midx2 = MultiIndex.from_arrays([[3], [5]], names=["a", name])\n result = midx.append(midx2)\n expected = MultiIndex.from_arrays([[1, 2, 3], [3, 4, 5]], names=["a", exp])\n tm.assert_index_equal(result, expected)\n\n\ndef test_append_names_dont_match():\n # GH#48288\n midx = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])\n midx2 = MultiIndex.from_arrays([[3], [5]], names=["x", "y"])\n result = midx.append(midx2)\n expected = MultiIndex.from_arrays([[1, 2, 3], [3, 4, 5]], names=None)\n tm.assert_index_equal(result, expected)\n\n\ndef test_append_overlapping_interval_levels():\n # GH 54934\n ivl1 = pd.IntervalIndex.from_breaks([0.0, 1.0, 2.0])\n ivl2 = pd.IntervalIndex.from_breaks([0.5, 1.5, 2.5])\n mi1 = MultiIndex.from_product([ivl1, ivl1])\n mi2 = MultiIndex.from_product([ivl2, ivl2])\n result = mi1.append(mi2)\n expected = MultiIndex.from_tuples(\n [\n (pd.Interval(0.0, 1.0), pd.Interval(0.0, 1.0)),\n (pd.Interval(0.0, 1.0), pd.Interval(1.0, 2.0)),\n (pd.Interval(1.0, 2.0), pd.Interval(0.0, 1.0)),\n (pd.Interval(1.0, 2.0), pd.Interval(1.0, 2.0)),\n (pd.Interval(0.5, 1.5), pd.Interval(0.5, 1.5)),\n (pd.Interval(0.5, 1.5), pd.Interval(1.5, 2.5)),\n (pd.Interval(1.5, 2.5), pd.Interval(0.5, 1.5)),\n (pd.Interval(1.5, 2.5), pd.Interval(1.5, 2.5)),\n ]\n )\n tm.assert_index_equal(result, expected)\n\n\ndef test_repeat():\n reps = 2\n numbers = [1, 2, 3]\n names = np.array(["foo", "bar"])\n\n m = MultiIndex.from_product([numbers, names], names=names)\n expected = MultiIndex.from_product([numbers, names.repeat(reps)], names=names)\n tm.assert_index_equal(m.repeat(reps), expected)\n\n\ndef test_insert_base(idx):\n result = idx[1:4]\n\n # test 0th element\n assert idx[0:4].equals(result.insert(0, idx[0]))\n\n\ndef test_delete_base(idx):\n expected = idx[1:]\n result = idx.delete(0)\n assert result.equals(expected)\n assert result.name == expected.name\n\n expected = idx[:-1]\n result = idx.delete(-1)\n assert result.equals(expected)\n assert result.name == expected.name\n\n msg = "index 6 is out of bounds for axis 0 with size 6"\n with pytest.raises(IndexError, match=msg):\n idx.delete(len(idx))\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_reshape.py
test_reshape.py
Python
6,711
0.95
0.058036
0.067797
react-lib
915
2024-03-13T19:46:52.810815
GPL-3.0
true
a344482ae313e4c1b653c9d917052591
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n CategoricalIndex,\n DataFrame,\n Index,\n IntervalIndex,\n MultiIndex,\n Series,\n)\nimport pandas._testing as tm\nfrom pandas.api.types import (\n is_float_dtype,\n is_unsigned_integer_dtype,\n)\n\n\n@pytest.mark.parametrize("case", [0.5, "xxx"])\n@pytest.mark.parametrize(\n "method", ["intersection", "union", "difference", "symmetric_difference"]\n)\ndef test_set_ops_error_cases(idx, case, sort, method):\n # non-iterable input\n msg = "Input must be Index or array-like"\n with pytest.raises(TypeError, match=msg):\n getattr(idx, method)(case, sort=sort)\n\n\n@pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list])\ndef test_intersection_base(idx, sort, klass):\n first = idx[2::-1] # first 3 elements reversed\n second = idx[:5]\n\n if klass is not MultiIndex:\n second = klass(second.values)\n\n intersect = first.intersection(second, sort=sort)\n if sort is None:\n expected = first.sort_values()\n else:\n expected = first\n tm.assert_index_equal(intersect, expected)\n\n msg = "other must be a MultiIndex or a list of tuples"\n with pytest.raises(TypeError, match=msg):\n first.intersection([1, 2, 3], sort=sort)\n\n\n@pytest.mark.arm_slow\n@pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list])\ndef test_union_base(idx, sort, klass):\n first = idx[::-1]\n second = idx[:5]\n\n if klass is not MultiIndex:\n second = klass(second.values)\n\n union = first.union(second, sort=sort)\n if sort is None:\n expected = first.sort_values()\n else:\n expected = first\n tm.assert_index_equal(union, expected)\n\n msg = "other must be a MultiIndex or a list of tuples"\n with pytest.raises(TypeError, match=msg):\n first.union([1, 2, 3], sort=sort)\n\n\ndef test_difference_base(idx, sort):\n second = idx[4:]\n answer = idx[:4]\n result = idx.difference(second, sort=sort)\n\n if sort is None:\n answer = answer.sort_values()\n\n assert result.equals(answer)\n tm.assert_index_equal(result, answer)\n\n # GH 10149\n cases = [klass(second.values) for klass in [np.array, Series, list]]\n for case in cases:\n result = idx.difference(case, sort=sort)\n tm.assert_index_equal(result, answer)\n\n msg = "other must be a MultiIndex or a list of tuples"\n with pytest.raises(TypeError, match=msg):\n idx.difference([1, 2, 3], sort=sort)\n\n\ndef test_symmetric_difference(idx, sort):\n first = idx[1:]\n second = idx[:-1]\n answer = idx[[-1, 0]]\n result = first.symmetric_difference(second, sort=sort)\n\n if sort is None:\n answer = answer.sort_values()\n\n tm.assert_index_equal(result, answer)\n\n # GH 10149\n cases = [klass(second.values) for klass in [np.array, Series, list]]\n for case in cases:\n result = first.symmetric_difference(case, sort=sort)\n tm.assert_index_equal(result, answer)\n\n msg = "other must be a MultiIndex or a list of tuples"\n with pytest.raises(TypeError, match=msg):\n first.symmetric_difference([1, 2, 3], sort=sort)\n\n\ndef test_multiindex_symmetric_difference():\n # GH 13490\n idx = MultiIndex.from_product([["a", "b"], ["A", "B"]], names=["a", "b"])\n result = idx.symmetric_difference(idx)\n assert result.names == idx.names\n\n idx2 = idx.copy().rename(["A", "B"])\n result = idx.symmetric_difference(idx2)\n assert result.names == [None, None]\n\n\ndef test_empty(idx):\n # GH 15270\n assert not idx.empty\n assert idx[:0].empty\n\n\ndef test_difference(idx, sort):\n first = idx\n result = first.difference(idx[-3:], sort=sort)\n vals = idx[:-3].values\n\n if sort is None:\n vals = sorted(vals)\n\n expected = MultiIndex.from_tuples(vals, sortorder=0, names=idx.names)\n\n assert isinstance(result, MultiIndex)\n assert result.equals(expected)\n assert result.names == idx.names\n tm.assert_index_equal(result, expected)\n\n # empty difference: reflexive\n result = idx.difference(idx, sort=sort)\n expected = idx[:0]\n assert result.equals(expected)\n assert result.names == idx.names\n\n # empty difference: superset\n result = idx[-3:].difference(idx, sort=sort)\n expected = idx[:0]\n assert result.equals(expected)\n assert result.names == idx.names\n\n # empty difference: degenerate\n result = idx[:0].difference(idx, sort=sort)\n expected = idx[:0]\n assert result.equals(expected)\n assert result.names == idx.names\n\n # names not the same\n chunklet = idx[-3:]\n chunklet.names = ["foo", "baz"]\n result = first.difference(chunklet, sort=sort)\n assert result.names == (None, None)\n\n # empty, but non-equal\n result = idx.difference(idx.sortlevel(1)[0], sort=sort)\n assert len(result) == 0\n\n # raise Exception called with non-MultiIndex\n result = first.difference(first.values, sort=sort)\n assert result.equals(first[:0])\n\n # name from empty array\n result = first.difference([], sort=sort)\n assert first.equals(result)\n assert first.names == result.names\n\n # name from non-empty array\n result = first.difference([("foo", "one")], sort=sort)\n expected = MultiIndex.from_tuples(\n [("bar", "one"), ("baz", "two"), ("foo", "two"), ("qux", "one"), ("qux", "two")]\n )\n expected.names = first.names\n assert first.names == result.names\n\n msg = "other must be a MultiIndex or a list of tuples"\n with pytest.raises(TypeError, match=msg):\n first.difference([1, 2, 3, 4, 5], sort=sort)\n\n\ndef test_difference_sort_special():\n # GH-24959\n idx = MultiIndex.from_product([[1, 0], ["a", "b"]])\n # sort=None, the default\n result = idx.difference([])\n tm.assert_index_equal(result, idx)\n\n\ndef test_difference_sort_special_true():\n idx = MultiIndex.from_product([[1, 0], ["a", "b"]])\n result = idx.difference([], sort=True)\n expected = MultiIndex.from_product([[0, 1], ["a", "b"]])\n tm.assert_index_equal(result, expected)\n\n\ndef test_difference_sort_incomparable():\n # GH-24959\n idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]])\n\n other = MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]])\n # sort=None, the default\n msg = "sort order is undefined for incomparable objects"\n with tm.assert_produces_warning(RuntimeWarning, match=msg):\n result = idx.difference(other)\n tm.assert_index_equal(result, idx)\n\n # sort=False\n result = idx.difference(other, sort=False)\n tm.assert_index_equal(result, idx)\n\n\ndef test_difference_sort_incomparable_true():\n idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]])\n other = MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]])\n\n # TODO: this is raising in constructing a Categorical when calling\n # algos.safe_sort. Should we catch and re-raise with a better message?\n msg = "'values' is not ordered, please explicitly specify the categories order "\n with pytest.raises(TypeError, match=msg):\n idx.difference(other, sort=True)\n\n\ndef test_union(idx, sort):\n piece1 = idx[:5][::-1]\n piece2 = idx[3:]\n\n the_union = piece1.union(piece2, sort=sort)\n\n if sort in (None, False):\n tm.assert_index_equal(the_union.sort_values(), idx.sort_values())\n else:\n tm.assert_index_equal(the_union, idx)\n\n # corner case, pass self or empty thing:\n the_union = idx.union(idx, sort=sort)\n tm.assert_index_equal(the_union, idx)\n\n the_union = idx.union(idx[:0], sort=sort)\n tm.assert_index_equal(the_union, idx)\n\n tuples = idx.values\n result = idx[:4].union(tuples[4:], sort=sort)\n if sort is None:\n tm.assert_index_equal(result.sort_values(), idx.sort_values())\n else:\n assert result.equals(idx)\n\n\ndef test_union_with_regular_index(idx, using_infer_string):\n other = Index(["A", "B", "C"])\n\n result = other.union(idx)\n assert ("foo", "one") in result\n assert "B" in result\n\n if using_infer_string:\n with pytest.raises(NotImplementedError, match="Can only union"):\n idx.union(other)\n else:\n msg = "The values in the array are unorderable"\n with tm.assert_produces_warning(RuntimeWarning, match=msg):\n result2 = idx.union(other)\n # This is more consistent now, if sorting fails then we don't sort at all\n # in the MultiIndex case.\n assert not result.equals(result2)\n\n\ndef test_intersection(idx, sort):\n piece1 = idx[:5][::-1]\n piece2 = idx[3:]\n\n the_int = piece1.intersection(piece2, sort=sort)\n\n if sort in (None, True):\n tm.assert_index_equal(the_int, idx[3:5])\n else:\n tm.assert_index_equal(the_int.sort_values(), idx[3:5])\n\n # corner case, pass self\n the_int = idx.intersection(idx, sort=sort)\n tm.assert_index_equal(the_int, idx)\n\n # empty intersection: disjoint\n empty = idx[:2].intersection(idx[2:], sort=sort)\n expected = idx[:0]\n assert empty.equals(expected)\n\n tuples = idx.values\n result = idx.intersection(tuples)\n assert result.equals(idx)\n\n\n@pytest.mark.parametrize(\n "method", ["intersection", "union", "difference", "symmetric_difference"]\n)\ndef test_setop_with_categorical(idx, sort, method):\n other = idx.to_flat_index().astype("category")\n res_names = [None] * idx.nlevels\n\n result = getattr(idx, method)(other, sort=sort)\n expected = getattr(idx, method)(idx, sort=sort).rename(res_names)\n tm.assert_index_equal(result, expected)\n\n result = getattr(idx, method)(other[:5], sort=sort)\n expected = getattr(idx, method)(idx[:5], sort=sort).rename(res_names)\n tm.assert_index_equal(result, expected)\n\n\ndef test_intersection_non_object(idx, sort):\n other = Index(range(3), name="foo")\n\n result = idx.intersection(other, sort=sort)\n expected = MultiIndex(levels=idx.levels, codes=[[]] * idx.nlevels, names=None)\n tm.assert_index_equal(result, expected, exact=True)\n\n # if we pass a length-0 ndarray (i.e. no name, we retain our idx.name)\n result = idx.intersection(np.asarray(other)[:0], sort=sort)\n expected = MultiIndex(levels=idx.levels, codes=[[]] * idx.nlevels, names=idx.names)\n tm.assert_index_equal(result, expected, exact=True)\n\n msg = "other must be a MultiIndex or a list of tuples"\n with pytest.raises(TypeError, match=msg):\n # With non-zero length non-index, we try and fail to convert to tuples\n idx.intersection(np.asarray(other), sort=sort)\n\n\ndef test_intersect_equal_sort():\n # GH-24959\n idx = MultiIndex.from_product([[1, 0], ["a", "b"]])\n tm.assert_index_equal(idx.intersection(idx, sort=False), idx)\n tm.assert_index_equal(idx.intersection(idx, sort=None), idx)\n\n\ndef test_intersect_equal_sort_true():\n idx = MultiIndex.from_product([[1, 0], ["a", "b"]])\n expected = MultiIndex.from_product([[0, 1], ["a", "b"]])\n result = idx.intersection(idx, sort=True)\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("slice_", [slice(None), slice(0)])\ndef test_union_sort_other_empty(slice_):\n # https://github.com/pandas-dev/pandas/issues/24959\n idx = MultiIndex.from_product([[1, 0], ["a", "b"]])\n\n # default, sort=None\n other = idx[slice_]\n tm.assert_index_equal(idx.union(other), idx)\n tm.assert_index_equal(other.union(idx), idx)\n\n # sort=False\n tm.assert_index_equal(idx.union(other, sort=False), idx)\n\n\ndef test_union_sort_other_empty_sort():\n idx = MultiIndex.from_product([[1, 0], ["a", "b"]])\n other = idx[:0]\n result = idx.union(other, sort=True)\n expected = MultiIndex.from_product([[0, 1], ["a", "b"]])\n tm.assert_index_equal(result, expected)\n\n\ndef test_union_sort_other_incomparable():\n # https://github.com/pandas-dev/pandas/issues/24959\n idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]])\n\n # default, sort=None\n with tm.assert_produces_warning(RuntimeWarning):\n result = idx.union(idx[:1])\n tm.assert_index_equal(result, idx)\n\n # sort=False\n result = idx.union(idx[:1], sort=False)\n tm.assert_index_equal(result, idx)\n\n\ndef test_union_sort_other_incomparable_sort():\n idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]])\n msg = "'<' not supported between instances of 'Timestamp' and 'int'"\n with pytest.raises(TypeError, match=msg):\n idx.union(idx[:1], sort=True)\n\n\ndef test_union_non_object_dtype_raises():\n # GH#32646 raise NotImplementedError instead of less-informative error\n mi = MultiIndex.from_product([["a", "b"], [1, 2]])\n\n idx = mi.levels[1]\n\n msg = "Can only union MultiIndex with MultiIndex or Index of tuples"\n with pytest.raises(NotImplementedError, match=msg):\n mi.union(idx)\n\n\ndef test_union_empty_self_different_names():\n # GH#38423\n mi = MultiIndex.from_arrays([[]])\n mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])\n result = mi.union(mi2)\n expected = MultiIndex.from_arrays([[1, 2], [3, 4]])\n tm.assert_index_equal(result, expected)\n\n\ndef test_union_multiindex_empty_rangeindex():\n # GH#41234\n mi = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])\n ri = pd.RangeIndex(0)\n\n result_left = mi.union(ri)\n tm.assert_index_equal(mi, result_left, check_names=False)\n\n result_right = ri.union(mi)\n tm.assert_index_equal(mi, result_right, check_names=False)\n\n\n@pytest.mark.parametrize(\n "method", ["union", "intersection", "difference", "symmetric_difference"]\n)\ndef test_setops_sort_validation(method):\n idx1 = MultiIndex.from_product([["a", "b"], [1, 2]])\n idx2 = MultiIndex.from_product([["b", "c"], [1, 2]])\n\n with pytest.raises(ValueError, match="The 'sort' keyword only takes"):\n getattr(idx1, method)(idx2, sort=2)\n\n # sort=True is supported as of GH#?\n getattr(idx1, method)(idx2, sort=True)\n\n\n@pytest.mark.parametrize("val", [pd.NA, 100])\ndef test_difference_keep_ea_dtypes(any_numeric_ea_dtype, val):\n # GH#48606\n midx = MultiIndex.from_arrays(\n [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None]\n )\n midx2 = MultiIndex.from_arrays(\n [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]]\n )\n result = midx.difference(midx2)\n expected = MultiIndex.from_arrays([Series([1], dtype=any_numeric_ea_dtype), [2]])\n tm.assert_index_equal(result, expected)\n\n result = midx.difference(midx.sort_values(ascending=False))\n expected = MultiIndex.from_arrays(\n [Series([], dtype=any_numeric_ea_dtype), Series([], dtype=np.int64)],\n names=["a", None],\n )\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("val", [pd.NA, 5])\ndef test_symmetric_difference_keeping_ea_dtype(any_numeric_ea_dtype, val):\n # GH#48607\n midx = MultiIndex.from_arrays(\n [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None]\n )\n midx2 = MultiIndex.from_arrays(\n [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]]\n )\n result = midx.symmetric_difference(midx2)\n expected = MultiIndex.from_arrays(\n [Series([1, 1, val], dtype=any_numeric_ea_dtype), [1, 2, 3]]\n )\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n ("tuples", "exp_tuples"),\n [\n ([("val1", "test1")], [("val1", "test1")]),\n ([("val1", "test1"), ("val1", "test1")], [("val1", "test1")]),\n (\n [("val2", "test2"), ("val1", "test1")],\n [("val2", "test2"), ("val1", "test1")],\n ),\n ],\n)\ndef test_intersect_with_duplicates(tuples, exp_tuples):\n # GH#36915\n left = MultiIndex.from_tuples(tuples, names=["first", "second"])\n right = MultiIndex.from_tuples(\n [("val1", "test1"), ("val1", "test1"), ("val2", "test2")],\n names=["first", "second"],\n )\n result = left.intersection(right)\n expected = MultiIndex.from_tuples(exp_tuples, names=["first", "second"])\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "data, names, expected",\n [\n ((1,), None, [None, None]),\n ((1,), ["a"], [None, None]),\n ((1,), ["b"], [None, None]),\n ((1, 2), ["c", "d"], [None, None]),\n ((1, 2), ["b", "a"], [None, None]),\n ((1, 2, 3), ["a", "b", "c"], [None, None]),\n ((1, 2), ["a", "c"], ["a", None]),\n ((1, 2), ["c", "b"], [None, "b"]),\n ((1, 2), ["a", "b"], ["a", "b"]),\n ((1, 2), [None, "b"], [None, "b"]),\n ],\n)\ndef test_maybe_match_names(data, names, expected):\n # GH#38323\n mi = MultiIndex.from_tuples([], names=["a", "b"])\n mi2 = MultiIndex.from_tuples([data], names=names)\n result = mi._maybe_match_names(mi2)\n assert result == expected\n\n\ndef test_intersection_equal_different_names():\n # GH#30302\n mi1 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["c", "b"])\n mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])\n\n result = mi1.intersection(mi2)\n expected = MultiIndex.from_arrays([[1, 2], [3, 4]], names=[None, "b"])\n tm.assert_index_equal(result, expected)\n\n\ndef test_intersection_different_names():\n # GH#38323\n mi = MultiIndex.from_arrays([[1], [3]], names=["c", "b"])\n mi2 = MultiIndex.from_arrays([[1], [3]])\n result = mi.intersection(mi2)\n tm.assert_index_equal(result, mi2)\n\n\ndef test_intersection_with_missing_values_on_both_sides(nulls_fixture):\n # GH#38623\n mi1 = MultiIndex.from_arrays([[3, nulls_fixture, 4, nulls_fixture], [1, 2, 4, 2]])\n mi2 = MultiIndex.from_arrays([[3, nulls_fixture, 3], [1, 2, 4]])\n result = mi1.intersection(mi2)\n expected = MultiIndex.from_arrays([[3, nulls_fixture], [1, 2]])\n tm.assert_index_equal(result, expected)\n\n\ndef test_union_with_missing_values_on_both_sides(nulls_fixture):\n # GH#38623\n mi1 = MultiIndex.from_arrays([[1, nulls_fixture]])\n mi2 = MultiIndex.from_arrays([[1, nulls_fixture, 3]])\n result = mi1.union(mi2)\n expected = MultiIndex.from_arrays([[1, 3, nulls_fixture]])\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("dtype", ["float64", "Float64"])\n@pytest.mark.parametrize("sort", [None, False])\ndef test_union_nan_got_duplicated(dtype, sort):\n # GH#38977, GH#49010\n mi1 = MultiIndex.from_arrays([pd.array([1.0, np.nan], dtype=dtype), [2, 3]])\n mi2 = MultiIndex.from_arrays([pd.array([1.0, np.nan, 3.0], dtype=dtype), [2, 3, 4]])\n result = mi1.union(mi2, sort=sort)\n if sort is None:\n expected = MultiIndex.from_arrays(\n [pd.array([1.0, 3.0, np.nan], dtype=dtype), [2, 4, 3]]\n )\n else:\n expected = mi2\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("val", [4, 1])\ndef test_union_keep_ea_dtype(any_numeric_ea_dtype, val):\n # GH#48505\n\n arr1 = Series([val, 2], dtype=any_numeric_ea_dtype)\n arr2 = Series([2, 1], dtype=any_numeric_ea_dtype)\n midx = MultiIndex.from_arrays([arr1, [1, 2]], names=["a", None])\n midx2 = MultiIndex.from_arrays([arr2, [2, 1]])\n result = midx.union(midx2)\n if val == 4:\n expected = MultiIndex.from_arrays(\n [Series([1, 2, 4], dtype=any_numeric_ea_dtype), [1, 2, 1]]\n )\n else:\n expected = MultiIndex.from_arrays(\n [Series([1, 2], dtype=any_numeric_ea_dtype), [1, 2]]\n )\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("dupe_val", [3, pd.NA])\ndef test_union_with_duplicates_keep_ea_dtype(dupe_val, any_numeric_ea_dtype):\n # GH48900\n mi1 = MultiIndex.from_arrays(\n [\n Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype),\n Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype),\n ]\n )\n mi2 = MultiIndex.from_arrays(\n [\n Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),\n Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),\n ]\n )\n result = mi1.union(mi2)\n expected = MultiIndex.from_arrays(\n [\n Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),\n Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),\n ]\n )\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\ndef test_union_duplicates(index, request):\n # GH#38977\n if index.empty or isinstance(index, (IntervalIndex, CategoricalIndex)):\n pytest.skip(f"No duplicates in an empty {type(index).__name__}")\n\n values = index.unique().values.tolist()\n mi1 = MultiIndex.from_arrays([values, [1] * len(values)])\n mi2 = MultiIndex.from_arrays([[values[0]] + values, [1] * (len(values) + 1)])\n result = mi2.union(mi1)\n expected = mi2.sort_values()\n tm.assert_index_equal(result, expected)\n\n if (\n is_unsigned_integer_dtype(mi2.levels[0])\n and (mi2.get_level_values(0) < 2**63).all()\n ):\n # GH#47294 - union uses lib.fast_zip, converting data to Python integers\n # and loses type information. Result is then unsigned only when values are\n # sufficiently large to require unsigned dtype. This happens only if other\n # has dups or one of both have missing values\n expected = expected.set_levels(\n [expected.levels[0].astype(np.int64), expected.levels[1]]\n )\n elif is_float_dtype(mi2.levels[0]):\n # mi2 has duplicates witch is a different path than above, Fix that path\n # to use correct float dtype?\n expected = expected.set_levels(\n [expected.levels[0].astype(float), expected.levels[1]]\n )\n\n result = mi1.union(mi2)\n tm.assert_index_equal(result, expected)\n\n\ndef test_union_keep_dtype_precision(any_real_numeric_dtype):\n # GH#48498\n arr1 = Series([4, 1, 1], dtype=any_real_numeric_dtype)\n arr2 = Series([1, 4], dtype=any_real_numeric_dtype)\n midx = MultiIndex.from_arrays([arr1, [2, 1, 1]], names=["a", None])\n midx2 = MultiIndex.from_arrays([arr2, [1, 2]], names=["a", None])\n\n result = midx.union(midx2)\n expected = MultiIndex.from_arrays(\n ([Series([1, 1, 4], dtype=any_real_numeric_dtype), [1, 1, 2]]),\n names=["a", None],\n )\n tm.assert_index_equal(result, expected)\n\n\ndef test_union_keep_ea_dtype_with_na(any_numeric_ea_dtype):\n # GH#48498\n arr1 = Series([4, pd.NA], dtype=any_numeric_ea_dtype)\n arr2 = Series([1, pd.NA], dtype=any_numeric_ea_dtype)\n midx = MultiIndex.from_arrays([arr1, [2, 1]], names=["a", None])\n midx2 = MultiIndex.from_arrays([arr2, [1, 2]])\n result = midx.union(midx2)\n expected = MultiIndex.from_arrays(\n [Series([1, 4, pd.NA, pd.NA], dtype=any_numeric_ea_dtype), [1, 2, 1, 2]]\n )\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "levels1, levels2, codes1, codes2, names",\n [\n (\n [["a", "b", "c"], [0, ""]],\n [["c", "d", "b"], [""]],\n [[0, 1, 2], [1, 1, 1]],\n [[0, 1, 2], [0, 0, 0]],\n ["name1", "name2"],\n ),\n ],\n)\ndef test_intersection_lexsort_depth(levels1, levels2, codes1, codes2, names):\n # GH#25169\n mi1 = MultiIndex(levels=levels1, codes=codes1, names=names)\n mi2 = MultiIndex(levels=levels2, codes=codes2, names=names)\n mi_int = mi1.intersection(mi2)\n assert mi_int._lexsort_depth == 2\n\n\n@pytest.mark.parametrize(\n "a",\n [pd.Categorical(["a", "b"], categories=["a", "b"]), ["a", "b"]],\n)\n@pytest.mark.parametrize(\n "b",\n [\n pd.Categorical(["a", "b"], categories=["b", "a"], ordered=True),\n pd.Categorical(["a", "b"], categories=["b", "a"]),\n ],\n)\ndef test_intersection_with_non_lex_sorted_categories(a, b):\n # GH#49974\n other = ["1", "2"]\n\n df1 = DataFrame({"x": a, "y": other})\n df2 = DataFrame({"x": b, "y": other})\n\n expected = MultiIndex.from_arrays([a, other], names=["x", "y"])\n\n res1 = MultiIndex.from_frame(df1).intersection(\n MultiIndex.from_frame(df2.sort_values(["x", "y"]))\n )\n res2 = MultiIndex.from_frame(df1).intersection(MultiIndex.from_frame(df2))\n res3 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection(\n MultiIndex.from_frame(df2)\n )\n res4 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection(\n MultiIndex.from_frame(df2.sort_values(["x", "y"]))\n )\n\n tm.assert_index_equal(res1, expected)\n tm.assert_index_equal(res2, expected)\n tm.assert_index_equal(res3, expected)\n tm.assert_index_equal(res4, expected)\n\n\n@pytest.mark.parametrize("val", [pd.NA, 100])\ndef test_intersection_keep_ea_dtypes(val, any_numeric_ea_dtype):\n # GH#48604\n midx = MultiIndex.from_arrays(\n [Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None]\n )\n midx2 = MultiIndex.from_arrays(\n [Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]]\n )\n result = midx.intersection(midx2)\n expected = MultiIndex.from_arrays([Series([2], dtype=any_numeric_ea_dtype), [1]])\n tm.assert_index_equal(result, expected)\n\n\ndef test_union_with_na_when_constructing_dataframe():\n # GH43222\n series1 = Series(\n (1,),\n index=MultiIndex.from_arrays(\n [Series([None], dtype="str"), Series([None], dtype="str")]\n ),\n )\n series2 = Series((10, 20), index=MultiIndex.from_tuples(((None, None), ("a", "b"))))\n result = DataFrame([series1, series2])\n expected = DataFrame({(np.nan, np.nan): [1.0, 10.0], ("a", "b"): [np.nan, 20.0]})\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\indexes\multi\test_setops.py
test_setops.py
Python
25,460
0.95
0.090674
0.101142
python-kit
583
2024-01-31T15:08:05.358764
Apache-2.0
true
2c2a34119e3d20addbee07af8c2350f3