Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- mantis_evalkit/bin/python3.10 +3 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_asof.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_assign.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_at_time.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_between_time.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_combine.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_combine_first.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_compare.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_convert_dtypes.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_cov_corr.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_describe.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_dropna.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_dtypes.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_duplicated.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_filter.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_first_valid_index.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_infer_objects.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_interpolate.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_iterrows.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_matmul.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_pct_change.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_quantile.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_reindex_like.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_rename.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_reorder_levels.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_replace.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_round.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_set_axis.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_shift.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_sort_index.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_sort_values.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_to_numpy.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_to_period.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_to_records.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_truncate.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_tz_localize.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_at_time.py +132 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_interpolate.py +548 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_quantile.py +972 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_reset_index.py +782 -0
- mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_set_axis.py +143 -0
- moondream/lib/python3.10/site-packages/altair/vegalite/v5/__pycache__/api.cpython-310.pyc +3 -0
- moondream/lib/python3.10/site-packages/pandas/io/clipboard/__init__.py +747 -0
- moondream/lib/python3.10/site-packages/pandas/io/clipboard/__pycache__/__init__.cpython-310.pyc +0 -0
- moondream/lib/python3.10/site-packages/pandas/io/parsers/__init__.py +9 -0
- moondream/lib/python3.10/site-packages/pandas/io/parsers/__pycache__/__init__.cpython-310.pyc +0 -0
- moondream/lib/python3.10/site-packages/pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-310.pyc +0 -0
- moondream/lib/python3.10/site-packages/pandas/io/parsers/__pycache__/base_parser.cpython-310.pyc +0 -0
- moondream/lib/python3.10/site-packages/pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -550,3 +550,5 @@ mantis_evalkit/lib/python3.10/site-packages/nvidia/cublas/lib/libnvblas.so.12 fi
|
|
| 550 |
moondream/lib/python3.10/site-packages/fontTools/subset/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 551 |
moondream/lib/python3.10/site-packages/pygments/lexers/__pycache__/lisp.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 552 |
parrot/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 550 |
moondream/lib/python3.10/site-packages/fontTools/subset/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 551 |
moondream/lib/python3.10/site-packages/pygments/lexers/__pycache__/lisp.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 552 |
parrot/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 553 |
+
moondream/lib/python3.10/site-packages/altair/vegalite/v5/__pycache__/api.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 554 |
+
mantis_evalkit/bin/python3.10 filter=lfs diff=lfs merge=lfs -text
|
mantis_evalkit/bin/python3.10
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:942d139b2c77dad76f23ac64382f5e2714b5b2f0b1be3e76a8f79e1214cf0e6d
|
| 3 |
+
size 17225608
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_asof.cpython-310.pyc
ADDED
|
Binary file (5.34 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_assign.cpython-310.pyc
ADDED
|
Binary file (3.8 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_at_time.cpython-310.pyc
ADDED
|
Binary file (4.98 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_between_time.cpython-310.pyc
ADDED
|
Binary file (7.14 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_combine.cpython-310.pyc
ADDED
|
Binary file (1.68 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_combine_first.cpython-310.pyc
ADDED
|
Binary file (15.6 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_compare.cpython-310.pyc
ADDED
|
Binary file (6.77 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_convert_dtypes.cpython-310.pyc
ADDED
|
Binary file (6.56 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_cov_corr.cpython-310.pyc
ADDED
|
Binary file (15.4 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_describe.cpython-310.pyc
ADDED
|
Binary file (11.4 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_dropna.cpython-310.pyc
ADDED
|
Binary file (9.02 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_dtypes.cpython-310.pyc
ADDED
|
Binary file (5.01 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_duplicated.cpython-310.pyc
ADDED
|
Binary file (3.03 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_filter.cpython-310.pyc
ADDED
|
Binary file (4.81 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_first_valid_index.cpython-310.pyc
ADDED
|
Binary file (2.98 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_infer_objects.cpython-310.pyc
ADDED
|
Binary file (1.26 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_interpolate.cpython-310.pyc
ADDED
|
Binary file (16.6 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_iterrows.cpython-310.pyc
ADDED
|
Binary file (554 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_matmul.cpython-310.pyc
ADDED
|
Binary file (2.3 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_pct_change.cpython-310.pyc
ADDED
|
Binary file (5.22 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_quantile.cpython-310.pyc
ADDED
|
Binary file (23.6 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_reindex_like.cpython-310.pyc
ADDED
|
Binary file (1.83 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_rename.cpython-310.pyc
ADDED
|
Binary file (11.7 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_reorder_levels.cpython-310.pyc
ADDED
|
Binary file (2.32 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_replace.cpython-310.pyc
ADDED
|
Binary file (44.9 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_round.cpython-310.pyc
ADDED
|
Binary file (6.13 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_set_axis.cpython-310.pyc
ADDED
|
Binary file (4.79 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_shift.cpython-310.pyc
ADDED
|
Binary file (23 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_sort_index.cpython-310.pyc
ADDED
|
Binary file (25.9 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_sort_values.cpython-310.pyc
ADDED
|
Binary file (24.9 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_to_numpy.cpython-310.pyc
ADDED
|
Binary file (2.01 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_to_period.cpython-310.pyc
ADDED
|
Binary file (3.04 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_to_records.cpython-310.pyc
ADDED
|
Binary file (11.8 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_truncate.cpython-310.pyc
ADDED
|
Binary file (4.97 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/__pycache__/test_tz_localize.cpython-310.pyc
ADDED
|
Binary file (2.31 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_at_time.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import time
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
import pytz
|
| 6 |
+
|
| 7 |
+
from pandas._libs.tslibs import timezones
|
| 8 |
+
|
| 9 |
+
from pandas import (
|
| 10 |
+
DataFrame,
|
| 11 |
+
date_range,
|
| 12 |
+
)
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestAtTime:
|
| 17 |
+
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
|
| 18 |
+
def test_localized_at_time(self, tzstr, frame_or_series):
|
| 19 |
+
tz = timezones.maybe_get_tz(tzstr)
|
| 20 |
+
|
| 21 |
+
rng = date_range("4/16/2012", "5/1/2012", freq="h")
|
| 22 |
+
ts = frame_or_series(
|
| 23 |
+
np.random.default_rng(2).standard_normal(len(rng)), index=rng
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
ts_local = ts.tz_localize(tzstr)
|
| 27 |
+
|
| 28 |
+
result = ts_local.at_time(time(10, 0))
|
| 29 |
+
expected = ts.at_time(time(10, 0)).tz_localize(tzstr)
|
| 30 |
+
tm.assert_equal(result, expected)
|
| 31 |
+
assert timezones.tz_compare(result.index.tz, tz)
|
| 32 |
+
|
| 33 |
+
def test_at_time(self, frame_or_series):
|
| 34 |
+
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
|
| 35 |
+
ts = DataFrame(
|
| 36 |
+
np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng
|
| 37 |
+
)
|
| 38 |
+
ts = tm.get_obj(ts, frame_or_series)
|
| 39 |
+
rs = ts.at_time(rng[1])
|
| 40 |
+
assert (rs.index.hour == rng[1].hour).all()
|
| 41 |
+
assert (rs.index.minute == rng[1].minute).all()
|
| 42 |
+
assert (rs.index.second == rng[1].second).all()
|
| 43 |
+
|
| 44 |
+
result = ts.at_time("9:30")
|
| 45 |
+
expected = ts.at_time(time(9, 30))
|
| 46 |
+
tm.assert_equal(result, expected)
|
| 47 |
+
|
| 48 |
+
def test_at_time_midnight(self, frame_or_series):
|
| 49 |
+
# midnight, everything
|
| 50 |
+
rng = date_range("1/1/2000", "1/31/2000")
|
| 51 |
+
ts = DataFrame(
|
| 52 |
+
np.random.default_rng(2).standard_normal((len(rng), 3)), index=rng
|
| 53 |
+
)
|
| 54 |
+
ts = tm.get_obj(ts, frame_or_series)
|
| 55 |
+
|
| 56 |
+
result = ts.at_time(time(0, 0))
|
| 57 |
+
tm.assert_equal(result, ts)
|
| 58 |
+
|
| 59 |
+
def test_at_time_nonexistent(self, frame_or_series):
|
| 60 |
+
# time doesn't exist
|
| 61 |
+
rng = date_range("1/1/2012", freq="23Min", periods=384)
|
| 62 |
+
ts = DataFrame(np.random.default_rng(2).standard_normal(len(rng)), rng)
|
| 63 |
+
ts = tm.get_obj(ts, frame_or_series)
|
| 64 |
+
rs = ts.at_time("16:00")
|
| 65 |
+
assert len(rs) == 0
|
| 66 |
+
|
| 67 |
+
@pytest.mark.parametrize(
|
| 68 |
+
"hour", ["1:00", "1:00AM", time(1), time(1, tzinfo=pytz.UTC)]
|
| 69 |
+
)
|
| 70 |
+
def test_at_time_errors(self, hour):
|
| 71 |
+
# GH#24043
|
| 72 |
+
dti = date_range("2018", periods=3, freq="h")
|
| 73 |
+
df = DataFrame(list(range(len(dti))), index=dti)
|
| 74 |
+
if getattr(hour, "tzinfo", None) is None:
|
| 75 |
+
result = df.at_time(hour)
|
| 76 |
+
expected = df.iloc[1:2]
|
| 77 |
+
tm.assert_frame_equal(result, expected)
|
| 78 |
+
else:
|
| 79 |
+
with pytest.raises(ValueError, match="Index must be timezone"):
|
| 80 |
+
df.at_time(hour)
|
| 81 |
+
|
| 82 |
+
def test_at_time_tz(self):
|
| 83 |
+
# GH#24043
|
| 84 |
+
dti = date_range("2018", periods=3, freq="h", tz="US/Pacific")
|
| 85 |
+
df = DataFrame(list(range(len(dti))), index=dti)
|
| 86 |
+
result = df.at_time(time(4, tzinfo=pytz.timezone("US/Eastern")))
|
| 87 |
+
expected = df.iloc[1:2]
|
| 88 |
+
tm.assert_frame_equal(result, expected)
|
| 89 |
+
|
| 90 |
+
def test_at_time_raises(self, frame_or_series):
|
| 91 |
+
# GH#20725
|
| 92 |
+
obj = DataFrame([[1, 2, 3], [4, 5, 6]])
|
| 93 |
+
obj = tm.get_obj(obj, frame_or_series)
|
| 94 |
+
msg = "Index must be DatetimeIndex"
|
| 95 |
+
with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex
|
| 96 |
+
obj.at_time("00:00")
|
| 97 |
+
|
| 98 |
+
@pytest.mark.parametrize("axis", ["index", "columns", 0, 1])
|
| 99 |
+
def test_at_time_axis(self, axis):
|
| 100 |
+
# issue 8839
|
| 101 |
+
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
|
| 102 |
+
ts = DataFrame(np.random.default_rng(2).standard_normal((len(rng), len(rng))))
|
| 103 |
+
ts.index, ts.columns = rng, rng
|
| 104 |
+
|
| 105 |
+
indices = rng[(rng.hour == 9) & (rng.minute == 30) & (rng.second == 0)]
|
| 106 |
+
|
| 107 |
+
if axis in ["index", 0]:
|
| 108 |
+
expected = ts.loc[indices, :]
|
| 109 |
+
elif axis in ["columns", 1]:
|
| 110 |
+
expected = ts.loc[:, indices]
|
| 111 |
+
|
| 112 |
+
result = ts.at_time("9:30", axis=axis)
|
| 113 |
+
|
| 114 |
+
# Without clearing freq, result has freq 1440T and expected 5T
|
| 115 |
+
result.index = result.index._with_freq(None)
|
| 116 |
+
expected.index = expected.index._with_freq(None)
|
| 117 |
+
tm.assert_frame_equal(result, expected)
|
| 118 |
+
|
| 119 |
+
def test_at_time_datetimeindex(self):
|
| 120 |
+
index = date_range("2012-01-01", "2012-01-05", freq="30min")
|
| 121 |
+
df = DataFrame(
|
| 122 |
+
np.random.default_rng(2).standard_normal((len(index), 5)), index=index
|
| 123 |
+
)
|
| 124 |
+
akey = time(12, 0, 0)
|
| 125 |
+
ainds = [24, 72, 120, 168]
|
| 126 |
+
|
| 127 |
+
result = df.at_time(akey)
|
| 128 |
+
expected = df.loc[akey]
|
| 129 |
+
expected2 = df.iloc[ainds]
|
| 130 |
+
tm.assert_frame_equal(result, expected)
|
| 131 |
+
tm.assert_frame_equal(result, expected2)
|
| 132 |
+
assert len(result) == 4
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_interpolate.py
ADDED
|
@@ -0,0 +1,548 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
|
| 6 |
+
from pandas.errors import ChainedAssignmentError
|
| 7 |
+
import pandas.util._test_decorators as td
|
| 8 |
+
|
| 9 |
+
from pandas import (
|
| 10 |
+
DataFrame,
|
| 11 |
+
NaT,
|
| 12 |
+
Series,
|
| 13 |
+
date_range,
|
| 14 |
+
)
|
| 15 |
+
import pandas._testing as tm
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TestDataFrameInterpolate:
|
| 19 |
+
def test_interpolate_complex(self):
|
| 20 |
+
# GH#53635
|
| 21 |
+
ser = Series([complex("1+1j"), float("nan"), complex("2+2j")])
|
| 22 |
+
assert ser.dtype.kind == "c"
|
| 23 |
+
|
| 24 |
+
res = ser.interpolate()
|
| 25 |
+
expected = Series([ser[0], ser[0] * 1.5, ser[2]])
|
| 26 |
+
tm.assert_series_equal(res, expected)
|
| 27 |
+
|
| 28 |
+
df = ser.to_frame()
|
| 29 |
+
res = df.interpolate()
|
| 30 |
+
expected = expected.to_frame()
|
| 31 |
+
tm.assert_frame_equal(res, expected)
|
| 32 |
+
|
| 33 |
+
def test_interpolate_datetimelike_values(self, frame_or_series):
|
| 34 |
+
# GH#11312, GH#51005
|
| 35 |
+
orig = Series(date_range("2012-01-01", periods=5))
|
| 36 |
+
ser = orig.copy()
|
| 37 |
+
ser[2] = NaT
|
| 38 |
+
|
| 39 |
+
res = frame_or_series(ser).interpolate()
|
| 40 |
+
expected = frame_or_series(orig)
|
| 41 |
+
tm.assert_equal(res, expected)
|
| 42 |
+
|
| 43 |
+
# datetime64tz cast
|
| 44 |
+
ser_tz = ser.dt.tz_localize("US/Pacific")
|
| 45 |
+
res_tz = frame_or_series(ser_tz).interpolate()
|
| 46 |
+
expected_tz = frame_or_series(orig.dt.tz_localize("US/Pacific"))
|
| 47 |
+
tm.assert_equal(res_tz, expected_tz)
|
| 48 |
+
|
| 49 |
+
# timedelta64 cast
|
| 50 |
+
ser_td = ser - ser[0]
|
| 51 |
+
res_td = frame_or_series(ser_td).interpolate()
|
| 52 |
+
expected_td = frame_or_series(orig - orig[0])
|
| 53 |
+
tm.assert_equal(res_td, expected_td)
|
| 54 |
+
|
| 55 |
+
def test_interpolate_inplace(self, frame_or_series, using_array_manager, request):
|
| 56 |
+
# GH#44749
|
| 57 |
+
if using_array_manager and frame_or_series is DataFrame:
|
| 58 |
+
mark = pytest.mark.xfail(reason=".values-based in-place check is invalid")
|
| 59 |
+
request.applymarker(mark)
|
| 60 |
+
|
| 61 |
+
obj = frame_or_series([1, np.nan, 2])
|
| 62 |
+
orig = obj.values
|
| 63 |
+
|
| 64 |
+
obj.interpolate(inplace=True)
|
| 65 |
+
expected = frame_or_series([1, 1.5, 2])
|
| 66 |
+
tm.assert_equal(obj, expected)
|
| 67 |
+
|
| 68 |
+
# check we operated *actually* inplace
|
| 69 |
+
assert np.shares_memory(orig, obj.values)
|
| 70 |
+
assert orig.squeeze()[1] == 1.5
|
| 71 |
+
|
| 72 |
+
@pytest.mark.xfail(
|
| 73 |
+
using_pyarrow_string_dtype(), reason="interpolate doesn't work for string"
|
| 74 |
+
)
|
| 75 |
+
def test_interp_basic(self, using_copy_on_write):
|
| 76 |
+
df = DataFrame(
|
| 77 |
+
{
|
| 78 |
+
"A": [1, 2, np.nan, 4],
|
| 79 |
+
"B": [1, 4, 9, np.nan],
|
| 80 |
+
"C": [1, 2, 3, 5],
|
| 81 |
+
"D": list("abcd"),
|
| 82 |
+
}
|
| 83 |
+
)
|
| 84 |
+
expected = DataFrame(
|
| 85 |
+
{
|
| 86 |
+
"A": [1.0, 2.0, 3.0, 4.0],
|
| 87 |
+
"B": [1.0, 4.0, 9.0, 9.0],
|
| 88 |
+
"C": [1, 2, 3, 5],
|
| 89 |
+
"D": list("abcd"),
|
| 90 |
+
}
|
| 91 |
+
)
|
| 92 |
+
msg = "DataFrame.interpolate with object dtype"
|
| 93 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 94 |
+
result = df.interpolate()
|
| 95 |
+
tm.assert_frame_equal(result, expected)
|
| 96 |
+
|
| 97 |
+
# check we didn't operate inplace GH#45791
|
| 98 |
+
cvalues = df["C"]._values
|
| 99 |
+
dvalues = df["D"].values
|
| 100 |
+
if using_copy_on_write:
|
| 101 |
+
assert np.shares_memory(cvalues, result["C"]._values)
|
| 102 |
+
assert np.shares_memory(dvalues, result["D"]._values)
|
| 103 |
+
else:
|
| 104 |
+
assert not np.shares_memory(cvalues, result["C"]._values)
|
| 105 |
+
assert not np.shares_memory(dvalues, result["D"]._values)
|
| 106 |
+
|
| 107 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 108 |
+
res = df.interpolate(inplace=True)
|
| 109 |
+
assert res is None
|
| 110 |
+
tm.assert_frame_equal(df, expected)
|
| 111 |
+
|
| 112 |
+
# check we DID operate inplace
|
| 113 |
+
assert np.shares_memory(df["C"]._values, cvalues)
|
| 114 |
+
assert np.shares_memory(df["D"]._values, dvalues)
|
| 115 |
+
|
| 116 |
+
@pytest.mark.xfail(
|
| 117 |
+
using_pyarrow_string_dtype(), reason="interpolate doesn't work for string"
|
| 118 |
+
)
|
| 119 |
+
def test_interp_basic_with_non_range_index(self, using_infer_string):
|
| 120 |
+
df = DataFrame(
|
| 121 |
+
{
|
| 122 |
+
"A": [1, 2, np.nan, 4],
|
| 123 |
+
"B": [1, 4, 9, np.nan],
|
| 124 |
+
"C": [1, 2, 3, 5],
|
| 125 |
+
"D": list("abcd"),
|
| 126 |
+
}
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
msg = "DataFrame.interpolate with object dtype"
|
| 130 |
+
warning = FutureWarning if not using_infer_string else None
|
| 131 |
+
with tm.assert_produces_warning(warning, match=msg):
|
| 132 |
+
result = df.set_index("C").interpolate()
|
| 133 |
+
expected = df.set_index("C")
|
| 134 |
+
expected.loc[3, "A"] = 3
|
| 135 |
+
expected.loc[5, "B"] = 9
|
| 136 |
+
tm.assert_frame_equal(result, expected)
|
| 137 |
+
|
| 138 |
+
def test_interp_empty(self):
|
| 139 |
+
# https://github.com/pandas-dev/pandas/issues/35598
|
| 140 |
+
df = DataFrame()
|
| 141 |
+
result = df.interpolate()
|
| 142 |
+
assert result is not df
|
| 143 |
+
expected = df
|
| 144 |
+
tm.assert_frame_equal(result, expected)
|
| 145 |
+
|
| 146 |
+
def test_interp_bad_method(self):
|
| 147 |
+
df = DataFrame(
|
| 148 |
+
{
|
| 149 |
+
"A": [1, 2, np.nan, 4],
|
| 150 |
+
"B": [1, 4, 9, np.nan],
|
| 151 |
+
"C": [1, 2, 3, 5],
|
| 152 |
+
}
|
| 153 |
+
)
|
| 154 |
+
msg = (
|
| 155 |
+
r"method must be one of \['linear', 'time', 'index', 'values', "
|
| 156 |
+
r"'nearest', 'zero', 'slinear', 'quadratic', 'cubic', "
|
| 157 |
+
r"'barycentric', 'krogh', 'spline', 'polynomial', "
|
| 158 |
+
r"'from_derivatives', 'piecewise_polynomial', 'pchip', 'akima', "
|
| 159 |
+
r"'cubicspline'\]. Got 'not_a_method' instead."
|
| 160 |
+
)
|
| 161 |
+
with pytest.raises(ValueError, match=msg):
|
| 162 |
+
df.interpolate(method="not_a_method")
|
| 163 |
+
|
| 164 |
+
def test_interp_combo(self):
|
| 165 |
+
df = DataFrame(
|
| 166 |
+
{
|
| 167 |
+
"A": [1.0, 2.0, np.nan, 4.0],
|
| 168 |
+
"B": [1, 4, 9, np.nan],
|
| 169 |
+
"C": [1, 2, 3, 5],
|
| 170 |
+
"D": list("abcd"),
|
| 171 |
+
}
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
result = df["A"].interpolate()
|
| 175 |
+
expected = Series([1.0, 2.0, 3.0, 4.0], name="A")
|
| 176 |
+
tm.assert_series_equal(result, expected)
|
| 177 |
+
|
| 178 |
+
msg = "The 'downcast' keyword in Series.interpolate is deprecated"
|
| 179 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 180 |
+
result = df["A"].interpolate(downcast="infer")
|
| 181 |
+
expected = Series([1, 2, 3, 4], name="A")
|
| 182 |
+
tm.assert_series_equal(result, expected)
|
| 183 |
+
|
| 184 |
+
def test_inerpolate_invalid_downcast(self):
|
| 185 |
+
# GH#53103
|
| 186 |
+
df = DataFrame(
|
| 187 |
+
{
|
| 188 |
+
"A": [1.0, 2.0, np.nan, 4.0],
|
| 189 |
+
"B": [1, 4, 9, np.nan],
|
| 190 |
+
"C": [1, 2, 3, 5],
|
| 191 |
+
"D": list("abcd"),
|
| 192 |
+
}
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
msg = "downcast must be either None or 'infer'"
|
| 196 |
+
msg2 = "The 'downcast' keyword in DataFrame.interpolate is deprecated"
|
| 197 |
+
msg3 = "The 'downcast' keyword in Series.interpolate is deprecated"
|
| 198 |
+
with pytest.raises(ValueError, match=msg):
|
| 199 |
+
with tm.assert_produces_warning(FutureWarning, match=msg2):
|
| 200 |
+
df.interpolate(downcast="int64")
|
| 201 |
+
with pytest.raises(ValueError, match=msg):
|
| 202 |
+
with tm.assert_produces_warning(FutureWarning, match=msg3):
|
| 203 |
+
df["A"].interpolate(downcast="int64")
|
| 204 |
+
|
| 205 |
+
def test_interp_nan_idx(self):
|
| 206 |
+
df = DataFrame({"A": [1, 2, np.nan, 4], "B": [np.nan, 2, 3, 4]})
|
| 207 |
+
df = df.set_index("A")
|
| 208 |
+
msg = (
|
| 209 |
+
"Interpolation with NaNs in the index has not been implemented. "
|
| 210 |
+
"Try filling those NaNs before interpolating."
|
| 211 |
+
)
|
| 212 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 213 |
+
df.interpolate(method="values")
|
| 214 |
+
|
| 215 |
+
def test_interp_various(self):
|
| 216 |
+
pytest.importorskip("scipy")
|
| 217 |
+
df = DataFrame(
|
| 218 |
+
{"A": [1, 2, np.nan, 4, 5, np.nan, 7], "C": [1, 2, 3, 5, 8, 13, 21]}
|
| 219 |
+
)
|
| 220 |
+
df = df.set_index("C")
|
| 221 |
+
expected = df.copy()
|
| 222 |
+
result = df.interpolate(method="polynomial", order=1)
|
| 223 |
+
|
| 224 |
+
expected.loc[3, "A"] = 2.66666667
|
| 225 |
+
expected.loc[13, "A"] = 5.76923076
|
| 226 |
+
tm.assert_frame_equal(result, expected)
|
| 227 |
+
|
| 228 |
+
result = df.interpolate(method="cubic")
|
| 229 |
+
# GH #15662.
|
| 230 |
+
expected.loc[3, "A"] = 2.81547781
|
| 231 |
+
expected.loc[13, "A"] = 5.52964175
|
| 232 |
+
tm.assert_frame_equal(result, expected)
|
| 233 |
+
|
| 234 |
+
result = df.interpolate(method="nearest")
|
| 235 |
+
expected.loc[3, "A"] = 2
|
| 236 |
+
expected.loc[13, "A"] = 5
|
| 237 |
+
tm.assert_frame_equal(result, expected, check_dtype=False)
|
| 238 |
+
|
| 239 |
+
result = df.interpolate(method="quadratic")
|
| 240 |
+
expected.loc[3, "A"] = 2.82150771
|
| 241 |
+
expected.loc[13, "A"] = 6.12648668
|
| 242 |
+
tm.assert_frame_equal(result, expected)
|
| 243 |
+
|
| 244 |
+
result = df.interpolate(method="slinear")
|
| 245 |
+
expected.loc[3, "A"] = 2.66666667
|
| 246 |
+
expected.loc[13, "A"] = 5.76923077
|
| 247 |
+
tm.assert_frame_equal(result, expected)
|
| 248 |
+
|
| 249 |
+
result = df.interpolate(method="zero")
|
| 250 |
+
expected.loc[3, "A"] = 2.0
|
| 251 |
+
expected.loc[13, "A"] = 5
|
| 252 |
+
tm.assert_frame_equal(result, expected, check_dtype=False)
|
| 253 |
+
|
| 254 |
+
def test_interp_alt_scipy(self):
|
| 255 |
+
pytest.importorskip("scipy")
|
| 256 |
+
df = DataFrame(
|
| 257 |
+
{"A": [1, 2, np.nan, 4, 5, np.nan, 7], "C": [1, 2, 3, 5, 8, 13, 21]}
|
| 258 |
+
)
|
| 259 |
+
result = df.interpolate(method="barycentric")
|
| 260 |
+
expected = df.copy()
|
| 261 |
+
expected.loc[2, "A"] = 3
|
| 262 |
+
expected.loc[5, "A"] = 6
|
| 263 |
+
tm.assert_frame_equal(result, expected)
|
| 264 |
+
|
| 265 |
+
msg = "The 'downcast' keyword in DataFrame.interpolate is deprecated"
|
| 266 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 267 |
+
result = df.interpolate(method="barycentric", downcast="infer")
|
| 268 |
+
tm.assert_frame_equal(result, expected.astype(np.int64))
|
| 269 |
+
|
| 270 |
+
result = df.interpolate(method="krogh")
|
| 271 |
+
expectedk = df.copy()
|
| 272 |
+
expectedk["A"] = expected["A"]
|
| 273 |
+
tm.assert_frame_equal(result, expectedk)
|
| 274 |
+
|
| 275 |
+
result = df.interpolate(method="pchip")
|
| 276 |
+
expected.loc[2, "A"] = 3
|
| 277 |
+
expected.loc[5, "A"] = 6.0
|
| 278 |
+
|
| 279 |
+
tm.assert_frame_equal(result, expected)
|
| 280 |
+
|
| 281 |
+
def test_interp_rowwise(self):
|
| 282 |
+
df = DataFrame(
|
| 283 |
+
{
|
| 284 |
+
0: [1, 2, np.nan, 4],
|
| 285 |
+
1: [2, 3, 4, np.nan],
|
| 286 |
+
2: [np.nan, 4, 5, 6],
|
| 287 |
+
3: [4, np.nan, 6, 7],
|
| 288 |
+
4: [1, 2, 3, 4],
|
| 289 |
+
}
|
| 290 |
+
)
|
| 291 |
+
result = df.interpolate(axis=1)
|
| 292 |
+
expected = df.copy()
|
| 293 |
+
expected.loc[3, 1] = 5
|
| 294 |
+
expected.loc[0, 2] = 3
|
| 295 |
+
expected.loc[1, 3] = 3
|
| 296 |
+
expected[4] = expected[4].astype(np.float64)
|
| 297 |
+
tm.assert_frame_equal(result, expected)
|
| 298 |
+
|
| 299 |
+
result = df.interpolate(axis=1, method="values")
|
| 300 |
+
tm.assert_frame_equal(result, expected)
|
| 301 |
+
|
| 302 |
+
result = df.interpolate(axis=0)
|
| 303 |
+
expected = df.interpolate()
|
| 304 |
+
tm.assert_frame_equal(result, expected)
|
| 305 |
+
|
| 306 |
+
@pytest.mark.parametrize(
|
| 307 |
+
"axis_name, axis_number",
|
| 308 |
+
[
|
| 309 |
+
pytest.param("rows", 0, id="rows_0"),
|
| 310 |
+
pytest.param("index", 0, id="index_0"),
|
| 311 |
+
pytest.param("columns", 1, id="columns_1"),
|
| 312 |
+
],
|
| 313 |
+
)
|
| 314 |
+
def test_interp_axis_names(self, axis_name, axis_number):
|
| 315 |
+
# GH 29132: test axis names
|
| 316 |
+
data = {0: [0, np.nan, 6], 1: [1, np.nan, 7], 2: [2, 5, 8]}
|
| 317 |
+
|
| 318 |
+
df = DataFrame(data, dtype=np.float64)
|
| 319 |
+
result = df.interpolate(axis=axis_name, method="linear")
|
| 320 |
+
expected = df.interpolate(axis=axis_number, method="linear")
|
| 321 |
+
tm.assert_frame_equal(result, expected)
|
| 322 |
+
|
| 323 |
+
def test_rowwise_alt(self):
|
| 324 |
+
df = DataFrame(
|
| 325 |
+
{
|
| 326 |
+
0: [0, 0.5, 1.0, np.nan, 4, 8, np.nan, np.nan, 64],
|
| 327 |
+
1: [1, 2, 3, 4, 3, 2, 1, 0, -1],
|
| 328 |
+
}
|
| 329 |
+
)
|
| 330 |
+
df.interpolate(axis=0)
|
| 331 |
+
# TODO: assert something?
|
| 332 |
+
|
| 333 |
+
@pytest.mark.parametrize(
|
| 334 |
+
"check_scipy", [False, pytest.param(True, marks=td.skip_if_no("scipy"))]
|
| 335 |
+
)
|
| 336 |
+
def test_interp_leading_nans(self, check_scipy):
|
| 337 |
+
df = DataFrame(
|
| 338 |
+
{"A": [np.nan, np.nan, 0.5, 0.25, 0], "B": [np.nan, -3, -3.5, np.nan, -4]}
|
| 339 |
+
)
|
| 340 |
+
result = df.interpolate()
|
| 341 |
+
expected = df.copy()
|
| 342 |
+
expected.loc[3, "B"] = -3.75
|
| 343 |
+
tm.assert_frame_equal(result, expected)
|
| 344 |
+
|
| 345 |
+
if check_scipy:
|
| 346 |
+
result = df.interpolate(method="polynomial", order=1)
|
| 347 |
+
tm.assert_frame_equal(result, expected)
|
| 348 |
+
|
| 349 |
+
def test_interp_raise_on_only_mixed(self, axis):
|
| 350 |
+
df = DataFrame(
|
| 351 |
+
{
|
| 352 |
+
"A": [1, 2, np.nan, 4],
|
| 353 |
+
"B": ["a", "b", "c", "d"],
|
| 354 |
+
"C": [np.nan, 2, 5, 7],
|
| 355 |
+
"D": [np.nan, np.nan, 9, 9],
|
| 356 |
+
"E": [1, 2, 3, 4],
|
| 357 |
+
}
|
| 358 |
+
)
|
| 359 |
+
msg = (
|
| 360 |
+
"Cannot interpolate with all object-dtype columns "
|
| 361 |
+
"in the DataFrame. Try setting at least one "
|
| 362 |
+
"column to a numeric dtype."
|
| 363 |
+
)
|
| 364 |
+
with pytest.raises(TypeError, match=msg):
|
| 365 |
+
df.astype("object").interpolate(axis=axis)
|
| 366 |
+
|
| 367 |
+
def test_interp_raise_on_all_object_dtype(self):
|
| 368 |
+
# GH 22985
|
| 369 |
+
df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, dtype="object")
|
| 370 |
+
msg = (
|
| 371 |
+
"Cannot interpolate with all object-dtype columns "
|
| 372 |
+
"in the DataFrame. Try setting at least one "
|
| 373 |
+
"column to a numeric dtype."
|
| 374 |
+
)
|
| 375 |
+
with pytest.raises(TypeError, match=msg):
|
| 376 |
+
df.interpolate()
|
| 377 |
+
|
| 378 |
+
def test_interp_inplace(self, using_copy_on_write):
|
| 379 |
+
df = DataFrame({"a": [1.0, 2.0, np.nan, 4.0]})
|
| 380 |
+
expected = DataFrame({"a": [1.0, 2.0, 3.0, 4.0]})
|
| 381 |
+
expected_cow = df.copy()
|
| 382 |
+
result = df.copy()
|
| 383 |
+
|
| 384 |
+
if using_copy_on_write:
|
| 385 |
+
with tm.raises_chained_assignment_error():
|
| 386 |
+
return_value = result["a"].interpolate(inplace=True)
|
| 387 |
+
assert return_value is None
|
| 388 |
+
tm.assert_frame_equal(result, expected_cow)
|
| 389 |
+
else:
|
| 390 |
+
with tm.assert_produces_warning(FutureWarning, match="inplace method"):
|
| 391 |
+
return_value = result["a"].interpolate(inplace=True)
|
| 392 |
+
assert return_value is None
|
| 393 |
+
tm.assert_frame_equal(result, expected)
|
| 394 |
+
|
| 395 |
+
result = df.copy()
|
| 396 |
+
msg = "The 'downcast' keyword in Series.interpolate is deprecated"
|
| 397 |
+
|
| 398 |
+
if using_copy_on_write:
|
| 399 |
+
with tm.assert_produces_warning(
|
| 400 |
+
(FutureWarning, ChainedAssignmentError), match=msg
|
| 401 |
+
):
|
| 402 |
+
return_value = result["a"].interpolate(inplace=True, downcast="infer")
|
| 403 |
+
assert return_value is None
|
| 404 |
+
tm.assert_frame_equal(result, expected_cow)
|
| 405 |
+
else:
|
| 406 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 407 |
+
return_value = result["a"].interpolate(inplace=True, downcast="infer")
|
| 408 |
+
assert return_value is None
|
| 409 |
+
tm.assert_frame_equal(result, expected.astype("int64"))
|
| 410 |
+
|
| 411 |
+
def test_interp_inplace_row(self):
|
| 412 |
+
# GH 10395
|
| 413 |
+
result = DataFrame(
|
| 414 |
+
{"a": [1.0, 2.0, 3.0, 4.0], "b": [np.nan, 2.0, 3.0, 4.0], "c": [3, 2, 2, 2]}
|
| 415 |
+
)
|
| 416 |
+
expected = result.interpolate(method="linear", axis=1, inplace=False)
|
| 417 |
+
return_value = result.interpolate(method="linear", axis=1, inplace=True)
|
| 418 |
+
assert return_value is None
|
| 419 |
+
tm.assert_frame_equal(result, expected)
|
| 420 |
+
|
| 421 |
+
def test_interp_ignore_all_good(self):
|
| 422 |
+
# GH
|
| 423 |
+
df = DataFrame(
|
| 424 |
+
{
|
| 425 |
+
"A": [1, 2, np.nan, 4],
|
| 426 |
+
"B": [1, 2, 3, 4],
|
| 427 |
+
"C": [1.0, 2.0, np.nan, 4.0],
|
| 428 |
+
"D": [1.0, 2.0, 3.0, 4.0],
|
| 429 |
+
}
|
| 430 |
+
)
|
| 431 |
+
expected = DataFrame(
|
| 432 |
+
{
|
| 433 |
+
"A": np.array([1, 2, 3, 4], dtype="float64"),
|
| 434 |
+
"B": np.array([1, 2, 3, 4], dtype="int64"),
|
| 435 |
+
"C": np.array([1.0, 2.0, 3, 4.0], dtype="float64"),
|
| 436 |
+
"D": np.array([1.0, 2.0, 3.0, 4.0], dtype="float64"),
|
| 437 |
+
}
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
msg = "The 'downcast' keyword in DataFrame.interpolate is deprecated"
|
| 441 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 442 |
+
result = df.interpolate(downcast=None)
|
| 443 |
+
tm.assert_frame_equal(result, expected)
|
| 444 |
+
|
| 445 |
+
# all good
|
| 446 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 447 |
+
result = df[["B", "D"]].interpolate(downcast=None)
|
| 448 |
+
tm.assert_frame_equal(result, df[["B", "D"]])
|
| 449 |
+
|
| 450 |
+
def test_interp_time_inplace_axis(self):
|
| 451 |
+
# GH 9687
|
| 452 |
+
periods = 5
|
| 453 |
+
idx = date_range(start="2014-01-01", periods=periods)
|
| 454 |
+
data = np.random.default_rng(2).random((periods, periods))
|
| 455 |
+
data[data < 0.5] = np.nan
|
| 456 |
+
expected = DataFrame(index=idx, columns=idx, data=data)
|
| 457 |
+
|
| 458 |
+
result = expected.interpolate(axis=0, method="time")
|
| 459 |
+
return_value = expected.interpolate(axis=0, method="time", inplace=True)
|
| 460 |
+
assert return_value is None
|
| 461 |
+
tm.assert_frame_equal(result, expected)
|
| 462 |
+
|
| 463 |
+
@pytest.mark.parametrize("axis_name, axis_number", [("index", 0), ("columns", 1)])
|
| 464 |
+
def test_interp_string_axis(self, axis_name, axis_number):
|
| 465 |
+
# https://github.com/pandas-dev/pandas/issues/25190
|
| 466 |
+
x = np.linspace(0, 100, 1000)
|
| 467 |
+
y = np.sin(x)
|
| 468 |
+
df = DataFrame(
|
| 469 |
+
data=np.tile(y, (10, 1)), index=np.arange(10), columns=x
|
| 470 |
+
).reindex(columns=x * 1.005)
|
| 471 |
+
result = df.interpolate(method="linear", axis=axis_name)
|
| 472 |
+
expected = df.interpolate(method="linear", axis=axis_number)
|
| 473 |
+
tm.assert_frame_equal(result, expected)
|
| 474 |
+
|
| 475 |
+
@pytest.mark.parametrize("multiblock", [True, False])
|
| 476 |
+
@pytest.mark.parametrize("method", ["ffill", "bfill", "pad"])
|
| 477 |
+
def test_interp_fillna_methods(
|
| 478 |
+
self, request, axis, multiblock, method, using_array_manager
|
| 479 |
+
):
|
| 480 |
+
# GH 12918
|
| 481 |
+
if using_array_manager and axis in (1, "columns"):
|
| 482 |
+
# TODO(ArrayManager) support axis=1
|
| 483 |
+
td.mark_array_manager_not_yet_implemented(request)
|
| 484 |
+
|
| 485 |
+
df = DataFrame(
|
| 486 |
+
{
|
| 487 |
+
"A": [1.0, 2.0, 3.0, 4.0, np.nan, 5.0],
|
| 488 |
+
"B": [2.0, 4.0, 6.0, np.nan, 8.0, 10.0],
|
| 489 |
+
"C": [3.0, 6.0, 9.0, np.nan, np.nan, 30.0],
|
| 490 |
+
}
|
| 491 |
+
)
|
| 492 |
+
if multiblock:
|
| 493 |
+
df["D"] = np.nan
|
| 494 |
+
df["E"] = 1.0
|
| 495 |
+
|
| 496 |
+
method2 = method if method != "pad" else "ffill"
|
| 497 |
+
expected = getattr(df, method2)(axis=axis)
|
| 498 |
+
msg = f"DataFrame.interpolate with method={method} is deprecated"
|
| 499 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 500 |
+
result = df.interpolate(method=method, axis=axis)
|
| 501 |
+
tm.assert_frame_equal(result, expected)
|
| 502 |
+
|
| 503 |
+
def test_interpolate_empty_df(self):
|
| 504 |
+
# GH#53199
|
| 505 |
+
df = DataFrame()
|
| 506 |
+
expected = df.copy()
|
| 507 |
+
result = df.interpolate(inplace=True)
|
| 508 |
+
assert result is None
|
| 509 |
+
tm.assert_frame_equal(df, expected)
|
| 510 |
+
|
| 511 |
+
def test_interpolate_ea(self, any_int_ea_dtype):
|
| 512 |
+
# GH#55347
|
| 513 |
+
df = DataFrame({"a": [1, None, None, None, 3]}, dtype=any_int_ea_dtype)
|
| 514 |
+
orig = df.copy()
|
| 515 |
+
result = df.interpolate(limit=2)
|
| 516 |
+
expected = DataFrame({"a": [1, 1.5, 2.0, None, 3]}, dtype="Float64")
|
| 517 |
+
tm.assert_frame_equal(result, expected)
|
| 518 |
+
tm.assert_frame_equal(df, orig)
|
| 519 |
+
|
| 520 |
+
@pytest.mark.parametrize(
|
| 521 |
+
"dtype",
|
| 522 |
+
[
|
| 523 |
+
"Float64",
|
| 524 |
+
"Float32",
|
| 525 |
+
pytest.param("float32[pyarrow]", marks=td.skip_if_no("pyarrow")),
|
| 526 |
+
pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow")),
|
| 527 |
+
],
|
| 528 |
+
)
|
| 529 |
+
def test_interpolate_ea_float(self, dtype):
|
| 530 |
+
# GH#55347
|
| 531 |
+
df = DataFrame({"a": [1, None, None, None, 3]}, dtype=dtype)
|
| 532 |
+
orig = df.copy()
|
| 533 |
+
result = df.interpolate(limit=2)
|
| 534 |
+
expected = DataFrame({"a": [1, 1.5, 2.0, None, 3]}, dtype=dtype)
|
| 535 |
+
tm.assert_frame_equal(result, expected)
|
| 536 |
+
tm.assert_frame_equal(df, orig)
|
| 537 |
+
|
| 538 |
+
@pytest.mark.parametrize(
|
| 539 |
+
"dtype",
|
| 540 |
+
["int64", "uint64", "int32", "int16", "int8", "uint32", "uint16", "uint8"],
|
| 541 |
+
)
|
| 542 |
+
def test_interpolate_arrow(self, dtype):
|
| 543 |
+
# GH#55347
|
| 544 |
+
pytest.importorskip("pyarrow")
|
| 545 |
+
df = DataFrame({"a": [1, None, None, None, 3]}, dtype=dtype + "[pyarrow]")
|
| 546 |
+
result = df.interpolate(limit=2)
|
| 547 |
+
expected = DataFrame({"a": [1, 1.5, 2.0, None, 3]}, dtype="float64[pyarrow]")
|
| 548 |
+
tm.assert_frame_equal(result, expected)
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_quantile.py
ADDED
|
@@ -0,0 +1,972 @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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas import (
|
| 6 |
+
DataFrame,
|
| 7 |
+
Index,
|
| 8 |
+
Series,
|
| 9 |
+
Timestamp,
|
| 10 |
+
)
|
| 11 |
+
import pandas._testing as tm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest.fixture(
|
| 15 |
+
params=[["linear", "single"], ["nearest", "table"]], ids=lambda x: "-".join(x)
|
| 16 |
+
)
|
| 17 |
+
def interp_method(request):
|
| 18 |
+
"""(interpolation, method) arguments for quantile"""
|
| 19 |
+
return request.param
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TestDataFrameQuantile:
|
| 23 |
+
@pytest.mark.parametrize(
|
| 24 |
+
"df,expected",
|
| 25 |
+
[
|
| 26 |
+
[
|
| 27 |
+
DataFrame(
|
| 28 |
+
{
|
| 29 |
+
0: Series(pd.arrays.SparseArray([1, 2])),
|
| 30 |
+
1: Series(pd.arrays.SparseArray([3, 4])),
|
| 31 |
+
}
|
| 32 |
+
),
|
| 33 |
+
Series([1.5, 3.5], name=0.5),
|
| 34 |
+
],
|
| 35 |
+
[
|
| 36 |
+
DataFrame(Series([0.0, None, 1.0, 2.0], dtype="Sparse[float]")),
|
| 37 |
+
Series([1.0], name=0.5),
|
| 38 |
+
],
|
| 39 |
+
],
|
| 40 |
+
)
|
| 41 |
+
def test_quantile_sparse(self, df, expected):
|
| 42 |
+
# GH#17198
|
| 43 |
+
# GH#24600
|
| 44 |
+
result = df.quantile()
|
| 45 |
+
expected = expected.astype("Sparse[float]")
|
| 46 |
+
tm.assert_series_equal(result, expected)
|
| 47 |
+
|
| 48 |
+
def test_quantile(
|
| 49 |
+
self, datetime_frame, interp_method, using_array_manager, request
|
| 50 |
+
):
|
| 51 |
+
interpolation, method = interp_method
|
| 52 |
+
df = datetime_frame
|
| 53 |
+
result = df.quantile(
|
| 54 |
+
0.1, axis=0, numeric_only=True, interpolation=interpolation, method=method
|
| 55 |
+
)
|
| 56 |
+
expected = Series(
|
| 57 |
+
[np.percentile(df[col], 10) for col in df.columns],
|
| 58 |
+
index=df.columns,
|
| 59 |
+
name=0.1,
|
| 60 |
+
)
|
| 61 |
+
if interpolation == "linear":
|
| 62 |
+
# np.percentile values only comparable to linear interpolation
|
| 63 |
+
tm.assert_series_equal(result, expected)
|
| 64 |
+
else:
|
| 65 |
+
tm.assert_index_equal(result.index, expected.index)
|
| 66 |
+
request.applymarker(
|
| 67 |
+
pytest.mark.xfail(
|
| 68 |
+
using_array_manager, reason="Name set incorrectly for arraymanager"
|
| 69 |
+
)
|
| 70 |
+
)
|
| 71 |
+
assert result.name == expected.name
|
| 72 |
+
|
| 73 |
+
result = df.quantile(
|
| 74 |
+
0.9, axis=1, numeric_only=True, interpolation=interpolation, method=method
|
| 75 |
+
)
|
| 76 |
+
expected = Series(
|
| 77 |
+
[np.percentile(df.loc[date], 90) for date in df.index],
|
| 78 |
+
index=df.index,
|
| 79 |
+
name=0.9,
|
| 80 |
+
)
|
| 81 |
+
if interpolation == "linear":
|
| 82 |
+
# np.percentile values only comparable to linear interpolation
|
| 83 |
+
tm.assert_series_equal(result, expected)
|
| 84 |
+
else:
|
| 85 |
+
tm.assert_index_equal(result.index, expected.index)
|
| 86 |
+
request.applymarker(
|
| 87 |
+
pytest.mark.xfail(
|
| 88 |
+
using_array_manager, reason="Name set incorrectly for arraymanager"
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
assert result.name == expected.name
|
| 92 |
+
|
| 93 |
+
def test_empty(self, interp_method):
|
| 94 |
+
interpolation, method = interp_method
|
| 95 |
+
q = DataFrame({"x": [], "y": []}).quantile(
|
| 96 |
+
0.1, axis=0, numeric_only=True, interpolation=interpolation, method=method
|
| 97 |
+
)
|
| 98 |
+
assert np.isnan(q["x"]) and np.isnan(q["y"])
|
| 99 |
+
|
| 100 |
+
def test_non_numeric_exclusion(self, interp_method, request, using_array_manager):
|
| 101 |
+
interpolation, method = interp_method
|
| 102 |
+
df = DataFrame({"col1": ["A", "A", "B", "B"], "col2": [1, 2, 3, 4]})
|
| 103 |
+
rs = df.quantile(
|
| 104 |
+
0.5, numeric_only=True, interpolation=interpolation, method=method
|
| 105 |
+
)
|
| 106 |
+
xp = df.median(numeric_only=True).rename(0.5)
|
| 107 |
+
if interpolation == "nearest":
|
| 108 |
+
xp = (xp + 0.5).astype(np.int64)
|
| 109 |
+
if method == "table" and using_array_manager:
|
| 110 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 111 |
+
tm.assert_series_equal(rs, xp)
|
| 112 |
+
|
| 113 |
+
def test_axis(self, interp_method, request, using_array_manager):
|
| 114 |
+
# axis
|
| 115 |
+
interpolation, method = interp_method
|
| 116 |
+
df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3])
|
| 117 |
+
result = df.quantile(0.5, axis=1, interpolation=interpolation, method=method)
|
| 118 |
+
expected = Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5)
|
| 119 |
+
if interpolation == "nearest":
|
| 120 |
+
expected = expected.astype(np.int64)
|
| 121 |
+
if method == "table" and using_array_manager:
|
| 122 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 123 |
+
tm.assert_series_equal(result, expected)
|
| 124 |
+
|
| 125 |
+
result = df.quantile(
|
| 126 |
+
[0.5, 0.75], axis=1, interpolation=interpolation, method=method
|
| 127 |
+
)
|
| 128 |
+
expected = DataFrame(
|
| 129 |
+
{1: [1.5, 1.75], 2: [2.5, 2.75], 3: [3.5, 3.75]}, index=[0.5, 0.75]
|
| 130 |
+
)
|
| 131 |
+
if interpolation == "nearest":
|
| 132 |
+
expected.iloc[0, :] -= 0.5
|
| 133 |
+
expected.iloc[1, :] += 0.25
|
| 134 |
+
expected = expected.astype(np.int64)
|
| 135 |
+
tm.assert_frame_equal(result, expected, check_index_type=True)
|
| 136 |
+
|
| 137 |
+
def test_axis_numeric_only_true(self, interp_method, request, using_array_manager):
|
| 138 |
+
# We may want to break API in the future to change this
|
| 139 |
+
# so that we exclude non-numeric along the same axis
|
| 140 |
+
# See GH #7312
|
| 141 |
+
interpolation, method = interp_method
|
| 142 |
+
df = DataFrame([[1, 2, 3], ["a", "b", 4]])
|
| 143 |
+
result = df.quantile(
|
| 144 |
+
0.5, axis=1, numeric_only=True, interpolation=interpolation, method=method
|
| 145 |
+
)
|
| 146 |
+
expected = Series([3.0, 4.0], index=[0, 1], name=0.5)
|
| 147 |
+
if interpolation == "nearest":
|
| 148 |
+
expected = expected.astype(np.int64)
|
| 149 |
+
if method == "table" and using_array_manager:
|
| 150 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 151 |
+
tm.assert_series_equal(result, expected)
|
| 152 |
+
|
| 153 |
+
def test_quantile_date_range(self, interp_method, request, using_array_manager):
|
| 154 |
+
# GH 2460
|
| 155 |
+
interpolation, method = interp_method
|
| 156 |
+
dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")
|
| 157 |
+
ser = Series(dti)
|
| 158 |
+
df = DataFrame(ser)
|
| 159 |
+
|
| 160 |
+
result = df.quantile(
|
| 161 |
+
numeric_only=False, interpolation=interpolation, method=method
|
| 162 |
+
)
|
| 163 |
+
expected = Series(
|
| 164 |
+
["2016-01-02 00:00:00"], name=0.5, dtype="datetime64[ns, US/Pacific]"
|
| 165 |
+
)
|
| 166 |
+
if method == "table" and using_array_manager:
|
| 167 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 168 |
+
|
| 169 |
+
tm.assert_series_equal(result, expected)
|
| 170 |
+
|
| 171 |
+
def test_quantile_axis_mixed(self, interp_method, request, using_array_manager):
|
| 172 |
+
# mixed on axis=1
|
| 173 |
+
interpolation, method = interp_method
|
| 174 |
+
df = DataFrame(
|
| 175 |
+
{
|
| 176 |
+
"A": [1, 2, 3],
|
| 177 |
+
"B": [2.0, 3.0, 4.0],
|
| 178 |
+
"C": pd.date_range("20130101", periods=3),
|
| 179 |
+
"D": ["foo", "bar", "baz"],
|
| 180 |
+
}
|
| 181 |
+
)
|
| 182 |
+
result = df.quantile(
|
| 183 |
+
0.5, axis=1, numeric_only=True, interpolation=interpolation, method=method
|
| 184 |
+
)
|
| 185 |
+
expected = Series([1.5, 2.5, 3.5], name=0.5)
|
| 186 |
+
if interpolation == "nearest":
|
| 187 |
+
expected -= 0.5
|
| 188 |
+
if method == "table" and using_array_manager:
|
| 189 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 190 |
+
tm.assert_series_equal(result, expected)
|
| 191 |
+
|
| 192 |
+
# must raise
|
| 193 |
+
msg = "'<' not supported between instances of 'Timestamp' and 'float'"
|
| 194 |
+
with pytest.raises(TypeError, match=msg):
|
| 195 |
+
df.quantile(0.5, axis=1, numeric_only=False)
|
| 196 |
+
|
| 197 |
+
def test_quantile_axis_parameter(self, interp_method, request, using_array_manager):
|
| 198 |
+
# GH 9543/9544
|
| 199 |
+
interpolation, method = interp_method
|
| 200 |
+
if method == "table" and using_array_manager:
|
| 201 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 202 |
+
df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3])
|
| 203 |
+
|
| 204 |
+
result = df.quantile(0.5, axis=0, interpolation=interpolation, method=method)
|
| 205 |
+
|
| 206 |
+
expected = Series([2.0, 3.0], index=["A", "B"], name=0.5)
|
| 207 |
+
if interpolation == "nearest":
|
| 208 |
+
expected = expected.astype(np.int64)
|
| 209 |
+
tm.assert_series_equal(result, expected)
|
| 210 |
+
|
| 211 |
+
expected = df.quantile(
|
| 212 |
+
0.5, axis="index", interpolation=interpolation, method=method
|
| 213 |
+
)
|
| 214 |
+
if interpolation == "nearest":
|
| 215 |
+
expected = expected.astype(np.int64)
|
| 216 |
+
tm.assert_series_equal(result, expected)
|
| 217 |
+
|
| 218 |
+
result = df.quantile(0.5, axis=1, interpolation=interpolation, method=method)
|
| 219 |
+
|
| 220 |
+
expected = Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5)
|
| 221 |
+
if interpolation == "nearest":
|
| 222 |
+
expected = expected.astype(np.int64)
|
| 223 |
+
tm.assert_series_equal(result, expected)
|
| 224 |
+
|
| 225 |
+
result = df.quantile(
|
| 226 |
+
0.5, axis="columns", interpolation=interpolation, method=method
|
| 227 |
+
)
|
| 228 |
+
tm.assert_series_equal(result, expected)
|
| 229 |
+
|
| 230 |
+
msg = "No axis named -1 for object type DataFrame"
|
| 231 |
+
with pytest.raises(ValueError, match=msg):
|
| 232 |
+
df.quantile(0.1, axis=-1, interpolation=interpolation, method=method)
|
| 233 |
+
msg = "No axis named column for object type DataFrame"
|
| 234 |
+
with pytest.raises(ValueError, match=msg):
|
| 235 |
+
df.quantile(0.1, axis="column")
|
| 236 |
+
|
| 237 |
+
def test_quantile_interpolation(self):
|
| 238 |
+
# see gh-10174
|
| 239 |
+
|
| 240 |
+
# interpolation method other than default linear
|
| 241 |
+
df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3])
|
| 242 |
+
result = df.quantile(0.5, axis=1, interpolation="nearest")
|
| 243 |
+
expected = Series([1, 2, 3], index=[1, 2, 3], name=0.5)
|
| 244 |
+
tm.assert_series_equal(result, expected)
|
| 245 |
+
|
| 246 |
+
# cross-check interpolation=nearest results in original dtype
|
| 247 |
+
exp = np.percentile(
|
| 248 |
+
np.array([[1, 2, 3], [2, 3, 4]]),
|
| 249 |
+
0.5,
|
| 250 |
+
axis=0,
|
| 251 |
+
method="nearest",
|
| 252 |
+
)
|
| 253 |
+
expected = Series(exp, index=[1, 2, 3], name=0.5, dtype="int64")
|
| 254 |
+
tm.assert_series_equal(result, expected)
|
| 255 |
+
|
| 256 |
+
# float
|
| 257 |
+
df = DataFrame({"A": [1.0, 2.0, 3.0], "B": [2.0, 3.0, 4.0]}, index=[1, 2, 3])
|
| 258 |
+
result = df.quantile(0.5, axis=1, interpolation="nearest")
|
| 259 |
+
expected = Series([1.0, 2.0, 3.0], index=[1, 2, 3], name=0.5)
|
| 260 |
+
tm.assert_series_equal(result, expected)
|
| 261 |
+
exp = np.percentile(
|
| 262 |
+
np.array([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]]),
|
| 263 |
+
0.5,
|
| 264 |
+
axis=0,
|
| 265 |
+
method="nearest",
|
| 266 |
+
)
|
| 267 |
+
expected = Series(exp, index=[1, 2, 3], name=0.5, dtype="float64")
|
| 268 |
+
tm.assert_series_equal(result, expected)
|
| 269 |
+
|
| 270 |
+
# axis
|
| 271 |
+
result = df.quantile([0.5, 0.75], axis=1, interpolation="lower")
|
| 272 |
+
expected = DataFrame(
|
| 273 |
+
{1: [1.0, 1.0], 2: [2.0, 2.0], 3: [3.0, 3.0]}, index=[0.5, 0.75]
|
| 274 |
+
)
|
| 275 |
+
tm.assert_frame_equal(result, expected)
|
| 276 |
+
|
| 277 |
+
# test degenerate case
|
| 278 |
+
df = DataFrame({"x": [], "y": []})
|
| 279 |
+
q = df.quantile(0.1, axis=0, interpolation="higher")
|
| 280 |
+
assert np.isnan(q["x"]) and np.isnan(q["y"])
|
| 281 |
+
|
| 282 |
+
# multi
|
| 283 |
+
df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"])
|
| 284 |
+
result = df.quantile([0.25, 0.5], interpolation="midpoint")
|
| 285 |
+
|
| 286 |
+
# https://github.com/numpy/numpy/issues/7163
|
| 287 |
+
expected = DataFrame(
|
| 288 |
+
[[1.5, 1.5, 1.5], [2.0, 2.0, 2.0]],
|
| 289 |
+
index=[0.25, 0.5],
|
| 290 |
+
columns=["a", "b", "c"],
|
| 291 |
+
)
|
| 292 |
+
tm.assert_frame_equal(result, expected)
|
| 293 |
+
|
| 294 |
+
def test_quantile_interpolation_datetime(self, datetime_frame):
|
| 295 |
+
# see gh-10174
|
| 296 |
+
|
| 297 |
+
# interpolation = linear (default case)
|
| 298 |
+
df = datetime_frame
|
| 299 |
+
q = df.quantile(0.1, axis=0, numeric_only=True, interpolation="linear")
|
| 300 |
+
assert q["A"] == np.percentile(df["A"], 10)
|
| 301 |
+
|
| 302 |
+
def test_quantile_interpolation_int(self, int_frame):
|
| 303 |
+
# see gh-10174
|
| 304 |
+
|
| 305 |
+
df = int_frame
|
| 306 |
+
# interpolation = linear (default case)
|
| 307 |
+
q = df.quantile(0.1)
|
| 308 |
+
assert q["A"] == np.percentile(df["A"], 10)
|
| 309 |
+
|
| 310 |
+
# test with and without interpolation keyword
|
| 311 |
+
q1 = df.quantile(0.1, axis=0, interpolation="linear")
|
| 312 |
+
assert q1["A"] == np.percentile(df["A"], 10)
|
| 313 |
+
tm.assert_series_equal(q, q1)
|
| 314 |
+
|
| 315 |
+
def test_quantile_multi(self, interp_method, request, using_array_manager):
|
| 316 |
+
interpolation, method = interp_method
|
| 317 |
+
df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"])
|
| 318 |
+
result = df.quantile([0.25, 0.5], interpolation=interpolation, method=method)
|
| 319 |
+
expected = DataFrame(
|
| 320 |
+
[[1.5, 1.5, 1.5], [2.0, 2.0, 2.0]],
|
| 321 |
+
index=[0.25, 0.5],
|
| 322 |
+
columns=["a", "b", "c"],
|
| 323 |
+
)
|
| 324 |
+
if interpolation == "nearest":
|
| 325 |
+
expected = expected.astype(np.int64)
|
| 326 |
+
if method == "table" and using_array_manager:
|
| 327 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 328 |
+
tm.assert_frame_equal(result, expected)
|
| 329 |
+
|
| 330 |
+
def test_quantile_multi_axis_1(self, interp_method, request, using_array_manager):
|
| 331 |
+
interpolation, method = interp_method
|
| 332 |
+
df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"])
|
| 333 |
+
result = df.quantile(
|
| 334 |
+
[0.25, 0.5], axis=1, interpolation=interpolation, method=method
|
| 335 |
+
)
|
| 336 |
+
expected = DataFrame(
|
| 337 |
+
[[1.0, 2.0, 3.0]] * 2, index=[0.25, 0.5], columns=[0, 1, 2]
|
| 338 |
+
)
|
| 339 |
+
if interpolation == "nearest":
|
| 340 |
+
expected = expected.astype(np.int64)
|
| 341 |
+
if method == "table" and using_array_manager:
|
| 342 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 343 |
+
tm.assert_frame_equal(result, expected)
|
| 344 |
+
|
| 345 |
+
def test_quantile_multi_empty(self, interp_method):
|
| 346 |
+
interpolation, method = interp_method
|
| 347 |
+
result = DataFrame({"x": [], "y": []}).quantile(
|
| 348 |
+
[0.1, 0.9], axis=0, interpolation=interpolation, method=method
|
| 349 |
+
)
|
| 350 |
+
expected = DataFrame(
|
| 351 |
+
{"x": [np.nan, np.nan], "y": [np.nan, np.nan]}, index=[0.1, 0.9]
|
| 352 |
+
)
|
| 353 |
+
tm.assert_frame_equal(result, expected)
|
| 354 |
+
|
| 355 |
+
def test_quantile_datetime(self, unit):
|
| 356 |
+
dti = pd.to_datetime(["2010", "2011"]).as_unit(unit)
|
| 357 |
+
df = DataFrame({"a": dti, "b": [0, 5]})
|
| 358 |
+
|
| 359 |
+
# exclude datetime
|
| 360 |
+
result = df.quantile(0.5, numeric_only=True)
|
| 361 |
+
expected = Series([2.5], index=["b"], name=0.5)
|
| 362 |
+
tm.assert_series_equal(result, expected)
|
| 363 |
+
|
| 364 |
+
# datetime
|
| 365 |
+
result = df.quantile(0.5, numeric_only=False)
|
| 366 |
+
expected = Series(
|
| 367 |
+
[Timestamp("2010-07-02 12:00:00"), 2.5], index=["a", "b"], name=0.5
|
| 368 |
+
)
|
| 369 |
+
tm.assert_series_equal(result, expected)
|
| 370 |
+
|
| 371 |
+
# datetime w/ multi
|
| 372 |
+
result = df.quantile([0.5], numeric_only=False)
|
| 373 |
+
expected = DataFrame(
|
| 374 |
+
{"a": Timestamp("2010-07-02 12:00:00").as_unit(unit), "b": 2.5},
|
| 375 |
+
index=[0.5],
|
| 376 |
+
)
|
| 377 |
+
tm.assert_frame_equal(result, expected)
|
| 378 |
+
|
| 379 |
+
# axis = 1
|
| 380 |
+
df["c"] = pd.to_datetime(["2011", "2012"]).as_unit(unit)
|
| 381 |
+
result = df[["a", "c"]].quantile(0.5, axis=1, numeric_only=False)
|
| 382 |
+
expected = Series(
|
| 383 |
+
[Timestamp("2010-07-02 12:00:00"), Timestamp("2011-07-02 12:00:00")],
|
| 384 |
+
index=[0, 1],
|
| 385 |
+
name=0.5,
|
| 386 |
+
dtype=f"M8[{unit}]",
|
| 387 |
+
)
|
| 388 |
+
tm.assert_series_equal(result, expected)
|
| 389 |
+
|
| 390 |
+
result = df[["a", "c"]].quantile([0.5], axis=1, numeric_only=False)
|
| 391 |
+
expected = DataFrame(
|
| 392 |
+
[[Timestamp("2010-07-02 12:00:00"), Timestamp("2011-07-02 12:00:00")]],
|
| 393 |
+
index=[0.5],
|
| 394 |
+
columns=[0, 1],
|
| 395 |
+
dtype=f"M8[{unit}]",
|
| 396 |
+
)
|
| 397 |
+
tm.assert_frame_equal(result, expected)
|
| 398 |
+
|
| 399 |
+
# empty when numeric_only=True
|
| 400 |
+
result = df[["a", "c"]].quantile(0.5, numeric_only=True)
|
| 401 |
+
expected = Series([], index=[], dtype=np.float64, name=0.5)
|
| 402 |
+
tm.assert_series_equal(result, expected)
|
| 403 |
+
|
| 404 |
+
result = df[["a", "c"]].quantile([0.5], numeric_only=True)
|
| 405 |
+
expected = DataFrame(index=[0.5], columns=[])
|
| 406 |
+
tm.assert_frame_equal(result, expected)
|
| 407 |
+
|
| 408 |
+
@pytest.mark.parametrize(
|
| 409 |
+
"dtype",
|
| 410 |
+
[
|
| 411 |
+
"datetime64[ns]",
|
| 412 |
+
"datetime64[ns, US/Pacific]",
|
| 413 |
+
"timedelta64[ns]",
|
| 414 |
+
"Period[D]",
|
| 415 |
+
],
|
| 416 |
+
)
|
| 417 |
+
def test_quantile_dt64_empty(self, dtype, interp_method):
|
| 418 |
+
# GH#41544
|
| 419 |
+
interpolation, method = interp_method
|
| 420 |
+
df = DataFrame(columns=["a", "b"], dtype=dtype)
|
| 421 |
+
|
| 422 |
+
res = df.quantile(
|
| 423 |
+
0.5, axis=1, numeric_only=False, interpolation=interpolation, method=method
|
| 424 |
+
)
|
| 425 |
+
expected = Series([], index=[], name=0.5, dtype=dtype)
|
| 426 |
+
tm.assert_series_equal(res, expected)
|
| 427 |
+
|
| 428 |
+
# no columns in result, so no dtype preservation
|
| 429 |
+
res = df.quantile(
|
| 430 |
+
[0.5],
|
| 431 |
+
axis=1,
|
| 432 |
+
numeric_only=False,
|
| 433 |
+
interpolation=interpolation,
|
| 434 |
+
method=method,
|
| 435 |
+
)
|
| 436 |
+
expected = DataFrame(index=[0.5], columns=[])
|
| 437 |
+
tm.assert_frame_equal(res, expected)
|
| 438 |
+
|
| 439 |
+
@pytest.mark.parametrize("invalid", [-1, 2, [0.5, -1], [0.5, 2]])
|
| 440 |
+
def test_quantile_invalid(self, invalid, datetime_frame, interp_method):
|
| 441 |
+
msg = "percentiles should all be in the interval \\[0, 1\\]"
|
| 442 |
+
interpolation, method = interp_method
|
| 443 |
+
with pytest.raises(ValueError, match=msg):
|
| 444 |
+
datetime_frame.quantile(invalid, interpolation=interpolation, method=method)
|
| 445 |
+
|
| 446 |
+
def test_quantile_box(self, interp_method, request, using_array_manager):
|
| 447 |
+
interpolation, method = interp_method
|
| 448 |
+
if method == "table" and using_array_manager:
|
| 449 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 450 |
+
df = DataFrame(
|
| 451 |
+
{
|
| 452 |
+
"A": [
|
| 453 |
+
Timestamp("2011-01-01"),
|
| 454 |
+
Timestamp("2011-01-02"),
|
| 455 |
+
Timestamp("2011-01-03"),
|
| 456 |
+
],
|
| 457 |
+
"B": [
|
| 458 |
+
Timestamp("2011-01-01", tz="US/Eastern"),
|
| 459 |
+
Timestamp("2011-01-02", tz="US/Eastern"),
|
| 460 |
+
Timestamp("2011-01-03", tz="US/Eastern"),
|
| 461 |
+
],
|
| 462 |
+
"C": [
|
| 463 |
+
pd.Timedelta("1 days"),
|
| 464 |
+
pd.Timedelta("2 days"),
|
| 465 |
+
pd.Timedelta("3 days"),
|
| 466 |
+
],
|
| 467 |
+
}
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
res = df.quantile(
|
| 471 |
+
0.5, numeric_only=False, interpolation=interpolation, method=method
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
exp = Series(
|
| 475 |
+
[
|
| 476 |
+
Timestamp("2011-01-02"),
|
| 477 |
+
Timestamp("2011-01-02", tz="US/Eastern"),
|
| 478 |
+
pd.Timedelta("2 days"),
|
| 479 |
+
],
|
| 480 |
+
name=0.5,
|
| 481 |
+
index=["A", "B", "C"],
|
| 482 |
+
)
|
| 483 |
+
tm.assert_series_equal(res, exp)
|
| 484 |
+
|
| 485 |
+
res = df.quantile(
|
| 486 |
+
[0.5], numeric_only=False, interpolation=interpolation, method=method
|
| 487 |
+
)
|
| 488 |
+
exp = DataFrame(
|
| 489 |
+
[
|
| 490 |
+
[
|
| 491 |
+
Timestamp("2011-01-02"),
|
| 492 |
+
Timestamp("2011-01-02", tz="US/Eastern"),
|
| 493 |
+
pd.Timedelta("2 days"),
|
| 494 |
+
]
|
| 495 |
+
],
|
| 496 |
+
index=[0.5],
|
| 497 |
+
columns=["A", "B", "C"],
|
| 498 |
+
)
|
| 499 |
+
tm.assert_frame_equal(res, exp)
|
| 500 |
+
|
| 501 |
+
def test_quantile_box_nat(self):
|
| 502 |
+
# DatetimeLikeBlock may be consolidated and contain NaT in different loc
|
| 503 |
+
df = DataFrame(
|
| 504 |
+
{
|
| 505 |
+
"A": [
|
| 506 |
+
Timestamp("2011-01-01"),
|
| 507 |
+
pd.NaT,
|
| 508 |
+
Timestamp("2011-01-02"),
|
| 509 |
+
Timestamp("2011-01-03"),
|
| 510 |
+
],
|
| 511 |
+
"a": [
|
| 512 |
+
Timestamp("2011-01-01"),
|
| 513 |
+
Timestamp("2011-01-02"),
|
| 514 |
+
pd.NaT,
|
| 515 |
+
Timestamp("2011-01-03"),
|
| 516 |
+
],
|
| 517 |
+
"B": [
|
| 518 |
+
Timestamp("2011-01-01", tz="US/Eastern"),
|
| 519 |
+
pd.NaT,
|
| 520 |
+
Timestamp("2011-01-02", tz="US/Eastern"),
|
| 521 |
+
Timestamp("2011-01-03", tz="US/Eastern"),
|
| 522 |
+
],
|
| 523 |
+
"b": [
|
| 524 |
+
Timestamp("2011-01-01", tz="US/Eastern"),
|
| 525 |
+
Timestamp("2011-01-02", tz="US/Eastern"),
|
| 526 |
+
pd.NaT,
|
| 527 |
+
Timestamp("2011-01-03", tz="US/Eastern"),
|
| 528 |
+
],
|
| 529 |
+
"C": [
|
| 530 |
+
pd.Timedelta("1 days"),
|
| 531 |
+
pd.Timedelta("2 days"),
|
| 532 |
+
pd.Timedelta("3 days"),
|
| 533 |
+
pd.NaT,
|
| 534 |
+
],
|
| 535 |
+
"c": [
|
| 536 |
+
pd.NaT,
|
| 537 |
+
pd.Timedelta("1 days"),
|
| 538 |
+
pd.Timedelta("2 days"),
|
| 539 |
+
pd.Timedelta("3 days"),
|
| 540 |
+
],
|
| 541 |
+
},
|
| 542 |
+
columns=list("AaBbCc"),
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
res = df.quantile(0.5, numeric_only=False)
|
| 546 |
+
exp = Series(
|
| 547 |
+
[
|
| 548 |
+
Timestamp("2011-01-02"),
|
| 549 |
+
Timestamp("2011-01-02"),
|
| 550 |
+
Timestamp("2011-01-02", tz="US/Eastern"),
|
| 551 |
+
Timestamp("2011-01-02", tz="US/Eastern"),
|
| 552 |
+
pd.Timedelta("2 days"),
|
| 553 |
+
pd.Timedelta("2 days"),
|
| 554 |
+
],
|
| 555 |
+
name=0.5,
|
| 556 |
+
index=list("AaBbCc"),
|
| 557 |
+
)
|
| 558 |
+
tm.assert_series_equal(res, exp)
|
| 559 |
+
|
| 560 |
+
res = df.quantile([0.5], numeric_only=False)
|
| 561 |
+
exp = DataFrame(
|
| 562 |
+
[
|
| 563 |
+
[
|
| 564 |
+
Timestamp("2011-01-02"),
|
| 565 |
+
Timestamp("2011-01-02"),
|
| 566 |
+
Timestamp("2011-01-02", tz="US/Eastern"),
|
| 567 |
+
Timestamp("2011-01-02", tz="US/Eastern"),
|
| 568 |
+
pd.Timedelta("2 days"),
|
| 569 |
+
pd.Timedelta("2 days"),
|
| 570 |
+
]
|
| 571 |
+
],
|
| 572 |
+
index=[0.5],
|
| 573 |
+
columns=list("AaBbCc"),
|
| 574 |
+
)
|
| 575 |
+
tm.assert_frame_equal(res, exp)
|
| 576 |
+
|
| 577 |
+
def test_quantile_nan(self, interp_method, request, using_array_manager):
|
| 578 |
+
interpolation, method = interp_method
|
| 579 |
+
if method == "table" and using_array_manager:
|
| 580 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 581 |
+
# GH 14357 - float block where some cols have missing values
|
| 582 |
+
df = DataFrame({"a": np.arange(1, 6.0), "b": np.arange(1, 6.0)})
|
| 583 |
+
df.iloc[-1, 1] = np.nan
|
| 584 |
+
|
| 585 |
+
res = df.quantile(0.5, interpolation=interpolation, method=method)
|
| 586 |
+
exp = Series(
|
| 587 |
+
[3.0, 2.5 if interpolation == "linear" else 3.0], index=["a", "b"], name=0.5
|
| 588 |
+
)
|
| 589 |
+
tm.assert_series_equal(res, exp)
|
| 590 |
+
|
| 591 |
+
res = df.quantile([0.5, 0.75], interpolation=interpolation, method=method)
|
| 592 |
+
exp = DataFrame(
|
| 593 |
+
{
|
| 594 |
+
"a": [3.0, 4.0],
|
| 595 |
+
"b": [2.5, 3.25] if interpolation == "linear" else [3.0, 4.0],
|
| 596 |
+
},
|
| 597 |
+
index=[0.5, 0.75],
|
| 598 |
+
)
|
| 599 |
+
tm.assert_frame_equal(res, exp)
|
| 600 |
+
|
| 601 |
+
res = df.quantile(0.5, axis=1, interpolation=interpolation, method=method)
|
| 602 |
+
exp = Series(np.arange(1.0, 6.0), name=0.5)
|
| 603 |
+
tm.assert_series_equal(res, exp)
|
| 604 |
+
|
| 605 |
+
res = df.quantile(
|
| 606 |
+
[0.5, 0.75], axis=1, interpolation=interpolation, method=method
|
| 607 |
+
)
|
| 608 |
+
exp = DataFrame([np.arange(1.0, 6.0)] * 2, index=[0.5, 0.75])
|
| 609 |
+
if interpolation == "nearest":
|
| 610 |
+
exp.iloc[1, -1] = np.nan
|
| 611 |
+
tm.assert_frame_equal(res, exp)
|
| 612 |
+
|
| 613 |
+
# full-nan column
|
| 614 |
+
df["b"] = np.nan
|
| 615 |
+
|
| 616 |
+
res = df.quantile(0.5, interpolation=interpolation, method=method)
|
| 617 |
+
exp = Series([3.0, np.nan], index=["a", "b"], name=0.5)
|
| 618 |
+
tm.assert_series_equal(res, exp)
|
| 619 |
+
|
| 620 |
+
res = df.quantile([0.5, 0.75], interpolation=interpolation, method=method)
|
| 621 |
+
exp = DataFrame({"a": [3.0, 4.0], "b": [np.nan, np.nan]}, index=[0.5, 0.75])
|
| 622 |
+
tm.assert_frame_equal(res, exp)
|
| 623 |
+
|
| 624 |
+
def test_quantile_nat(self, interp_method, request, using_array_manager, unit):
|
| 625 |
+
interpolation, method = interp_method
|
| 626 |
+
if method == "table" and using_array_manager:
|
| 627 |
+
request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))
|
| 628 |
+
# full NaT column
|
| 629 |
+
df = DataFrame({"a": [pd.NaT, pd.NaT, pd.NaT]}, dtype=f"M8[{unit}]")
|
| 630 |
+
|
| 631 |
+
res = df.quantile(
|
| 632 |
+
0.5, numeric_only=False, interpolation=interpolation, method=method
|
| 633 |
+
)
|
| 634 |
+
exp = Series([pd.NaT], index=["a"], name=0.5, dtype=f"M8[{unit}]")
|
| 635 |
+
tm.assert_series_equal(res, exp)
|
| 636 |
+
|
| 637 |
+
res = df.quantile(
|
| 638 |
+
[0.5], numeric_only=False, interpolation=interpolation, method=method
|
| 639 |
+
)
|
| 640 |
+
exp = DataFrame({"a": [pd.NaT]}, index=[0.5], dtype=f"M8[{unit}]")
|
| 641 |
+
tm.assert_frame_equal(res, exp)
|
| 642 |
+
|
| 643 |
+
# mixed non-null / full null column
|
| 644 |
+
df = DataFrame(
|
| 645 |
+
{
|
| 646 |
+
"a": [
|
| 647 |
+
Timestamp("2012-01-01"),
|
| 648 |
+
Timestamp("2012-01-02"),
|
| 649 |
+
Timestamp("2012-01-03"),
|
| 650 |
+
],
|
| 651 |
+
"b": [pd.NaT, pd.NaT, pd.NaT],
|
| 652 |
+
},
|
| 653 |
+
dtype=f"M8[{unit}]",
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
res = df.quantile(
|
| 657 |
+
0.5, numeric_only=False, interpolation=interpolation, method=method
|
| 658 |
+
)
|
| 659 |
+
exp = Series(
|
| 660 |
+
[Timestamp("2012-01-02"), pd.NaT],
|
| 661 |
+
index=["a", "b"],
|
| 662 |
+
name=0.5,
|
| 663 |
+
dtype=f"M8[{unit}]",
|
| 664 |
+
)
|
| 665 |
+
tm.assert_series_equal(res, exp)
|
| 666 |
+
|
| 667 |
+
res = df.quantile(
|
| 668 |
+
[0.5], numeric_only=False, interpolation=interpolation, method=method
|
| 669 |
+
)
|
| 670 |
+
exp = DataFrame(
|
| 671 |
+
[[Timestamp("2012-01-02"), pd.NaT]],
|
| 672 |
+
index=[0.5],
|
| 673 |
+
columns=["a", "b"],
|
| 674 |
+
dtype=f"M8[{unit}]",
|
| 675 |
+
)
|
| 676 |
+
tm.assert_frame_equal(res, exp)
|
| 677 |
+
|
| 678 |
+
def test_quantile_empty_no_rows_floats(self, interp_method):
|
| 679 |
+
interpolation, method = interp_method
|
| 680 |
+
|
| 681 |
+
df = DataFrame(columns=["a", "b"], dtype="float64")
|
| 682 |
+
|
| 683 |
+
res = df.quantile(0.5, interpolation=interpolation, method=method)
|
| 684 |
+
exp = Series([np.nan, np.nan], index=["a", "b"], name=0.5)
|
| 685 |
+
tm.assert_series_equal(res, exp)
|
| 686 |
+
|
| 687 |
+
res = df.quantile([0.5], interpolation=interpolation, method=method)
|
| 688 |
+
exp = DataFrame([[np.nan, np.nan]], columns=["a", "b"], index=[0.5])
|
| 689 |
+
tm.assert_frame_equal(res, exp)
|
| 690 |
+
|
| 691 |
+
res = df.quantile(0.5, axis=1, interpolation=interpolation, method=method)
|
| 692 |
+
exp = Series([], index=[], dtype="float64", name=0.5)
|
| 693 |
+
tm.assert_series_equal(res, exp)
|
| 694 |
+
|
| 695 |
+
res = df.quantile([0.5], axis=1, interpolation=interpolation, method=method)
|
| 696 |
+
exp = DataFrame(columns=[], index=[0.5])
|
| 697 |
+
tm.assert_frame_equal(res, exp)
|
| 698 |
+
|
| 699 |
+
def test_quantile_empty_no_rows_ints(self, interp_method):
|
| 700 |
+
interpolation, method = interp_method
|
| 701 |
+
df = DataFrame(columns=["a", "b"], dtype="int64")
|
| 702 |
+
|
| 703 |
+
res = df.quantile(0.5, interpolation=interpolation, method=method)
|
| 704 |
+
exp = Series([np.nan, np.nan], index=["a", "b"], name=0.5)
|
| 705 |
+
tm.assert_series_equal(res, exp)
|
| 706 |
+
|
| 707 |
+
def test_quantile_empty_no_rows_dt64(self, interp_method):
|
| 708 |
+
interpolation, method = interp_method
|
| 709 |
+
# datetimes
|
| 710 |
+
df = DataFrame(columns=["a", "b"], dtype="datetime64[ns]")
|
| 711 |
+
|
| 712 |
+
res = df.quantile(
|
| 713 |
+
0.5, numeric_only=False, interpolation=interpolation, method=method
|
| 714 |
+
)
|
| 715 |
+
exp = Series(
|
| 716 |
+
[pd.NaT, pd.NaT], index=["a", "b"], dtype="datetime64[ns]", name=0.5
|
| 717 |
+
)
|
| 718 |
+
tm.assert_series_equal(res, exp)
|
| 719 |
+
|
| 720 |
+
# Mixed dt64/dt64tz
|
| 721 |
+
df["a"] = df["a"].dt.tz_localize("US/Central")
|
| 722 |
+
res = df.quantile(
|
| 723 |
+
0.5, numeric_only=False, interpolation=interpolation, method=method
|
| 724 |
+
)
|
| 725 |
+
exp = exp.astype(object)
|
| 726 |
+
if interpolation == "nearest":
|
| 727 |
+
# GH#18463 TODO: would we prefer NaTs here?
|
| 728 |
+
msg = "The 'downcast' keyword in fillna is deprecated"
|
| 729 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 730 |
+
exp = exp.fillna(np.nan, downcast=False)
|
| 731 |
+
tm.assert_series_equal(res, exp)
|
| 732 |
+
|
| 733 |
+
# both dt64tz
|
| 734 |
+
df["b"] = df["b"].dt.tz_localize("US/Central")
|
| 735 |
+
res = df.quantile(
|
| 736 |
+
0.5, numeric_only=False, interpolation=interpolation, method=method
|
| 737 |
+
)
|
| 738 |
+
exp = exp.astype(df["b"].dtype)
|
| 739 |
+
tm.assert_series_equal(res, exp)
|
| 740 |
+
|
| 741 |
+
def test_quantile_empty_no_columns(self, interp_method):
|
| 742 |
+
# GH#23925 _get_numeric_data may drop all columns
|
| 743 |
+
interpolation, method = interp_method
|
| 744 |
+
df = DataFrame(pd.date_range("1/1/18", periods=5))
|
| 745 |
+
df.columns.name = "captain tightpants"
|
| 746 |
+
result = df.quantile(
|
| 747 |
+
0.5, numeric_only=True, interpolation=interpolation, method=method
|
| 748 |
+
)
|
| 749 |
+
expected = Series([], index=[], name=0.5, dtype=np.float64)
|
| 750 |
+
expected.index.name = "captain tightpants"
|
| 751 |
+
tm.assert_series_equal(result, expected)
|
| 752 |
+
|
| 753 |
+
result = df.quantile(
|
| 754 |
+
[0.5], numeric_only=True, interpolation=interpolation, method=method
|
| 755 |
+
)
|
| 756 |
+
expected = DataFrame([], index=[0.5], columns=[])
|
| 757 |
+
expected.columns.name = "captain tightpants"
|
| 758 |
+
tm.assert_frame_equal(result, expected)
|
| 759 |
+
|
| 760 |
+
def test_quantile_item_cache(
|
| 761 |
+
self, using_array_manager, interp_method, using_copy_on_write
|
| 762 |
+
):
|
| 763 |
+
# previous behavior incorrect retained an invalid _item_cache entry
|
| 764 |
+
interpolation, method = interp_method
|
| 765 |
+
df = DataFrame(
|
| 766 |
+
np.random.default_rng(2).standard_normal((4, 3)), columns=["A", "B", "C"]
|
| 767 |
+
)
|
| 768 |
+
df["D"] = df["A"] * 2
|
| 769 |
+
ser = df["A"]
|
| 770 |
+
if not using_array_manager:
|
| 771 |
+
assert len(df._mgr.blocks) == 2
|
| 772 |
+
|
| 773 |
+
df.quantile(numeric_only=False, interpolation=interpolation, method=method)
|
| 774 |
+
|
| 775 |
+
if using_copy_on_write:
|
| 776 |
+
ser.iloc[0] = 99
|
| 777 |
+
assert df.iloc[0, 0] == df["A"][0]
|
| 778 |
+
assert df.iloc[0, 0] != 99
|
| 779 |
+
else:
|
| 780 |
+
ser.values[0] = 99
|
| 781 |
+
assert df.iloc[0, 0] == df["A"][0]
|
| 782 |
+
assert df.iloc[0, 0] == 99
|
| 783 |
+
|
| 784 |
+
def test_invalid_method(self):
|
| 785 |
+
with pytest.raises(ValueError, match="Invalid method: foo"):
|
| 786 |
+
DataFrame(range(1)).quantile(0.5, method="foo")
|
| 787 |
+
|
| 788 |
+
def test_table_invalid_interpolation(self):
|
| 789 |
+
with pytest.raises(ValueError, match="Invalid interpolation: foo"):
|
| 790 |
+
DataFrame(range(1)).quantile(0.5, method="table", interpolation="foo")
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
class TestQuantileExtensionDtype:
|
| 794 |
+
# TODO: tests for axis=1?
|
| 795 |
+
# TODO: empty case?
|
| 796 |
+
|
| 797 |
+
@pytest.fixture(
|
| 798 |
+
params=[
|
| 799 |
+
pytest.param(
|
| 800 |
+
pd.IntervalIndex.from_breaks(range(10)),
|
| 801 |
+
marks=pytest.mark.xfail(reason="raises when trying to add Intervals"),
|
| 802 |
+
),
|
| 803 |
+
pd.period_range("2016-01-01", periods=9, freq="D"),
|
| 804 |
+
pd.date_range("2016-01-01", periods=9, tz="US/Pacific"),
|
| 805 |
+
pd.timedelta_range("1 Day", periods=9),
|
| 806 |
+
pd.array(np.arange(9), dtype="Int64"),
|
| 807 |
+
pd.array(np.arange(9), dtype="Float64"),
|
| 808 |
+
],
|
| 809 |
+
ids=lambda x: str(x.dtype),
|
| 810 |
+
)
|
| 811 |
+
def index(self, request):
|
| 812 |
+
# NB: not actually an Index object
|
| 813 |
+
idx = request.param
|
| 814 |
+
idx.name = "A"
|
| 815 |
+
return idx
|
| 816 |
+
|
| 817 |
+
@pytest.fixture
|
| 818 |
+
def obj(self, index, frame_or_series):
|
| 819 |
+
# bc index is not always an Index (yet), we need to re-patch .name
|
| 820 |
+
obj = frame_or_series(index).copy()
|
| 821 |
+
|
| 822 |
+
if frame_or_series is Series:
|
| 823 |
+
obj.name = "A"
|
| 824 |
+
else:
|
| 825 |
+
obj.columns = ["A"]
|
| 826 |
+
return obj
|
| 827 |
+
|
| 828 |
+
def compute_quantile(self, obj, qs):
|
| 829 |
+
if isinstance(obj, Series):
|
| 830 |
+
result = obj.quantile(qs)
|
| 831 |
+
else:
|
| 832 |
+
result = obj.quantile(qs, numeric_only=False)
|
| 833 |
+
return result
|
| 834 |
+
|
| 835 |
+
def test_quantile_ea(self, request, obj, index):
|
| 836 |
+
# result should be invariant to shuffling
|
| 837 |
+
indexer = np.arange(len(index), dtype=np.intp)
|
| 838 |
+
np.random.default_rng(2).shuffle(indexer)
|
| 839 |
+
obj = obj.iloc[indexer]
|
| 840 |
+
|
| 841 |
+
qs = [0.5, 0, 1]
|
| 842 |
+
result = self.compute_quantile(obj, qs)
|
| 843 |
+
|
| 844 |
+
exp_dtype = index.dtype
|
| 845 |
+
if index.dtype == "Int64":
|
| 846 |
+
# match non-nullable casting behavior
|
| 847 |
+
exp_dtype = "Float64"
|
| 848 |
+
|
| 849 |
+
# expected here assumes len(index) == 9
|
| 850 |
+
expected = Series(
|
| 851 |
+
[index[4], index[0], index[-1]], dtype=exp_dtype, index=qs, name="A"
|
| 852 |
+
)
|
| 853 |
+
expected = type(obj)(expected)
|
| 854 |
+
|
| 855 |
+
tm.assert_equal(result, expected)
|
| 856 |
+
|
| 857 |
+
def test_quantile_ea_with_na(self, obj, index):
|
| 858 |
+
obj.iloc[0] = index._na_value
|
| 859 |
+
obj.iloc[-1] = index._na_value
|
| 860 |
+
|
| 861 |
+
# result should be invariant to shuffling
|
| 862 |
+
indexer = np.arange(len(index), dtype=np.intp)
|
| 863 |
+
np.random.default_rng(2).shuffle(indexer)
|
| 864 |
+
obj = obj.iloc[indexer]
|
| 865 |
+
|
| 866 |
+
qs = [0.5, 0, 1]
|
| 867 |
+
result = self.compute_quantile(obj, qs)
|
| 868 |
+
|
| 869 |
+
# expected here assumes len(index) == 9
|
| 870 |
+
expected = Series(
|
| 871 |
+
[index[4], index[1], index[-2]], dtype=index.dtype, index=qs, name="A"
|
| 872 |
+
)
|
| 873 |
+
expected = type(obj)(expected)
|
| 874 |
+
tm.assert_equal(result, expected)
|
| 875 |
+
|
| 876 |
+
def test_quantile_ea_all_na(self, request, obj, index):
|
| 877 |
+
obj.iloc[:] = index._na_value
|
| 878 |
+
# Check dtypes were preserved; this was once a problem see GH#39763
|
| 879 |
+
assert np.all(obj.dtypes == index.dtype)
|
| 880 |
+
|
| 881 |
+
# result should be invariant to shuffling
|
| 882 |
+
indexer = np.arange(len(index), dtype=np.intp)
|
| 883 |
+
np.random.default_rng(2).shuffle(indexer)
|
| 884 |
+
obj = obj.iloc[indexer]
|
| 885 |
+
|
| 886 |
+
qs = [0.5, 0, 1]
|
| 887 |
+
result = self.compute_quantile(obj, qs)
|
| 888 |
+
|
| 889 |
+
expected = index.take([-1, -1, -1], allow_fill=True, fill_value=index._na_value)
|
| 890 |
+
expected = Series(expected, index=qs, name="A")
|
| 891 |
+
expected = type(obj)(expected)
|
| 892 |
+
tm.assert_equal(result, expected)
|
| 893 |
+
|
| 894 |
+
def test_quantile_ea_scalar(self, request, obj, index):
|
| 895 |
+
# scalar qs
|
| 896 |
+
|
| 897 |
+
# result should be invariant to shuffling
|
| 898 |
+
indexer = np.arange(len(index), dtype=np.intp)
|
| 899 |
+
np.random.default_rng(2).shuffle(indexer)
|
| 900 |
+
obj = obj.iloc[indexer]
|
| 901 |
+
|
| 902 |
+
qs = 0.5
|
| 903 |
+
result = self.compute_quantile(obj, qs)
|
| 904 |
+
|
| 905 |
+
exp_dtype = index.dtype
|
| 906 |
+
if index.dtype == "Int64":
|
| 907 |
+
exp_dtype = "Float64"
|
| 908 |
+
|
| 909 |
+
expected = Series({"A": index[4]}, dtype=exp_dtype, name=0.5)
|
| 910 |
+
if isinstance(obj, Series):
|
| 911 |
+
expected = expected["A"]
|
| 912 |
+
assert result == expected
|
| 913 |
+
else:
|
| 914 |
+
tm.assert_series_equal(result, expected)
|
| 915 |
+
|
| 916 |
+
@pytest.mark.parametrize(
|
| 917 |
+
"dtype, expected_data, expected_index, axis",
|
| 918 |
+
[
|
| 919 |
+
["float64", [], [], 1],
|
| 920 |
+
["int64", [], [], 1],
|
| 921 |
+
["float64", [np.nan, np.nan], ["a", "b"], 0],
|
| 922 |
+
["int64", [np.nan, np.nan], ["a", "b"], 0],
|
| 923 |
+
],
|
| 924 |
+
)
|
| 925 |
+
def test_empty_numeric(self, dtype, expected_data, expected_index, axis):
|
| 926 |
+
# GH 14564
|
| 927 |
+
df = DataFrame(columns=["a", "b"], dtype=dtype)
|
| 928 |
+
result = df.quantile(0.5, axis=axis)
|
| 929 |
+
expected = Series(
|
| 930 |
+
expected_data, name=0.5, index=Index(expected_index), dtype="float64"
|
| 931 |
+
)
|
| 932 |
+
tm.assert_series_equal(result, expected)
|
| 933 |
+
|
| 934 |
+
@pytest.mark.parametrize(
|
| 935 |
+
"dtype, expected_data, expected_index, axis, expected_dtype",
|
| 936 |
+
[
|
| 937 |
+
["datetime64[ns]", [], [], 1, "datetime64[ns]"],
|
| 938 |
+
["datetime64[ns]", [pd.NaT, pd.NaT], ["a", "b"], 0, "datetime64[ns]"],
|
| 939 |
+
],
|
| 940 |
+
)
|
| 941 |
+
def test_empty_datelike(
|
| 942 |
+
self, dtype, expected_data, expected_index, axis, expected_dtype
|
| 943 |
+
):
|
| 944 |
+
# GH 14564
|
| 945 |
+
df = DataFrame(columns=["a", "b"], dtype=dtype)
|
| 946 |
+
result = df.quantile(0.5, axis=axis, numeric_only=False)
|
| 947 |
+
expected = Series(
|
| 948 |
+
expected_data, name=0.5, index=Index(expected_index), dtype=expected_dtype
|
| 949 |
+
)
|
| 950 |
+
tm.assert_series_equal(result, expected)
|
| 951 |
+
|
| 952 |
+
@pytest.mark.parametrize(
|
| 953 |
+
"expected_data, expected_index, axis",
|
| 954 |
+
[
|
| 955 |
+
[[np.nan, np.nan], range(2), 1],
|
| 956 |
+
[[], [], 0],
|
| 957 |
+
],
|
| 958 |
+
)
|
| 959 |
+
def test_datelike_numeric_only(self, expected_data, expected_index, axis):
|
| 960 |
+
# GH 14564
|
| 961 |
+
df = DataFrame(
|
| 962 |
+
{
|
| 963 |
+
"a": pd.to_datetime(["2010", "2011"]),
|
| 964 |
+
"b": [0, 5],
|
| 965 |
+
"c": pd.to_datetime(["2011", "2012"]),
|
| 966 |
+
}
|
| 967 |
+
)
|
| 968 |
+
result = df[["a", "c"]].quantile(0.5, axis=axis, numeric_only=True)
|
| 969 |
+
expected = Series(
|
| 970 |
+
expected_data, name=0.5, index=Index(expected_index), dtype=np.float64
|
| 971 |
+
)
|
| 972 |
+
tm.assert_series_equal(result, expected)
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_reset_index.py
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from itertools import product
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from pandas.core.dtypes.common import (
|
| 8 |
+
is_float_dtype,
|
| 9 |
+
is_integer_dtype,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from pandas import (
|
| 14 |
+
Categorical,
|
| 15 |
+
CategoricalIndex,
|
| 16 |
+
DataFrame,
|
| 17 |
+
Index,
|
| 18 |
+
Interval,
|
| 19 |
+
IntervalIndex,
|
| 20 |
+
MultiIndex,
|
| 21 |
+
RangeIndex,
|
| 22 |
+
Series,
|
| 23 |
+
Timestamp,
|
| 24 |
+
cut,
|
| 25 |
+
date_range,
|
| 26 |
+
)
|
| 27 |
+
import pandas._testing as tm
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.fixture()
|
| 31 |
+
def multiindex_df():
|
| 32 |
+
levels = [["A", ""], ["B", "b"]]
|
| 33 |
+
return DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TestResetIndex:
|
| 37 |
+
def test_reset_index_empty_rangeindex(self):
|
| 38 |
+
# GH#45230
|
| 39 |
+
df = DataFrame(
|
| 40 |
+
columns=["brand"], dtype=np.int64, index=RangeIndex(0, 0, 1, name="foo")
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
df2 = df.set_index([df.index, "brand"])
|
| 44 |
+
|
| 45 |
+
result = df2.reset_index([1], drop=True)
|
| 46 |
+
tm.assert_frame_equal(result, df[[]], check_index_type=True)
|
| 47 |
+
|
| 48 |
+
def test_set_reset(self):
|
| 49 |
+
idx = Index([2**63, 2**63 + 5, 2**63 + 10], name="foo")
|
| 50 |
+
|
| 51 |
+
# set/reset
|
| 52 |
+
df = DataFrame({"A": [0, 1, 2]}, index=idx)
|
| 53 |
+
result = df.reset_index()
|
| 54 |
+
assert result["foo"].dtype == np.dtype("uint64")
|
| 55 |
+
|
| 56 |
+
df = result.set_index("foo")
|
| 57 |
+
tm.assert_index_equal(df.index, idx)
|
| 58 |
+
|
| 59 |
+
def test_set_index_reset_index_dt64tz(self):
|
| 60 |
+
idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo")
|
| 61 |
+
|
| 62 |
+
# set/reset
|
| 63 |
+
df = DataFrame({"A": [0, 1, 2]}, index=idx)
|
| 64 |
+
result = df.reset_index()
|
| 65 |
+
assert result["foo"].dtype == "datetime64[ns, US/Eastern]"
|
| 66 |
+
|
| 67 |
+
df = result.set_index("foo")
|
| 68 |
+
tm.assert_index_equal(df.index, idx)
|
| 69 |
+
|
| 70 |
+
def test_reset_index_tz(self, tz_aware_fixture):
|
| 71 |
+
# GH 3950
|
| 72 |
+
# reset_index with single level
|
| 73 |
+
tz = tz_aware_fixture
|
| 74 |
+
idx = date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx")
|
| 75 |
+
df = DataFrame({"a": range(5), "b": ["A", "B", "C", "D", "E"]}, index=idx)
|
| 76 |
+
|
| 77 |
+
expected = DataFrame(
|
| 78 |
+
{
|
| 79 |
+
"idx": idx,
|
| 80 |
+
"a": range(5),
|
| 81 |
+
"b": ["A", "B", "C", "D", "E"],
|
| 82 |
+
},
|
| 83 |
+
columns=["idx", "a", "b"],
|
| 84 |
+
)
|
| 85 |
+
result = df.reset_index()
|
| 86 |
+
tm.assert_frame_equal(result, expected)
|
| 87 |
+
|
| 88 |
+
@pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"])
|
| 89 |
+
def test_frame_reset_index_tzaware_index(self, tz):
|
| 90 |
+
dr = date_range("2012-06-02", periods=10, tz=tz)
|
| 91 |
+
df = DataFrame(np.random.default_rng(2).standard_normal(len(dr)), dr)
|
| 92 |
+
roundtripped = df.reset_index().set_index("index")
|
| 93 |
+
xp = df.index.tz
|
| 94 |
+
rs = roundtripped.index.tz
|
| 95 |
+
assert xp == rs
|
| 96 |
+
|
| 97 |
+
def test_reset_index_with_intervals(self):
|
| 98 |
+
idx = IntervalIndex.from_breaks(np.arange(11), name="x")
|
| 99 |
+
original = DataFrame({"x": idx, "y": np.arange(10)})[["x", "y"]]
|
| 100 |
+
|
| 101 |
+
result = original.set_index("x")
|
| 102 |
+
expected = DataFrame({"y": np.arange(10)}, index=idx)
|
| 103 |
+
tm.assert_frame_equal(result, expected)
|
| 104 |
+
|
| 105 |
+
result2 = result.reset_index()
|
| 106 |
+
tm.assert_frame_equal(result2, original)
|
| 107 |
+
|
| 108 |
+
def test_reset_index(self, float_frame):
|
| 109 |
+
stacked = float_frame.stack(future_stack=True)[::2]
|
| 110 |
+
stacked = DataFrame({"foo": stacked, "bar": stacked})
|
| 111 |
+
|
| 112 |
+
names = ["first", "second"]
|
| 113 |
+
stacked.index.names = names
|
| 114 |
+
deleveled = stacked.reset_index()
|
| 115 |
+
for i, (lev, level_codes) in enumerate(
|
| 116 |
+
zip(stacked.index.levels, stacked.index.codes)
|
| 117 |
+
):
|
| 118 |
+
values = lev.take(level_codes)
|
| 119 |
+
name = names[i]
|
| 120 |
+
tm.assert_index_equal(values, Index(deleveled[name]))
|
| 121 |
+
|
| 122 |
+
stacked.index.names = [None, None]
|
| 123 |
+
deleveled2 = stacked.reset_index()
|
| 124 |
+
tm.assert_series_equal(
|
| 125 |
+
deleveled["first"], deleveled2["level_0"], check_names=False
|
| 126 |
+
)
|
| 127 |
+
tm.assert_series_equal(
|
| 128 |
+
deleveled["second"], deleveled2["level_1"], check_names=False
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# default name assigned
|
| 132 |
+
rdf = float_frame.reset_index()
|
| 133 |
+
exp = Series(float_frame.index.values, name="index")
|
| 134 |
+
tm.assert_series_equal(rdf["index"], exp)
|
| 135 |
+
|
| 136 |
+
# default name assigned, corner case
|
| 137 |
+
df = float_frame.copy()
|
| 138 |
+
df["index"] = "foo"
|
| 139 |
+
rdf = df.reset_index()
|
| 140 |
+
exp = Series(float_frame.index.values, name="level_0")
|
| 141 |
+
tm.assert_series_equal(rdf["level_0"], exp)
|
| 142 |
+
|
| 143 |
+
# but this is ok
|
| 144 |
+
float_frame.index.name = "index"
|
| 145 |
+
deleveled = float_frame.reset_index()
|
| 146 |
+
tm.assert_series_equal(deleveled["index"], Series(float_frame.index))
|
| 147 |
+
tm.assert_index_equal(deleveled.index, Index(range(len(deleveled))), exact=True)
|
| 148 |
+
|
| 149 |
+
# preserve column names
|
| 150 |
+
float_frame.columns.name = "columns"
|
| 151 |
+
reset = float_frame.reset_index()
|
| 152 |
+
assert reset.columns.name == "columns"
|
| 153 |
+
|
| 154 |
+
# only remove certain columns
|
| 155 |
+
df = float_frame.reset_index().set_index(["index", "A", "B"])
|
| 156 |
+
rs = df.reset_index(["A", "B"])
|
| 157 |
+
|
| 158 |
+
tm.assert_frame_equal(rs, float_frame)
|
| 159 |
+
|
| 160 |
+
rs = df.reset_index(["index", "A", "B"])
|
| 161 |
+
tm.assert_frame_equal(rs, float_frame.reset_index())
|
| 162 |
+
|
| 163 |
+
rs = df.reset_index(["index", "A", "B"])
|
| 164 |
+
tm.assert_frame_equal(rs, float_frame.reset_index())
|
| 165 |
+
|
| 166 |
+
rs = df.reset_index("A")
|
| 167 |
+
xp = float_frame.reset_index().set_index(["index", "B"])
|
| 168 |
+
tm.assert_frame_equal(rs, xp)
|
| 169 |
+
|
| 170 |
+
# test resetting in place
|
| 171 |
+
df = float_frame.copy()
|
| 172 |
+
reset = float_frame.reset_index()
|
| 173 |
+
return_value = df.reset_index(inplace=True)
|
| 174 |
+
assert return_value is None
|
| 175 |
+
tm.assert_frame_equal(df, reset)
|
| 176 |
+
|
| 177 |
+
df = float_frame.reset_index().set_index(["index", "A", "B"])
|
| 178 |
+
rs = df.reset_index("A", drop=True)
|
| 179 |
+
xp = float_frame.copy()
|
| 180 |
+
del xp["A"]
|
| 181 |
+
xp = xp.set_index(["B"], append=True)
|
| 182 |
+
tm.assert_frame_equal(rs, xp)
|
| 183 |
+
|
| 184 |
+
def test_reset_index_name(self):
|
| 185 |
+
df = DataFrame(
|
| 186 |
+
[[1, 2, 3, 4], [5, 6, 7, 8]],
|
| 187 |
+
columns=["A", "B", "C", "D"],
|
| 188 |
+
index=Index(range(2), name="x"),
|
| 189 |
+
)
|
| 190 |
+
assert df.reset_index().index.name is None
|
| 191 |
+
assert df.reset_index(drop=True).index.name is None
|
| 192 |
+
return_value = df.reset_index(inplace=True)
|
| 193 |
+
assert return_value is None
|
| 194 |
+
assert df.index.name is None
|
| 195 |
+
|
| 196 |
+
@pytest.mark.parametrize("levels", [["A", "B"], [0, 1]])
|
| 197 |
+
def test_reset_index_level(self, levels):
|
| 198 |
+
df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "C", "D"])
|
| 199 |
+
|
| 200 |
+
# With MultiIndex
|
| 201 |
+
result = df.set_index(["A", "B"]).reset_index(level=levels[0])
|
| 202 |
+
tm.assert_frame_equal(result, df.set_index("B"))
|
| 203 |
+
|
| 204 |
+
result = df.set_index(["A", "B"]).reset_index(level=levels[:1])
|
| 205 |
+
tm.assert_frame_equal(result, df.set_index("B"))
|
| 206 |
+
|
| 207 |
+
result = df.set_index(["A", "B"]).reset_index(level=levels)
|
| 208 |
+
tm.assert_frame_equal(result, df)
|
| 209 |
+
|
| 210 |
+
result = df.set_index(["A", "B"]).reset_index(level=levels, drop=True)
|
| 211 |
+
tm.assert_frame_equal(result, df[["C", "D"]])
|
| 212 |
+
|
| 213 |
+
# With single-level Index (GH 16263)
|
| 214 |
+
result = df.set_index("A").reset_index(level=levels[0])
|
| 215 |
+
tm.assert_frame_equal(result, df)
|
| 216 |
+
|
| 217 |
+
result = df.set_index("A").reset_index(level=levels[:1])
|
| 218 |
+
tm.assert_frame_equal(result, df)
|
| 219 |
+
|
| 220 |
+
result = df.set_index(["A"]).reset_index(level=levels[0], drop=True)
|
| 221 |
+
tm.assert_frame_equal(result, df[["B", "C", "D"]])
|
| 222 |
+
|
| 223 |
+
@pytest.mark.parametrize("idx_lev", [["A", "B"], ["A"]])
|
| 224 |
+
def test_reset_index_level_missing(self, idx_lev):
|
| 225 |
+
# Missing levels - for both MultiIndex and single-level Index:
|
| 226 |
+
df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "C", "D"])
|
| 227 |
+
|
| 228 |
+
with pytest.raises(KeyError, match=r"(L|l)evel \(?E\)?"):
|
| 229 |
+
df.set_index(idx_lev).reset_index(level=["A", "E"])
|
| 230 |
+
with pytest.raises(IndexError, match="Too many levels"):
|
| 231 |
+
df.set_index(idx_lev).reset_index(level=[0, 1, 2])
|
| 232 |
+
|
| 233 |
+
def test_reset_index_right_dtype(self):
|
| 234 |
+
time = np.arange(0.0, 10, np.sqrt(2) / 2)
|
| 235 |
+
s1 = Series(
|
| 236 |
+
(9.81 * time**2) / 2, index=Index(time, name="time"), name="speed"
|
| 237 |
+
)
|
| 238 |
+
df = DataFrame(s1)
|
| 239 |
+
|
| 240 |
+
reset = s1.reset_index()
|
| 241 |
+
assert reset["time"].dtype == np.float64
|
| 242 |
+
|
| 243 |
+
reset = df.reset_index()
|
| 244 |
+
assert reset["time"].dtype == np.float64
|
| 245 |
+
|
| 246 |
+
def test_reset_index_multiindex_col(self):
|
| 247 |
+
vals = np.random.default_rng(2).standard_normal((3, 3)).astype(object)
|
| 248 |
+
idx = ["x", "y", "z"]
|
| 249 |
+
full = np.hstack(([[x] for x in idx], vals))
|
| 250 |
+
df = DataFrame(
|
| 251 |
+
vals,
|
| 252 |
+
Index(idx, name="a"),
|
| 253 |
+
columns=[["b", "b", "c"], ["mean", "median", "mean"]],
|
| 254 |
+
)
|
| 255 |
+
rs = df.reset_index()
|
| 256 |
+
xp = DataFrame(
|
| 257 |
+
full, columns=[["a", "b", "b", "c"], ["", "mean", "median", "mean"]]
|
| 258 |
+
)
|
| 259 |
+
tm.assert_frame_equal(rs, xp)
|
| 260 |
+
|
| 261 |
+
rs = df.reset_index(col_fill=None)
|
| 262 |
+
xp = DataFrame(
|
| 263 |
+
full, columns=[["a", "b", "b", "c"], ["a", "mean", "median", "mean"]]
|
| 264 |
+
)
|
| 265 |
+
tm.assert_frame_equal(rs, xp)
|
| 266 |
+
|
| 267 |
+
rs = df.reset_index(col_level=1, col_fill="blah")
|
| 268 |
+
xp = DataFrame(
|
| 269 |
+
full, columns=[["blah", "b", "b", "c"], ["a", "mean", "median", "mean"]]
|
| 270 |
+
)
|
| 271 |
+
tm.assert_frame_equal(rs, xp)
|
| 272 |
+
|
| 273 |
+
df = DataFrame(
|
| 274 |
+
vals,
|
| 275 |
+
MultiIndex.from_arrays([[0, 1, 2], ["x", "y", "z"]], names=["d", "a"]),
|
| 276 |
+
columns=[["b", "b", "c"], ["mean", "median", "mean"]],
|
| 277 |
+
)
|
| 278 |
+
rs = df.reset_index("a")
|
| 279 |
+
xp = DataFrame(
|
| 280 |
+
full,
|
| 281 |
+
Index([0, 1, 2], name="d"),
|
| 282 |
+
columns=[["a", "b", "b", "c"], ["", "mean", "median", "mean"]],
|
| 283 |
+
)
|
| 284 |
+
tm.assert_frame_equal(rs, xp)
|
| 285 |
+
|
| 286 |
+
rs = df.reset_index("a", col_fill=None)
|
| 287 |
+
xp = DataFrame(
|
| 288 |
+
full,
|
| 289 |
+
Index(range(3), name="d"),
|
| 290 |
+
columns=[["a", "b", "b", "c"], ["a", "mean", "median", "mean"]],
|
| 291 |
+
)
|
| 292 |
+
tm.assert_frame_equal(rs, xp)
|
| 293 |
+
|
| 294 |
+
rs = df.reset_index("a", col_fill="blah", col_level=1)
|
| 295 |
+
xp = DataFrame(
|
| 296 |
+
full,
|
| 297 |
+
Index(range(3), name="d"),
|
| 298 |
+
columns=[["blah", "b", "b", "c"], ["a", "mean", "median", "mean"]],
|
| 299 |
+
)
|
| 300 |
+
tm.assert_frame_equal(rs, xp)
|
| 301 |
+
|
| 302 |
+
def test_reset_index_multiindex_nan(self):
|
| 303 |
+
# GH#6322, testing reset_index on MultiIndexes
|
| 304 |
+
# when we have a nan or all nan
|
| 305 |
+
df = DataFrame(
|
| 306 |
+
{
|
| 307 |
+
"A": ["a", "b", "c"],
|
| 308 |
+
"B": [0, 1, np.nan],
|
| 309 |
+
"C": np.random.default_rng(2).random(3),
|
| 310 |
+
}
|
| 311 |
+
)
|
| 312 |
+
rs = df.set_index(["A", "B"]).reset_index()
|
| 313 |
+
tm.assert_frame_equal(rs, df)
|
| 314 |
+
|
| 315 |
+
df = DataFrame(
|
| 316 |
+
{
|
| 317 |
+
"A": [np.nan, "b", "c"],
|
| 318 |
+
"B": [0, 1, 2],
|
| 319 |
+
"C": np.random.default_rng(2).random(3),
|
| 320 |
+
}
|
| 321 |
+
)
|
| 322 |
+
rs = df.set_index(["A", "B"]).reset_index()
|
| 323 |
+
tm.assert_frame_equal(rs, df)
|
| 324 |
+
|
| 325 |
+
df = DataFrame({"A": ["a", "b", "c"], "B": [0, 1, 2], "C": [np.nan, 1.1, 2.2]})
|
| 326 |
+
rs = df.set_index(["A", "B"]).reset_index()
|
| 327 |
+
tm.assert_frame_equal(rs, df)
|
| 328 |
+
|
| 329 |
+
df = DataFrame(
|
| 330 |
+
{
|
| 331 |
+
"A": ["a", "b", "c"],
|
| 332 |
+
"B": [np.nan, np.nan, np.nan],
|
| 333 |
+
"C": np.random.default_rng(2).random(3),
|
| 334 |
+
}
|
| 335 |
+
)
|
| 336 |
+
rs = df.set_index(["A", "B"]).reset_index()
|
| 337 |
+
tm.assert_frame_equal(rs, df)
|
| 338 |
+
|
| 339 |
+
@pytest.mark.parametrize(
|
| 340 |
+
"name",
|
| 341 |
+
[
|
| 342 |
+
None,
|
| 343 |
+
"foo",
|
| 344 |
+
2,
|
| 345 |
+
3.0,
|
| 346 |
+
pd.Timedelta(6),
|
| 347 |
+
Timestamp("2012-12-30", tz="UTC"),
|
| 348 |
+
"2012-12-31",
|
| 349 |
+
],
|
| 350 |
+
)
|
| 351 |
+
def test_reset_index_with_datetimeindex_cols(self, name):
|
| 352 |
+
# GH#5818
|
| 353 |
+
df = DataFrame(
|
| 354 |
+
[[1, 2], [3, 4]],
|
| 355 |
+
columns=date_range("1/1/2013", "1/2/2013"),
|
| 356 |
+
index=["A", "B"],
|
| 357 |
+
)
|
| 358 |
+
df.index.name = name
|
| 359 |
+
|
| 360 |
+
result = df.reset_index()
|
| 361 |
+
|
| 362 |
+
item = name if name is not None else "index"
|
| 363 |
+
columns = Index([item, datetime(2013, 1, 1), datetime(2013, 1, 2)])
|
| 364 |
+
if isinstance(item, str) and item == "2012-12-31":
|
| 365 |
+
columns = columns.astype("datetime64[ns]")
|
| 366 |
+
else:
|
| 367 |
+
assert columns.dtype == object
|
| 368 |
+
|
| 369 |
+
expected = DataFrame(
|
| 370 |
+
[["A", 1, 2], ["B", 3, 4]],
|
| 371 |
+
columns=columns,
|
| 372 |
+
)
|
| 373 |
+
tm.assert_frame_equal(result, expected)
|
| 374 |
+
|
| 375 |
+
def test_reset_index_range(self):
|
| 376 |
+
# GH#12071
|
| 377 |
+
df = DataFrame([[0, 0], [1, 1]], columns=["A", "B"], index=RangeIndex(stop=2))
|
| 378 |
+
result = df.reset_index()
|
| 379 |
+
assert isinstance(result.index, RangeIndex)
|
| 380 |
+
expected = DataFrame(
|
| 381 |
+
[[0, 0, 0], [1, 1, 1]],
|
| 382 |
+
columns=["index", "A", "B"],
|
| 383 |
+
index=RangeIndex(stop=2),
|
| 384 |
+
)
|
| 385 |
+
tm.assert_frame_equal(result, expected)
|
| 386 |
+
|
| 387 |
+
def test_reset_index_multiindex_columns(self, multiindex_df):
|
| 388 |
+
result = multiindex_df[["B"]].rename_axis("A").reset_index()
|
| 389 |
+
tm.assert_frame_equal(result, multiindex_df)
|
| 390 |
+
|
| 391 |
+
# GH#16120: already existing column
|
| 392 |
+
msg = r"cannot insert \('A', ''\), already exists"
|
| 393 |
+
with pytest.raises(ValueError, match=msg):
|
| 394 |
+
multiindex_df.rename_axis("A").reset_index()
|
| 395 |
+
|
| 396 |
+
# GH#16164: multiindex (tuple) full key
|
| 397 |
+
result = multiindex_df.set_index([("A", "")]).reset_index()
|
| 398 |
+
tm.assert_frame_equal(result, multiindex_df)
|
| 399 |
+
|
| 400 |
+
# with additional (unnamed) index level
|
| 401 |
+
idx_col = DataFrame(
|
| 402 |
+
[[0], [1]], columns=MultiIndex.from_tuples([("level_0", "")])
|
| 403 |
+
)
|
| 404 |
+
expected = pd.concat([idx_col, multiindex_df[[("B", "b"), ("A", "")]]], axis=1)
|
| 405 |
+
result = multiindex_df.set_index([("B", "b")], append=True).reset_index()
|
| 406 |
+
tm.assert_frame_equal(result, expected)
|
| 407 |
+
|
| 408 |
+
# with index name which is a too long tuple...
|
| 409 |
+
msg = "Item must have length equal to number of levels."
|
| 410 |
+
with pytest.raises(ValueError, match=msg):
|
| 411 |
+
multiindex_df.rename_axis([("C", "c", "i")]).reset_index()
|
| 412 |
+
|
| 413 |
+
# or too short...
|
| 414 |
+
levels = [["A", "a", ""], ["B", "b", "i"]]
|
| 415 |
+
df2 = DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels))
|
| 416 |
+
idx_col = DataFrame(
|
| 417 |
+
[[0], [1]], columns=MultiIndex.from_tuples([("C", "c", "ii")])
|
| 418 |
+
)
|
| 419 |
+
expected = pd.concat([idx_col, df2], axis=1)
|
| 420 |
+
result = df2.rename_axis([("C", "c")]).reset_index(col_fill="ii")
|
| 421 |
+
tm.assert_frame_equal(result, expected)
|
| 422 |
+
|
| 423 |
+
# ... which is incompatible with col_fill=None
|
| 424 |
+
with pytest.raises(
|
| 425 |
+
ValueError,
|
| 426 |
+
match=(
|
| 427 |
+
"col_fill=None is incompatible with "
|
| 428 |
+
r"incomplete column name \('C', 'c'\)"
|
| 429 |
+
),
|
| 430 |
+
):
|
| 431 |
+
df2.rename_axis([("C", "c")]).reset_index(col_fill=None)
|
| 432 |
+
|
| 433 |
+
# with col_level != 0
|
| 434 |
+
result = df2.rename_axis([("c", "ii")]).reset_index(col_level=1, col_fill="C")
|
| 435 |
+
tm.assert_frame_equal(result, expected)
|
| 436 |
+
|
| 437 |
+
@pytest.mark.parametrize("flag", [False, True])
|
| 438 |
+
@pytest.mark.parametrize("allow_duplicates", [False, True])
|
| 439 |
+
def test_reset_index_duplicate_columns_allow(
|
| 440 |
+
self, multiindex_df, flag, allow_duplicates
|
| 441 |
+
):
|
| 442 |
+
# GH#44755 reset_index with duplicate column labels
|
| 443 |
+
df = multiindex_df.rename_axis("A")
|
| 444 |
+
df = df.set_flags(allows_duplicate_labels=flag)
|
| 445 |
+
|
| 446 |
+
if flag and allow_duplicates:
|
| 447 |
+
result = df.reset_index(allow_duplicates=allow_duplicates)
|
| 448 |
+
levels = [["A", ""], ["A", ""], ["B", "b"]]
|
| 449 |
+
expected = DataFrame(
|
| 450 |
+
[[0, 0, 2], [1, 1, 3]], columns=MultiIndex.from_tuples(levels)
|
| 451 |
+
)
|
| 452 |
+
tm.assert_frame_equal(result, expected)
|
| 453 |
+
else:
|
| 454 |
+
if not flag and allow_duplicates:
|
| 455 |
+
msg = (
|
| 456 |
+
"Cannot specify 'allow_duplicates=True' when "
|
| 457 |
+
"'self.flags.allows_duplicate_labels' is False"
|
| 458 |
+
)
|
| 459 |
+
else:
|
| 460 |
+
msg = r"cannot insert \('A', ''\), already exists"
|
| 461 |
+
with pytest.raises(ValueError, match=msg):
|
| 462 |
+
df.reset_index(allow_duplicates=allow_duplicates)
|
| 463 |
+
|
| 464 |
+
@pytest.mark.parametrize("flag", [False, True])
|
| 465 |
+
def test_reset_index_duplicate_columns_default(self, multiindex_df, flag):
|
| 466 |
+
df = multiindex_df.rename_axis("A")
|
| 467 |
+
df = df.set_flags(allows_duplicate_labels=flag)
|
| 468 |
+
|
| 469 |
+
msg = r"cannot insert \('A', ''\), already exists"
|
| 470 |
+
with pytest.raises(ValueError, match=msg):
|
| 471 |
+
df.reset_index()
|
| 472 |
+
|
| 473 |
+
@pytest.mark.parametrize("allow_duplicates", ["bad value"])
|
| 474 |
+
def test_reset_index_allow_duplicates_check(self, multiindex_df, allow_duplicates):
|
| 475 |
+
with pytest.raises(ValueError, match="expected type bool"):
|
| 476 |
+
multiindex_df.reset_index(allow_duplicates=allow_duplicates)
|
| 477 |
+
|
| 478 |
+
def test_reset_index_datetime(self, tz_naive_fixture):
|
| 479 |
+
# GH#3950
|
| 480 |
+
tz = tz_naive_fixture
|
| 481 |
+
idx1 = date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx1")
|
| 482 |
+
idx2 = Index(range(5), name="idx2", dtype="int64")
|
| 483 |
+
idx = MultiIndex.from_arrays([idx1, idx2])
|
| 484 |
+
df = DataFrame(
|
| 485 |
+
{"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]},
|
| 486 |
+
index=idx,
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
expected = DataFrame(
|
| 490 |
+
{
|
| 491 |
+
"idx1": idx1,
|
| 492 |
+
"idx2": np.arange(5, dtype="int64"),
|
| 493 |
+
"a": np.arange(5, dtype="int64"),
|
| 494 |
+
"b": ["A", "B", "C", "D", "E"],
|
| 495 |
+
},
|
| 496 |
+
columns=["idx1", "idx2", "a", "b"],
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
tm.assert_frame_equal(df.reset_index(), expected)
|
| 500 |
+
|
| 501 |
+
def test_reset_index_datetime2(self, tz_naive_fixture):
|
| 502 |
+
tz = tz_naive_fixture
|
| 503 |
+
idx1 = date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx1")
|
| 504 |
+
idx2 = Index(range(5), name="idx2", dtype="int64")
|
| 505 |
+
idx3 = date_range(
|
| 506 |
+
"1/1/2012", periods=5, freq="MS", tz="Europe/Paris", name="idx3"
|
| 507 |
+
)
|
| 508 |
+
idx = MultiIndex.from_arrays([idx1, idx2, idx3])
|
| 509 |
+
df = DataFrame(
|
| 510 |
+
{"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]},
|
| 511 |
+
index=idx,
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
expected = DataFrame(
|
| 515 |
+
{
|
| 516 |
+
"idx1": idx1,
|
| 517 |
+
"idx2": np.arange(5, dtype="int64"),
|
| 518 |
+
"idx3": idx3,
|
| 519 |
+
"a": np.arange(5, dtype="int64"),
|
| 520 |
+
"b": ["A", "B", "C", "D", "E"],
|
| 521 |
+
},
|
| 522 |
+
columns=["idx1", "idx2", "idx3", "a", "b"],
|
| 523 |
+
)
|
| 524 |
+
result = df.reset_index()
|
| 525 |
+
tm.assert_frame_equal(result, expected)
|
| 526 |
+
|
| 527 |
+
def test_reset_index_datetime3(self, tz_naive_fixture):
|
| 528 |
+
# GH#7793
|
| 529 |
+
tz = tz_naive_fixture
|
| 530 |
+
dti = date_range("20130101", periods=3, tz=tz)
|
| 531 |
+
idx = MultiIndex.from_product([["a", "b"], dti])
|
| 532 |
+
df = DataFrame(
|
| 533 |
+
np.arange(6, dtype="int64").reshape(6, 1), columns=["a"], index=idx
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
expected = DataFrame(
|
| 537 |
+
{
|
| 538 |
+
"level_0": "a a a b b b".split(),
|
| 539 |
+
"level_1": dti.append(dti),
|
| 540 |
+
"a": np.arange(6, dtype="int64"),
|
| 541 |
+
},
|
| 542 |
+
columns=["level_0", "level_1", "a"],
|
| 543 |
+
)
|
| 544 |
+
result = df.reset_index()
|
| 545 |
+
tm.assert_frame_equal(result, expected)
|
| 546 |
+
|
| 547 |
+
def test_reset_index_period(self):
|
| 548 |
+
# GH#7746
|
| 549 |
+
idx = MultiIndex.from_product(
|
| 550 |
+
[pd.period_range("20130101", periods=3, freq="M"), list("abc")],
|
| 551 |
+
names=["month", "feature"],
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
df = DataFrame(
|
| 555 |
+
np.arange(9, dtype="int64").reshape(-1, 1), index=idx, columns=["a"]
|
| 556 |
+
)
|
| 557 |
+
expected = DataFrame(
|
| 558 |
+
{
|
| 559 |
+
"month": (
|
| 560 |
+
[pd.Period("2013-01", freq="M")] * 3
|
| 561 |
+
+ [pd.Period("2013-02", freq="M")] * 3
|
| 562 |
+
+ [pd.Period("2013-03", freq="M")] * 3
|
| 563 |
+
),
|
| 564 |
+
"feature": ["a", "b", "c"] * 3,
|
| 565 |
+
"a": np.arange(9, dtype="int64"),
|
| 566 |
+
},
|
| 567 |
+
columns=["month", "feature", "a"],
|
| 568 |
+
)
|
| 569 |
+
result = df.reset_index()
|
| 570 |
+
tm.assert_frame_equal(result, expected)
|
| 571 |
+
|
| 572 |
+
def test_reset_index_delevel_infer_dtype(self):
|
| 573 |
+
tuples = list(product(["foo", "bar"], [10, 20], [1.0, 1.1]))
|
| 574 |
+
index = MultiIndex.from_tuples(tuples, names=["prm0", "prm1", "prm2"])
|
| 575 |
+
df = DataFrame(
|
| 576 |
+
np.random.default_rng(2).standard_normal((8, 3)),
|
| 577 |
+
columns=["A", "B", "C"],
|
| 578 |
+
index=index,
|
| 579 |
+
)
|
| 580 |
+
deleveled = df.reset_index()
|
| 581 |
+
assert is_integer_dtype(deleveled["prm1"])
|
| 582 |
+
assert is_float_dtype(deleveled["prm2"])
|
| 583 |
+
|
| 584 |
+
def test_reset_index_with_drop(
|
| 585 |
+
self, multiindex_year_month_day_dataframe_random_data
|
| 586 |
+
):
|
| 587 |
+
ymd = multiindex_year_month_day_dataframe_random_data
|
| 588 |
+
|
| 589 |
+
deleveled = ymd.reset_index(drop=True)
|
| 590 |
+
assert len(deleveled.columns) == len(ymd.columns)
|
| 591 |
+
assert deleveled.index.name == ymd.index.name
|
| 592 |
+
|
| 593 |
+
@pytest.mark.parametrize(
|
| 594 |
+
"ix_data, exp_data",
|
| 595 |
+
[
|
| 596 |
+
(
|
| 597 |
+
[(pd.NaT, 1), (pd.NaT, 2)],
|
| 598 |
+
{"a": [pd.NaT, pd.NaT], "b": [1, 2], "x": [11, 12]},
|
| 599 |
+
),
|
| 600 |
+
(
|
| 601 |
+
[(pd.NaT, 1), (Timestamp("2020-01-01"), 2)],
|
| 602 |
+
{"a": [pd.NaT, Timestamp("2020-01-01")], "b": [1, 2], "x": [11, 12]},
|
| 603 |
+
),
|
| 604 |
+
(
|
| 605 |
+
[(pd.NaT, 1), (pd.Timedelta(123, "d"), 2)],
|
| 606 |
+
{"a": [pd.NaT, pd.Timedelta(123, "d")], "b": [1, 2], "x": [11, 12]},
|
| 607 |
+
),
|
| 608 |
+
],
|
| 609 |
+
)
|
| 610 |
+
def test_reset_index_nat_multiindex(self, ix_data, exp_data):
|
| 611 |
+
# GH#36541: that reset_index() does not raise ValueError
|
| 612 |
+
ix = MultiIndex.from_tuples(ix_data, names=["a", "b"])
|
| 613 |
+
result = DataFrame({"x": [11, 12]}, index=ix)
|
| 614 |
+
result = result.reset_index()
|
| 615 |
+
|
| 616 |
+
expected = DataFrame(exp_data)
|
| 617 |
+
tm.assert_frame_equal(result, expected)
|
| 618 |
+
|
| 619 |
+
@pytest.mark.parametrize(
|
| 620 |
+
"codes", ([[0, 0, 1, 1], [0, 1, 0, 1]], [[0, 0, -1, 1], [0, 1, 0, 1]])
|
| 621 |
+
)
|
| 622 |
+
def test_rest_index_multiindex_categorical_with_missing_values(self, codes):
|
| 623 |
+
# GH#24206
|
| 624 |
+
|
| 625 |
+
index = MultiIndex(
|
| 626 |
+
[CategoricalIndex(["A", "B"]), CategoricalIndex(["a", "b"])], codes
|
| 627 |
+
)
|
| 628 |
+
data = {"col": range(len(index))}
|
| 629 |
+
df = DataFrame(data=data, index=index)
|
| 630 |
+
|
| 631 |
+
expected = DataFrame(
|
| 632 |
+
{
|
| 633 |
+
"level_0": Categorical.from_codes(codes[0], categories=["A", "B"]),
|
| 634 |
+
"level_1": Categorical.from_codes(codes[1], categories=["a", "b"]),
|
| 635 |
+
"col": range(4),
|
| 636 |
+
}
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
res = df.reset_index()
|
| 640 |
+
tm.assert_frame_equal(res, expected)
|
| 641 |
+
|
| 642 |
+
# roundtrip
|
| 643 |
+
res = expected.set_index(["level_0", "level_1"]).reset_index()
|
| 644 |
+
tm.assert_frame_equal(res, expected)
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
@pytest.mark.parametrize(
|
| 648 |
+
"array, dtype",
|
| 649 |
+
[
|
| 650 |
+
(["a", "b"], object),
|
| 651 |
+
(
|
| 652 |
+
pd.period_range("12-1-2000", periods=2, freq="Q-DEC"),
|
| 653 |
+
pd.PeriodDtype(freq="Q-DEC"),
|
| 654 |
+
),
|
| 655 |
+
],
|
| 656 |
+
)
|
| 657 |
+
def test_reset_index_dtypes_on_empty_frame_with_multiindex(
|
| 658 |
+
array, dtype, using_infer_string
|
| 659 |
+
):
|
| 660 |
+
# GH 19602 - Preserve dtype on empty DataFrame with MultiIndex
|
| 661 |
+
idx = MultiIndex.from_product([[0, 1], [0.5, 1.0], array])
|
| 662 |
+
result = DataFrame(index=idx)[:0].reset_index().dtypes
|
| 663 |
+
if using_infer_string and dtype == object:
|
| 664 |
+
dtype = "string"
|
| 665 |
+
expected = Series({"level_0": np.int64, "level_1": np.float64, "level_2": dtype})
|
| 666 |
+
tm.assert_series_equal(result, expected)
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def test_reset_index_empty_frame_with_datetime64_multiindex():
|
| 670 |
+
# https://github.com/pandas-dev/pandas/issues/35606
|
| 671 |
+
dti = pd.DatetimeIndex(["2020-07-20 00:00:00"], dtype="M8[ns]")
|
| 672 |
+
idx = MultiIndex.from_product([dti, [3, 4]], names=["a", "b"])[:0]
|
| 673 |
+
df = DataFrame(index=idx, columns=["c", "d"])
|
| 674 |
+
result = df.reset_index()
|
| 675 |
+
expected = DataFrame(
|
| 676 |
+
columns=list("abcd"), index=RangeIndex(start=0, stop=0, step=1)
|
| 677 |
+
)
|
| 678 |
+
expected["a"] = expected["a"].astype("datetime64[ns]")
|
| 679 |
+
expected["b"] = expected["b"].astype("int64")
|
| 680 |
+
tm.assert_frame_equal(result, expected)
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def test_reset_index_empty_frame_with_datetime64_multiindex_from_groupby(
|
| 684 |
+
using_infer_string,
|
| 685 |
+
):
|
| 686 |
+
# https://github.com/pandas-dev/pandas/issues/35657
|
| 687 |
+
dti = pd.DatetimeIndex(["2020-01-01"], dtype="M8[ns]")
|
| 688 |
+
df = DataFrame({"c1": [10.0], "c2": ["a"], "c3": dti})
|
| 689 |
+
df = df.head(0).groupby(["c2", "c3"])[["c1"]].sum()
|
| 690 |
+
result = df.reset_index()
|
| 691 |
+
expected = DataFrame(
|
| 692 |
+
columns=["c2", "c3", "c1"], index=RangeIndex(start=0, stop=0, step=1)
|
| 693 |
+
)
|
| 694 |
+
expected["c3"] = expected["c3"].astype("datetime64[ns]")
|
| 695 |
+
expected["c1"] = expected["c1"].astype("float64")
|
| 696 |
+
if using_infer_string:
|
| 697 |
+
expected["c2"] = expected["c2"].astype("string[pyarrow_numpy]")
|
| 698 |
+
tm.assert_frame_equal(result, expected)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def test_reset_index_multiindex_nat():
|
| 702 |
+
# GH 11479
|
| 703 |
+
idx = range(3)
|
| 704 |
+
tstamp = date_range("2015-07-01", freq="D", periods=3)
|
| 705 |
+
df = DataFrame({"id": idx, "tstamp": tstamp, "a": list("abc")})
|
| 706 |
+
df.loc[2, "tstamp"] = pd.NaT
|
| 707 |
+
result = df.set_index(["id", "tstamp"]).reset_index("id")
|
| 708 |
+
exp_dti = pd.DatetimeIndex(
|
| 709 |
+
["2015-07-01", "2015-07-02", "NaT"], dtype="M8[ns]", name="tstamp"
|
| 710 |
+
)
|
| 711 |
+
expected = DataFrame(
|
| 712 |
+
{"id": range(3), "a": list("abc")},
|
| 713 |
+
index=exp_dti,
|
| 714 |
+
)
|
| 715 |
+
tm.assert_frame_equal(result, expected)
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
def test_reset_index_interval_columns_object_cast():
|
| 719 |
+
# GH 19136
|
| 720 |
+
df = DataFrame(
|
| 721 |
+
np.eye(2), index=Index([1, 2], name="Year"), columns=cut([1, 2], [0, 1, 2])
|
| 722 |
+
)
|
| 723 |
+
result = df.reset_index()
|
| 724 |
+
expected = DataFrame(
|
| 725 |
+
[[1, 1.0, 0.0], [2, 0.0, 1.0]],
|
| 726 |
+
columns=Index(["Year", Interval(0, 1), Interval(1, 2)]),
|
| 727 |
+
)
|
| 728 |
+
tm.assert_frame_equal(result, expected)
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def test_reset_index_rename(float_frame):
|
| 732 |
+
# GH 6878
|
| 733 |
+
result = float_frame.reset_index(names="new_name")
|
| 734 |
+
expected = Series(float_frame.index.values, name="new_name")
|
| 735 |
+
tm.assert_series_equal(result["new_name"], expected)
|
| 736 |
+
|
| 737 |
+
result = float_frame.reset_index(names=123)
|
| 738 |
+
expected = Series(float_frame.index.values, name=123)
|
| 739 |
+
tm.assert_series_equal(result[123], expected)
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def test_reset_index_rename_multiindex(float_frame):
|
| 743 |
+
# GH 6878
|
| 744 |
+
stacked_df = float_frame.stack(future_stack=True)[::2]
|
| 745 |
+
stacked_df = DataFrame({"foo": stacked_df, "bar": stacked_df})
|
| 746 |
+
|
| 747 |
+
names = ["first", "second"]
|
| 748 |
+
stacked_df.index.names = names
|
| 749 |
+
|
| 750 |
+
result = stacked_df.reset_index()
|
| 751 |
+
expected = stacked_df.reset_index(names=["new_first", "new_second"])
|
| 752 |
+
tm.assert_series_equal(result["first"], expected["new_first"], check_names=False)
|
| 753 |
+
tm.assert_series_equal(result["second"], expected["new_second"], check_names=False)
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def test_errorreset_index_rename(float_frame):
|
| 757 |
+
# GH 6878
|
| 758 |
+
stacked_df = float_frame.stack(future_stack=True)[::2]
|
| 759 |
+
stacked_df = DataFrame({"first": stacked_df, "second": stacked_df})
|
| 760 |
+
|
| 761 |
+
with pytest.raises(
|
| 762 |
+
ValueError, match="Index names must be str or 1-dimensional list"
|
| 763 |
+
):
|
| 764 |
+
stacked_df.reset_index(names={"first": "new_first", "second": "new_second"})
|
| 765 |
+
|
| 766 |
+
with pytest.raises(IndexError, match="list index out of range"):
|
| 767 |
+
stacked_df.reset_index(names=["new_first"])
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def test_reset_index_false_index_name():
|
| 771 |
+
result_series = Series(data=range(5, 10), index=range(5))
|
| 772 |
+
result_series.index.name = False
|
| 773 |
+
result_series.reset_index()
|
| 774 |
+
expected_series = Series(range(5, 10), RangeIndex(range(5), name=False))
|
| 775 |
+
tm.assert_series_equal(result_series, expected_series)
|
| 776 |
+
|
| 777 |
+
# GH 38147
|
| 778 |
+
result_frame = DataFrame(data=range(5, 10), index=range(5))
|
| 779 |
+
result_frame.index.name = False
|
| 780 |
+
result_frame.reset_index()
|
| 781 |
+
expected_frame = DataFrame(range(5, 10), RangeIndex(range(5), name=False))
|
| 782 |
+
tm.assert_frame_equal(result_frame, expected_frame)
|
mantis_evalkit/lib/python3.10/site-packages/pandas/tests/frame/methods/test_set_axis.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import (
|
| 5 |
+
DataFrame,
|
| 6 |
+
Series,
|
| 7 |
+
)
|
| 8 |
+
import pandas._testing as tm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SharedSetAxisTests:
|
| 12 |
+
@pytest.fixture
|
| 13 |
+
def obj(self):
|
| 14 |
+
raise NotImplementedError("Implemented by subclasses")
|
| 15 |
+
|
| 16 |
+
def test_set_axis(self, obj):
|
| 17 |
+
# GH14636; this tests setting index for both Series and DataFrame
|
| 18 |
+
new_index = list("abcd")[: len(obj)]
|
| 19 |
+
expected = obj.copy()
|
| 20 |
+
expected.index = new_index
|
| 21 |
+
result = obj.set_axis(new_index, axis=0)
|
| 22 |
+
tm.assert_equal(expected, result)
|
| 23 |
+
|
| 24 |
+
def test_set_axis_copy(self, obj, using_copy_on_write):
|
| 25 |
+
# Test copy keyword GH#47932
|
| 26 |
+
new_index = list("abcd")[: len(obj)]
|
| 27 |
+
|
| 28 |
+
orig = obj.iloc[:]
|
| 29 |
+
expected = obj.copy()
|
| 30 |
+
expected.index = new_index
|
| 31 |
+
|
| 32 |
+
result = obj.set_axis(new_index, axis=0, copy=True)
|
| 33 |
+
tm.assert_equal(expected, result)
|
| 34 |
+
assert result is not obj
|
| 35 |
+
# check we DID make a copy
|
| 36 |
+
if not using_copy_on_write:
|
| 37 |
+
if obj.ndim == 1:
|
| 38 |
+
assert not tm.shares_memory(result, obj)
|
| 39 |
+
else:
|
| 40 |
+
assert not any(
|
| 41 |
+
tm.shares_memory(result.iloc[:, i], obj.iloc[:, i])
|
| 42 |
+
for i in range(obj.shape[1])
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
result = obj.set_axis(new_index, axis=0, copy=False)
|
| 46 |
+
tm.assert_equal(expected, result)
|
| 47 |
+
assert result is not obj
|
| 48 |
+
# check we did NOT make a copy
|
| 49 |
+
if obj.ndim == 1:
|
| 50 |
+
assert tm.shares_memory(result, obj)
|
| 51 |
+
else:
|
| 52 |
+
assert all(
|
| 53 |
+
tm.shares_memory(result.iloc[:, i], obj.iloc[:, i])
|
| 54 |
+
for i in range(obj.shape[1])
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# copy defaults to True
|
| 58 |
+
result = obj.set_axis(new_index, axis=0)
|
| 59 |
+
tm.assert_equal(expected, result)
|
| 60 |
+
assert result is not obj
|
| 61 |
+
if using_copy_on_write:
|
| 62 |
+
# check we DID NOT make a copy
|
| 63 |
+
if obj.ndim == 1:
|
| 64 |
+
assert tm.shares_memory(result, obj)
|
| 65 |
+
else:
|
| 66 |
+
assert any(
|
| 67 |
+
tm.shares_memory(result.iloc[:, i], obj.iloc[:, i])
|
| 68 |
+
for i in range(obj.shape[1])
|
| 69 |
+
)
|
| 70 |
+
# check we DID make a copy
|
| 71 |
+
elif obj.ndim == 1:
|
| 72 |
+
assert not tm.shares_memory(result, obj)
|
| 73 |
+
else:
|
| 74 |
+
assert not any(
|
| 75 |
+
tm.shares_memory(result.iloc[:, i], obj.iloc[:, i])
|
| 76 |
+
for i in range(obj.shape[1])
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
res = obj.set_axis(new_index, copy=False)
|
| 80 |
+
tm.assert_equal(expected, res)
|
| 81 |
+
# check we did NOT make a copy
|
| 82 |
+
if res.ndim == 1:
|
| 83 |
+
assert tm.shares_memory(res, orig)
|
| 84 |
+
else:
|
| 85 |
+
assert all(
|
| 86 |
+
tm.shares_memory(res.iloc[:, i], orig.iloc[:, i])
|
| 87 |
+
for i in range(res.shape[1])
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def test_set_axis_unnamed_kwarg_warns(self, obj):
|
| 91 |
+
# omitting the "axis" parameter
|
| 92 |
+
new_index = list("abcd")[: len(obj)]
|
| 93 |
+
|
| 94 |
+
expected = obj.copy()
|
| 95 |
+
expected.index = new_index
|
| 96 |
+
|
| 97 |
+
result = obj.set_axis(new_index)
|
| 98 |
+
tm.assert_equal(result, expected)
|
| 99 |
+
|
| 100 |
+
@pytest.mark.parametrize("axis", [3, "foo"])
|
| 101 |
+
def test_set_axis_invalid_axis_name(self, axis, obj):
|
| 102 |
+
# wrong values for the "axis" parameter
|
| 103 |
+
with pytest.raises(ValueError, match="No axis named"):
|
| 104 |
+
obj.set_axis(list("abc"), axis=axis)
|
| 105 |
+
|
| 106 |
+
def test_set_axis_setattr_index_not_collection(self, obj):
|
| 107 |
+
# wrong type
|
| 108 |
+
msg = (
|
| 109 |
+
r"Index\(\.\.\.\) must be called with a collection of some "
|
| 110 |
+
r"kind, None was passed"
|
| 111 |
+
)
|
| 112 |
+
with pytest.raises(TypeError, match=msg):
|
| 113 |
+
obj.index = None
|
| 114 |
+
|
| 115 |
+
def test_set_axis_setattr_index_wrong_length(self, obj):
|
| 116 |
+
# wrong length
|
| 117 |
+
msg = (
|
| 118 |
+
f"Length mismatch: Expected axis has {len(obj)} elements, "
|
| 119 |
+
f"new values have {len(obj)-1} elements"
|
| 120 |
+
)
|
| 121 |
+
with pytest.raises(ValueError, match=msg):
|
| 122 |
+
obj.index = np.arange(len(obj) - 1)
|
| 123 |
+
|
| 124 |
+
if obj.ndim == 2:
|
| 125 |
+
with pytest.raises(ValueError, match="Length mismatch"):
|
| 126 |
+
obj.columns = obj.columns[::2]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class TestDataFrameSetAxis(SharedSetAxisTests):
|
| 130 |
+
@pytest.fixture
|
| 131 |
+
def obj(self):
|
| 132 |
+
df = DataFrame(
|
| 133 |
+
{"A": [1.1, 2.2, 3.3], "B": [5.0, 6.1, 7.2], "C": [4.4, 5.5, 6.6]},
|
| 134 |
+
index=[2010, 2011, 2012],
|
| 135 |
+
)
|
| 136 |
+
return df
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class TestSeriesSetAxis(SharedSetAxisTests):
|
| 140 |
+
@pytest.fixture
|
| 141 |
+
def obj(self):
|
| 142 |
+
ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64")
|
| 143 |
+
return ser
|
moondream/lib/python3.10/site-packages/altair/vegalite/v5/__pycache__/api.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f22b5f7666123e57a16b8fcd0ee830797e1dcba7a2df4aa2866e2cfdee2f6a01
|
| 3 |
+
size 162833
|
moondream/lib/python3.10/site-packages/pandas/io/clipboard/__init__.py
ADDED
|
@@ -0,0 +1,747 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pyperclip
|
| 3 |
+
|
| 4 |
+
A cross-platform clipboard module for Python,
|
| 5 |
+
with copy & paste functions for plain text.
|
| 6 |
+
By Al Sweigart al@inventwithpython.com
|
| 7 |
+
Licence at LICENSES/PYPERCLIP_LICENSE
|
| 8 |
+
|
| 9 |
+
Usage:
|
| 10 |
+
import pyperclip
|
| 11 |
+
pyperclip.copy('The text to be copied to the clipboard.')
|
| 12 |
+
spam = pyperclip.paste()
|
| 13 |
+
|
| 14 |
+
if not pyperclip.is_available():
|
| 15 |
+
print("Copy functionality unavailable!")
|
| 16 |
+
|
| 17 |
+
On Windows, no additional modules are needed.
|
| 18 |
+
On Mac, the pyobjc module is used, falling back to the pbcopy and pbpaste cli
|
| 19 |
+
commands. (These commands should come with OS X.).
|
| 20 |
+
On Linux, install xclip, xsel, or wl-clipboard (for "wayland" sessions) via
|
| 21 |
+
package manager.
|
| 22 |
+
For example, in Debian:
|
| 23 |
+
sudo apt-get install xclip
|
| 24 |
+
sudo apt-get install xsel
|
| 25 |
+
sudo apt-get install wl-clipboard
|
| 26 |
+
|
| 27 |
+
Otherwise on Linux, you will need the PyQt5 modules installed.
|
| 28 |
+
|
| 29 |
+
This module does not work with PyGObject yet.
|
| 30 |
+
|
| 31 |
+
Cygwin is currently not supported.
|
| 32 |
+
|
| 33 |
+
Security Note: This module runs programs with these names:
|
| 34 |
+
- pbcopy
|
| 35 |
+
- pbpaste
|
| 36 |
+
- xclip
|
| 37 |
+
- xsel
|
| 38 |
+
- wl-copy/wl-paste
|
| 39 |
+
- klipper
|
| 40 |
+
- qdbus
|
| 41 |
+
A malicious user could rename or add programs with these names, tricking
|
| 42 |
+
Pyperclip into running them with whatever permissions the Python process has.
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
__version__ = "1.8.2"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
import contextlib
|
| 50 |
+
import ctypes
|
| 51 |
+
from ctypes import (
|
| 52 |
+
c_size_t,
|
| 53 |
+
c_wchar,
|
| 54 |
+
c_wchar_p,
|
| 55 |
+
get_errno,
|
| 56 |
+
sizeof,
|
| 57 |
+
)
|
| 58 |
+
import os
|
| 59 |
+
import platform
|
| 60 |
+
from shutil import which as _executable_exists
|
| 61 |
+
import subprocess
|
| 62 |
+
import time
|
| 63 |
+
import warnings
|
| 64 |
+
|
| 65 |
+
from pandas.errors import (
|
| 66 |
+
PyperclipException,
|
| 67 |
+
PyperclipWindowsException,
|
| 68 |
+
)
|
| 69 |
+
from pandas.util._exceptions import find_stack_level
|
| 70 |
+
|
| 71 |
+
# `import PyQt4` sys.exit()s if DISPLAY is not in the environment.
|
| 72 |
+
# Thus, we need to detect the presence of $DISPLAY manually
|
| 73 |
+
# and not load PyQt4 if it is absent.
|
| 74 |
+
HAS_DISPLAY = os.getenv("DISPLAY")
|
| 75 |
+
|
| 76 |
+
EXCEPT_MSG = """
|
| 77 |
+
Pyperclip could not find a copy/paste mechanism for your system.
|
| 78 |
+
For more information, please visit
|
| 79 |
+
https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
ENCODING = "utf-8"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class PyperclipTimeoutException(PyperclipException):
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _stringifyText(text) -> str:
|
| 90 |
+
acceptedTypes = (str, int, float, bool)
|
| 91 |
+
if not isinstance(text, acceptedTypes):
|
| 92 |
+
raise PyperclipException(
|
| 93 |
+
f"only str, int, float, and bool values "
|
| 94 |
+
f"can be copied to the clipboard, not {type(text).__name__}"
|
| 95 |
+
)
|
| 96 |
+
return str(text)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def init_osx_pbcopy_clipboard():
|
| 100 |
+
def copy_osx_pbcopy(text):
|
| 101 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 102 |
+
with subprocess.Popen(
|
| 103 |
+
["pbcopy", "w"], stdin=subprocess.PIPE, close_fds=True
|
| 104 |
+
) as p:
|
| 105 |
+
p.communicate(input=text.encode(ENCODING))
|
| 106 |
+
|
| 107 |
+
def paste_osx_pbcopy():
|
| 108 |
+
with subprocess.Popen(
|
| 109 |
+
["pbpaste", "r"], stdout=subprocess.PIPE, close_fds=True
|
| 110 |
+
) as p:
|
| 111 |
+
stdout = p.communicate()[0]
|
| 112 |
+
return stdout.decode(ENCODING)
|
| 113 |
+
|
| 114 |
+
return copy_osx_pbcopy, paste_osx_pbcopy
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def init_osx_pyobjc_clipboard():
|
| 118 |
+
def copy_osx_pyobjc(text):
|
| 119 |
+
"""Copy string argument to clipboard"""
|
| 120 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 121 |
+
newStr = Foundation.NSString.stringWithString_(text).nsstring()
|
| 122 |
+
newData = newStr.dataUsingEncoding_(Foundation.NSUTF8StringEncoding)
|
| 123 |
+
board = AppKit.NSPasteboard.generalPasteboard()
|
| 124 |
+
board.declareTypes_owner_([AppKit.NSStringPboardType], None)
|
| 125 |
+
board.setData_forType_(newData, AppKit.NSStringPboardType)
|
| 126 |
+
|
| 127 |
+
def paste_osx_pyobjc():
|
| 128 |
+
"""Returns contents of clipboard"""
|
| 129 |
+
board = AppKit.NSPasteboard.generalPasteboard()
|
| 130 |
+
content = board.stringForType_(AppKit.NSStringPboardType)
|
| 131 |
+
return content
|
| 132 |
+
|
| 133 |
+
return copy_osx_pyobjc, paste_osx_pyobjc
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def init_qt_clipboard():
|
| 137 |
+
global QApplication
|
| 138 |
+
# $DISPLAY should exist
|
| 139 |
+
|
| 140 |
+
# Try to import from qtpy, but if that fails try PyQt5 then PyQt4
|
| 141 |
+
try:
|
| 142 |
+
from qtpy.QtWidgets import QApplication
|
| 143 |
+
except ImportError:
|
| 144 |
+
try:
|
| 145 |
+
from PyQt5.QtWidgets import QApplication
|
| 146 |
+
except ImportError:
|
| 147 |
+
from PyQt4.QtGui import QApplication
|
| 148 |
+
|
| 149 |
+
app = QApplication.instance()
|
| 150 |
+
if app is None:
|
| 151 |
+
app = QApplication([])
|
| 152 |
+
|
| 153 |
+
def copy_qt(text):
|
| 154 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 155 |
+
cb = app.clipboard()
|
| 156 |
+
cb.setText(text)
|
| 157 |
+
|
| 158 |
+
def paste_qt() -> str:
|
| 159 |
+
cb = app.clipboard()
|
| 160 |
+
return str(cb.text())
|
| 161 |
+
|
| 162 |
+
return copy_qt, paste_qt
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def init_xclip_clipboard():
|
| 166 |
+
DEFAULT_SELECTION = "c"
|
| 167 |
+
PRIMARY_SELECTION = "p"
|
| 168 |
+
|
| 169 |
+
def copy_xclip(text, primary=False):
|
| 170 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 171 |
+
selection = DEFAULT_SELECTION
|
| 172 |
+
if primary:
|
| 173 |
+
selection = PRIMARY_SELECTION
|
| 174 |
+
with subprocess.Popen(
|
| 175 |
+
["xclip", "-selection", selection], stdin=subprocess.PIPE, close_fds=True
|
| 176 |
+
) as p:
|
| 177 |
+
p.communicate(input=text.encode(ENCODING))
|
| 178 |
+
|
| 179 |
+
def paste_xclip(primary=False):
|
| 180 |
+
selection = DEFAULT_SELECTION
|
| 181 |
+
if primary:
|
| 182 |
+
selection = PRIMARY_SELECTION
|
| 183 |
+
with subprocess.Popen(
|
| 184 |
+
["xclip", "-selection", selection, "-o"],
|
| 185 |
+
stdout=subprocess.PIPE,
|
| 186 |
+
stderr=subprocess.PIPE,
|
| 187 |
+
close_fds=True,
|
| 188 |
+
) as p:
|
| 189 |
+
stdout = p.communicate()[0]
|
| 190 |
+
# Intentionally ignore extraneous output on stderr when clipboard is empty
|
| 191 |
+
return stdout.decode(ENCODING)
|
| 192 |
+
|
| 193 |
+
return copy_xclip, paste_xclip
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def init_xsel_clipboard():
|
| 197 |
+
DEFAULT_SELECTION = "-b"
|
| 198 |
+
PRIMARY_SELECTION = "-p"
|
| 199 |
+
|
| 200 |
+
def copy_xsel(text, primary=False):
|
| 201 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 202 |
+
selection_flag = DEFAULT_SELECTION
|
| 203 |
+
if primary:
|
| 204 |
+
selection_flag = PRIMARY_SELECTION
|
| 205 |
+
with subprocess.Popen(
|
| 206 |
+
["xsel", selection_flag, "-i"], stdin=subprocess.PIPE, close_fds=True
|
| 207 |
+
) as p:
|
| 208 |
+
p.communicate(input=text.encode(ENCODING))
|
| 209 |
+
|
| 210 |
+
def paste_xsel(primary=False):
|
| 211 |
+
selection_flag = DEFAULT_SELECTION
|
| 212 |
+
if primary:
|
| 213 |
+
selection_flag = PRIMARY_SELECTION
|
| 214 |
+
with subprocess.Popen(
|
| 215 |
+
["xsel", selection_flag, "-o"], stdout=subprocess.PIPE, close_fds=True
|
| 216 |
+
) as p:
|
| 217 |
+
stdout = p.communicate()[0]
|
| 218 |
+
return stdout.decode(ENCODING)
|
| 219 |
+
|
| 220 |
+
return copy_xsel, paste_xsel
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def init_wl_clipboard():
|
| 224 |
+
PRIMARY_SELECTION = "-p"
|
| 225 |
+
|
| 226 |
+
def copy_wl(text, primary=False):
|
| 227 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 228 |
+
args = ["wl-copy"]
|
| 229 |
+
if primary:
|
| 230 |
+
args.append(PRIMARY_SELECTION)
|
| 231 |
+
if not text:
|
| 232 |
+
args.append("--clear")
|
| 233 |
+
subprocess.check_call(args, close_fds=True)
|
| 234 |
+
else:
|
| 235 |
+
p = subprocess.Popen(args, stdin=subprocess.PIPE, close_fds=True)
|
| 236 |
+
p.communicate(input=text.encode(ENCODING))
|
| 237 |
+
|
| 238 |
+
def paste_wl(primary=False):
|
| 239 |
+
args = ["wl-paste", "-n"]
|
| 240 |
+
if primary:
|
| 241 |
+
args.append(PRIMARY_SELECTION)
|
| 242 |
+
p = subprocess.Popen(args, stdout=subprocess.PIPE, close_fds=True)
|
| 243 |
+
stdout, _stderr = p.communicate()
|
| 244 |
+
return stdout.decode(ENCODING)
|
| 245 |
+
|
| 246 |
+
return copy_wl, paste_wl
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def init_klipper_clipboard():
|
| 250 |
+
def copy_klipper(text):
|
| 251 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 252 |
+
with subprocess.Popen(
|
| 253 |
+
[
|
| 254 |
+
"qdbus",
|
| 255 |
+
"org.kde.klipper",
|
| 256 |
+
"/klipper",
|
| 257 |
+
"setClipboardContents",
|
| 258 |
+
text.encode(ENCODING),
|
| 259 |
+
],
|
| 260 |
+
stdin=subprocess.PIPE,
|
| 261 |
+
close_fds=True,
|
| 262 |
+
) as p:
|
| 263 |
+
p.communicate(input=None)
|
| 264 |
+
|
| 265 |
+
def paste_klipper():
|
| 266 |
+
with subprocess.Popen(
|
| 267 |
+
["qdbus", "org.kde.klipper", "/klipper", "getClipboardContents"],
|
| 268 |
+
stdout=subprocess.PIPE,
|
| 269 |
+
close_fds=True,
|
| 270 |
+
) as p:
|
| 271 |
+
stdout = p.communicate()[0]
|
| 272 |
+
|
| 273 |
+
# Workaround for https://bugs.kde.org/show_bug.cgi?id=342874
|
| 274 |
+
# TODO: https://github.com/asweigart/pyperclip/issues/43
|
| 275 |
+
clipboardContents = stdout.decode(ENCODING)
|
| 276 |
+
# even if blank, Klipper will append a newline at the end
|
| 277 |
+
assert len(clipboardContents) > 0
|
| 278 |
+
# make sure that newline is there
|
| 279 |
+
assert clipboardContents.endswith("\n")
|
| 280 |
+
if clipboardContents.endswith("\n"):
|
| 281 |
+
clipboardContents = clipboardContents[:-1]
|
| 282 |
+
return clipboardContents
|
| 283 |
+
|
| 284 |
+
return copy_klipper, paste_klipper
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def init_dev_clipboard_clipboard():
|
| 288 |
+
def copy_dev_clipboard(text):
|
| 289 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 290 |
+
if text == "":
|
| 291 |
+
warnings.warn(
|
| 292 |
+
"Pyperclip cannot copy a blank string to the clipboard on Cygwin. "
|
| 293 |
+
"This is effectively a no-op.",
|
| 294 |
+
stacklevel=find_stack_level(),
|
| 295 |
+
)
|
| 296 |
+
if "\r" in text:
|
| 297 |
+
warnings.warn(
|
| 298 |
+
"Pyperclip cannot handle \\r characters on Cygwin.",
|
| 299 |
+
stacklevel=find_stack_level(),
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
with open("/dev/clipboard", "w", encoding="utf-8") as fd:
|
| 303 |
+
fd.write(text)
|
| 304 |
+
|
| 305 |
+
def paste_dev_clipboard() -> str:
|
| 306 |
+
with open("/dev/clipboard", encoding="utf-8") as fd:
|
| 307 |
+
content = fd.read()
|
| 308 |
+
return content
|
| 309 |
+
|
| 310 |
+
return copy_dev_clipboard, paste_dev_clipboard
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def init_no_clipboard():
|
| 314 |
+
class ClipboardUnavailable:
|
| 315 |
+
def __call__(self, *args, **kwargs):
|
| 316 |
+
raise PyperclipException(EXCEPT_MSG)
|
| 317 |
+
|
| 318 |
+
def __bool__(self) -> bool:
|
| 319 |
+
return False
|
| 320 |
+
|
| 321 |
+
return ClipboardUnavailable(), ClipboardUnavailable()
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
# Windows-related clipboard functions:
|
| 325 |
+
class CheckedCall:
|
| 326 |
+
def __init__(self, f) -> None:
|
| 327 |
+
super().__setattr__("f", f)
|
| 328 |
+
|
| 329 |
+
def __call__(self, *args):
|
| 330 |
+
ret = self.f(*args)
|
| 331 |
+
if not ret and get_errno():
|
| 332 |
+
raise PyperclipWindowsException("Error calling " + self.f.__name__)
|
| 333 |
+
return ret
|
| 334 |
+
|
| 335 |
+
def __setattr__(self, key, value):
|
| 336 |
+
setattr(self.f, key, value)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def init_windows_clipboard():
|
| 340 |
+
global HGLOBAL, LPVOID, DWORD, LPCSTR, INT
|
| 341 |
+
global HWND, HINSTANCE, HMENU, BOOL, UINT, HANDLE
|
| 342 |
+
from ctypes.wintypes import (
|
| 343 |
+
BOOL,
|
| 344 |
+
DWORD,
|
| 345 |
+
HANDLE,
|
| 346 |
+
HGLOBAL,
|
| 347 |
+
HINSTANCE,
|
| 348 |
+
HMENU,
|
| 349 |
+
HWND,
|
| 350 |
+
INT,
|
| 351 |
+
LPCSTR,
|
| 352 |
+
LPVOID,
|
| 353 |
+
UINT,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
windll = ctypes.windll
|
| 357 |
+
msvcrt = ctypes.CDLL("msvcrt")
|
| 358 |
+
|
| 359 |
+
safeCreateWindowExA = CheckedCall(windll.user32.CreateWindowExA)
|
| 360 |
+
safeCreateWindowExA.argtypes = [
|
| 361 |
+
DWORD,
|
| 362 |
+
LPCSTR,
|
| 363 |
+
LPCSTR,
|
| 364 |
+
DWORD,
|
| 365 |
+
INT,
|
| 366 |
+
INT,
|
| 367 |
+
INT,
|
| 368 |
+
INT,
|
| 369 |
+
HWND,
|
| 370 |
+
HMENU,
|
| 371 |
+
HINSTANCE,
|
| 372 |
+
LPVOID,
|
| 373 |
+
]
|
| 374 |
+
safeCreateWindowExA.restype = HWND
|
| 375 |
+
|
| 376 |
+
safeDestroyWindow = CheckedCall(windll.user32.DestroyWindow)
|
| 377 |
+
safeDestroyWindow.argtypes = [HWND]
|
| 378 |
+
safeDestroyWindow.restype = BOOL
|
| 379 |
+
|
| 380 |
+
OpenClipboard = windll.user32.OpenClipboard
|
| 381 |
+
OpenClipboard.argtypes = [HWND]
|
| 382 |
+
OpenClipboard.restype = BOOL
|
| 383 |
+
|
| 384 |
+
safeCloseClipboard = CheckedCall(windll.user32.CloseClipboard)
|
| 385 |
+
safeCloseClipboard.argtypes = []
|
| 386 |
+
safeCloseClipboard.restype = BOOL
|
| 387 |
+
|
| 388 |
+
safeEmptyClipboard = CheckedCall(windll.user32.EmptyClipboard)
|
| 389 |
+
safeEmptyClipboard.argtypes = []
|
| 390 |
+
safeEmptyClipboard.restype = BOOL
|
| 391 |
+
|
| 392 |
+
safeGetClipboardData = CheckedCall(windll.user32.GetClipboardData)
|
| 393 |
+
safeGetClipboardData.argtypes = [UINT]
|
| 394 |
+
safeGetClipboardData.restype = HANDLE
|
| 395 |
+
|
| 396 |
+
safeSetClipboardData = CheckedCall(windll.user32.SetClipboardData)
|
| 397 |
+
safeSetClipboardData.argtypes = [UINT, HANDLE]
|
| 398 |
+
safeSetClipboardData.restype = HANDLE
|
| 399 |
+
|
| 400 |
+
safeGlobalAlloc = CheckedCall(windll.kernel32.GlobalAlloc)
|
| 401 |
+
safeGlobalAlloc.argtypes = [UINT, c_size_t]
|
| 402 |
+
safeGlobalAlloc.restype = HGLOBAL
|
| 403 |
+
|
| 404 |
+
safeGlobalLock = CheckedCall(windll.kernel32.GlobalLock)
|
| 405 |
+
safeGlobalLock.argtypes = [HGLOBAL]
|
| 406 |
+
safeGlobalLock.restype = LPVOID
|
| 407 |
+
|
| 408 |
+
safeGlobalUnlock = CheckedCall(windll.kernel32.GlobalUnlock)
|
| 409 |
+
safeGlobalUnlock.argtypes = [HGLOBAL]
|
| 410 |
+
safeGlobalUnlock.restype = BOOL
|
| 411 |
+
|
| 412 |
+
wcslen = CheckedCall(msvcrt.wcslen)
|
| 413 |
+
wcslen.argtypes = [c_wchar_p]
|
| 414 |
+
wcslen.restype = UINT
|
| 415 |
+
|
| 416 |
+
GMEM_MOVEABLE = 0x0002
|
| 417 |
+
CF_UNICODETEXT = 13
|
| 418 |
+
|
| 419 |
+
@contextlib.contextmanager
|
| 420 |
+
def window():
|
| 421 |
+
"""
|
| 422 |
+
Context that provides a valid Windows hwnd.
|
| 423 |
+
"""
|
| 424 |
+
# we really just need the hwnd, so setting "STATIC"
|
| 425 |
+
# as predefined lpClass is just fine.
|
| 426 |
+
hwnd = safeCreateWindowExA(
|
| 427 |
+
0, b"STATIC", None, 0, 0, 0, 0, 0, None, None, None, None
|
| 428 |
+
)
|
| 429 |
+
try:
|
| 430 |
+
yield hwnd
|
| 431 |
+
finally:
|
| 432 |
+
safeDestroyWindow(hwnd)
|
| 433 |
+
|
| 434 |
+
@contextlib.contextmanager
|
| 435 |
+
def clipboard(hwnd):
|
| 436 |
+
"""
|
| 437 |
+
Context manager that opens the clipboard and prevents
|
| 438 |
+
other applications from modifying the clipboard content.
|
| 439 |
+
"""
|
| 440 |
+
# We may not get the clipboard handle immediately because
|
| 441 |
+
# some other application is accessing it (?)
|
| 442 |
+
# We try for at least 500ms to get the clipboard.
|
| 443 |
+
t = time.time() + 0.5
|
| 444 |
+
success = False
|
| 445 |
+
while time.time() < t:
|
| 446 |
+
success = OpenClipboard(hwnd)
|
| 447 |
+
if success:
|
| 448 |
+
break
|
| 449 |
+
time.sleep(0.01)
|
| 450 |
+
if not success:
|
| 451 |
+
raise PyperclipWindowsException("Error calling OpenClipboard")
|
| 452 |
+
|
| 453 |
+
try:
|
| 454 |
+
yield
|
| 455 |
+
finally:
|
| 456 |
+
safeCloseClipboard()
|
| 457 |
+
|
| 458 |
+
def copy_windows(text):
|
| 459 |
+
# This function is heavily based on
|
| 460 |
+
# http://msdn.com/ms649016#_win32_Copying_Information_to_the_Clipboard
|
| 461 |
+
|
| 462 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 463 |
+
|
| 464 |
+
with window() as hwnd:
|
| 465 |
+
# http://msdn.com/ms649048
|
| 466 |
+
# If an application calls OpenClipboard with hwnd set to NULL,
|
| 467 |
+
# EmptyClipboard sets the clipboard owner to NULL;
|
| 468 |
+
# this causes SetClipboardData to fail.
|
| 469 |
+
# => We need a valid hwnd to copy something.
|
| 470 |
+
with clipboard(hwnd):
|
| 471 |
+
safeEmptyClipboard()
|
| 472 |
+
|
| 473 |
+
if text:
|
| 474 |
+
# http://msdn.com/ms649051
|
| 475 |
+
# If the hMem parameter identifies a memory object,
|
| 476 |
+
# the object must have been allocated using the
|
| 477 |
+
# function with the GMEM_MOVEABLE flag.
|
| 478 |
+
count = wcslen(text) + 1
|
| 479 |
+
handle = safeGlobalAlloc(GMEM_MOVEABLE, count * sizeof(c_wchar))
|
| 480 |
+
locked_handle = safeGlobalLock(handle)
|
| 481 |
+
|
| 482 |
+
ctypes.memmove(
|
| 483 |
+
c_wchar_p(locked_handle),
|
| 484 |
+
c_wchar_p(text),
|
| 485 |
+
count * sizeof(c_wchar),
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
safeGlobalUnlock(handle)
|
| 489 |
+
safeSetClipboardData(CF_UNICODETEXT, handle)
|
| 490 |
+
|
| 491 |
+
def paste_windows():
|
| 492 |
+
with clipboard(None):
|
| 493 |
+
handle = safeGetClipboardData(CF_UNICODETEXT)
|
| 494 |
+
if not handle:
|
| 495 |
+
# GetClipboardData may return NULL with errno == NO_ERROR
|
| 496 |
+
# if the clipboard is empty.
|
| 497 |
+
# (Also, it may return a handle to an empty buffer,
|
| 498 |
+
# but technically that's not empty)
|
| 499 |
+
return ""
|
| 500 |
+
return c_wchar_p(handle).value
|
| 501 |
+
|
| 502 |
+
return copy_windows, paste_windows
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def init_wsl_clipboard():
|
| 506 |
+
def copy_wsl(text):
|
| 507 |
+
text = _stringifyText(text) # Converts non-str values to str.
|
| 508 |
+
with subprocess.Popen(["clip.exe"], stdin=subprocess.PIPE, close_fds=True) as p:
|
| 509 |
+
p.communicate(input=text.encode(ENCODING))
|
| 510 |
+
|
| 511 |
+
def paste_wsl():
|
| 512 |
+
with subprocess.Popen(
|
| 513 |
+
["powershell.exe", "-command", "Get-Clipboard"],
|
| 514 |
+
stdout=subprocess.PIPE,
|
| 515 |
+
stderr=subprocess.PIPE,
|
| 516 |
+
close_fds=True,
|
| 517 |
+
) as p:
|
| 518 |
+
stdout = p.communicate()[0]
|
| 519 |
+
# WSL appends "\r\n" to the contents.
|
| 520 |
+
return stdout[:-2].decode(ENCODING)
|
| 521 |
+
|
| 522 |
+
return copy_wsl, paste_wsl
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
# Automatic detection of clipboard mechanisms
|
| 526 |
+
# and importing is done in determine_clipboard():
|
| 527 |
+
def determine_clipboard():
|
| 528 |
+
"""
|
| 529 |
+
Determine the OS/platform and set the copy() and paste() functions
|
| 530 |
+
accordingly.
|
| 531 |
+
"""
|
| 532 |
+
global Foundation, AppKit, qtpy, PyQt4, PyQt5
|
| 533 |
+
|
| 534 |
+
# Setup for the CYGWIN platform:
|
| 535 |
+
if (
|
| 536 |
+
"cygwin" in platform.system().lower()
|
| 537 |
+
): # Cygwin has a variety of values returned by platform.system(),
|
| 538 |
+
# such as 'CYGWIN_NT-6.1'
|
| 539 |
+
# FIXME(pyperclip#55): pyperclip currently does not support Cygwin,
|
| 540 |
+
# see https://github.com/asweigart/pyperclip/issues/55
|
| 541 |
+
if os.path.exists("/dev/clipboard"):
|
| 542 |
+
warnings.warn(
|
| 543 |
+
"Pyperclip's support for Cygwin is not perfect, "
|
| 544 |
+
"see https://github.com/asweigart/pyperclip/issues/55",
|
| 545 |
+
stacklevel=find_stack_level(),
|
| 546 |
+
)
|
| 547 |
+
return init_dev_clipboard_clipboard()
|
| 548 |
+
|
| 549 |
+
# Setup for the WINDOWS platform:
|
| 550 |
+
elif os.name == "nt" or platform.system() == "Windows":
|
| 551 |
+
return init_windows_clipboard()
|
| 552 |
+
|
| 553 |
+
if platform.system() == "Linux":
|
| 554 |
+
if _executable_exists("wslconfig.exe"):
|
| 555 |
+
return init_wsl_clipboard()
|
| 556 |
+
|
| 557 |
+
# Setup for the macOS platform:
|
| 558 |
+
if os.name == "mac" or platform.system() == "Darwin":
|
| 559 |
+
try:
|
| 560 |
+
import AppKit
|
| 561 |
+
import Foundation # check if pyobjc is installed
|
| 562 |
+
except ImportError:
|
| 563 |
+
return init_osx_pbcopy_clipboard()
|
| 564 |
+
else:
|
| 565 |
+
return init_osx_pyobjc_clipboard()
|
| 566 |
+
|
| 567 |
+
# Setup for the LINUX platform:
|
| 568 |
+
if HAS_DISPLAY:
|
| 569 |
+
if os.environ.get("WAYLAND_DISPLAY") and _executable_exists("wl-copy"):
|
| 570 |
+
return init_wl_clipboard()
|
| 571 |
+
if _executable_exists("xsel"):
|
| 572 |
+
return init_xsel_clipboard()
|
| 573 |
+
if _executable_exists("xclip"):
|
| 574 |
+
return init_xclip_clipboard()
|
| 575 |
+
if _executable_exists("klipper") and _executable_exists("qdbus"):
|
| 576 |
+
return init_klipper_clipboard()
|
| 577 |
+
|
| 578 |
+
try:
|
| 579 |
+
# qtpy is a small abstraction layer that lets you write applications
|
| 580 |
+
# using a single api call to either PyQt or PySide.
|
| 581 |
+
# https://pypi.python.org/project/QtPy
|
| 582 |
+
import qtpy # check if qtpy is installed
|
| 583 |
+
except ImportError:
|
| 584 |
+
# If qtpy isn't installed, fall back on importing PyQt4.
|
| 585 |
+
try:
|
| 586 |
+
import PyQt5 # check if PyQt5 is installed
|
| 587 |
+
except ImportError:
|
| 588 |
+
try:
|
| 589 |
+
import PyQt4 # check if PyQt4 is installed
|
| 590 |
+
except ImportError:
|
| 591 |
+
pass # We want to fail fast for all non-ImportError exceptions.
|
| 592 |
+
else:
|
| 593 |
+
return init_qt_clipboard()
|
| 594 |
+
else:
|
| 595 |
+
return init_qt_clipboard()
|
| 596 |
+
else:
|
| 597 |
+
return init_qt_clipboard()
|
| 598 |
+
|
| 599 |
+
return init_no_clipboard()
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def set_clipboard(clipboard):
|
| 603 |
+
"""
|
| 604 |
+
Explicitly sets the clipboard mechanism. The "clipboard mechanism" is how
|
| 605 |
+
the copy() and paste() functions interact with the operating system to
|
| 606 |
+
implement the copy/paste feature. The clipboard parameter must be one of:
|
| 607 |
+
- pbcopy
|
| 608 |
+
- pyobjc (default on macOS)
|
| 609 |
+
- qt
|
| 610 |
+
- xclip
|
| 611 |
+
- xsel
|
| 612 |
+
- klipper
|
| 613 |
+
- windows (default on Windows)
|
| 614 |
+
- no (this is what is set when no clipboard mechanism can be found)
|
| 615 |
+
"""
|
| 616 |
+
global copy, paste
|
| 617 |
+
|
| 618 |
+
clipboard_types = {
|
| 619 |
+
"pbcopy": init_osx_pbcopy_clipboard,
|
| 620 |
+
"pyobjc": init_osx_pyobjc_clipboard,
|
| 621 |
+
"qt": init_qt_clipboard, # TODO - split this into 'qtpy', 'pyqt4', and 'pyqt5'
|
| 622 |
+
"xclip": init_xclip_clipboard,
|
| 623 |
+
"xsel": init_xsel_clipboard,
|
| 624 |
+
"wl-clipboard": init_wl_clipboard,
|
| 625 |
+
"klipper": init_klipper_clipboard,
|
| 626 |
+
"windows": init_windows_clipboard,
|
| 627 |
+
"no": init_no_clipboard,
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
if clipboard not in clipboard_types:
|
| 631 |
+
allowed_clipboard_types = [repr(_) for _ in clipboard_types]
|
| 632 |
+
raise ValueError(
|
| 633 |
+
f"Argument must be one of {', '.join(allowed_clipboard_types)}"
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
# Sets pyperclip's copy() and paste() functions:
|
| 637 |
+
copy, paste = clipboard_types[clipboard]()
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def lazy_load_stub_copy(text):
|
| 641 |
+
"""
|
| 642 |
+
A stub function for copy(), which will load the real copy() function when
|
| 643 |
+
called so that the real copy() function is used for later calls.
|
| 644 |
+
|
| 645 |
+
This allows users to import pyperclip without having determine_clipboard()
|
| 646 |
+
automatically run, which will automatically select a clipboard mechanism.
|
| 647 |
+
This could be a problem if it selects, say, the memory-heavy PyQt4 module
|
| 648 |
+
but the user was just going to immediately call set_clipboard() to use a
|
| 649 |
+
different clipboard mechanism.
|
| 650 |
+
|
| 651 |
+
The lazy loading this stub function implements gives the user a chance to
|
| 652 |
+
call set_clipboard() to pick another clipboard mechanism. Or, if the user
|
| 653 |
+
simply calls copy() or paste() without calling set_clipboard() first,
|
| 654 |
+
will fall back on whatever clipboard mechanism that determine_clipboard()
|
| 655 |
+
automatically chooses.
|
| 656 |
+
"""
|
| 657 |
+
global copy, paste
|
| 658 |
+
copy, paste = determine_clipboard()
|
| 659 |
+
return copy(text)
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def lazy_load_stub_paste():
|
| 663 |
+
"""
|
| 664 |
+
A stub function for paste(), which will load the real paste() function when
|
| 665 |
+
called so that the real paste() function is used for later calls.
|
| 666 |
+
|
| 667 |
+
This allows users to import pyperclip without having determine_clipboard()
|
| 668 |
+
automatically run, which will automatically select a clipboard mechanism.
|
| 669 |
+
This could be a problem if it selects, say, the memory-heavy PyQt4 module
|
| 670 |
+
but the user was just going to immediately call set_clipboard() to use a
|
| 671 |
+
different clipboard mechanism.
|
| 672 |
+
|
| 673 |
+
The lazy loading this stub function implements gives the user a chance to
|
| 674 |
+
call set_clipboard() to pick another clipboard mechanism. Or, if the user
|
| 675 |
+
simply calls copy() or paste() without calling set_clipboard() first,
|
| 676 |
+
will fall back on whatever clipboard mechanism that determine_clipboard()
|
| 677 |
+
automatically chooses.
|
| 678 |
+
"""
|
| 679 |
+
global copy, paste
|
| 680 |
+
copy, paste = determine_clipboard()
|
| 681 |
+
return paste()
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def is_available() -> bool:
|
| 685 |
+
return copy != lazy_load_stub_copy and paste != lazy_load_stub_paste
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
# Initially, copy() and paste() are set to lazy loading wrappers which will
|
| 689 |
+
# set `copy` and `paste` to real functions the first time they're used, unless
|
| 690 |
+
# set_clipboard() or determine_clipboard() is called first.
|
| 691 |
+
copy, paste = lazy_load_stub_copy, lazy_load_stub_paste
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def waitForPaste(timeout=None):
|
| 695 |
+
"""This function call blocks until a non-empty text string exists on the
|
| 696 |
+
clipboard. It returns this text.
|
| 697 |
+
|
| 698 |
+
This function raises PyperclipTimeoutException if timeout was set to
|
| 699 |
+
a number of seconds that has elapsed without non-empty text being put on
|
| 700 |
+
the clipboard."""
|
| 701 |
+
startTime = time.time()
|
| 702 |
+
while True:
|
| 703 |
+
clipboardText = paste()
|
| 704 |
+
if clipboardText != "":
|
| 705 |
+
return clipboardText
|
| 706 |
+
time.sleep(0.01)
|
| 707 |
+
|
| 708 |
+
if timeout is not None and time.time() > startTime + timeout:
|
| 709 |
+
raise PyperclipTimeoutException(
|
| 710 |
+
"waitForPaste() timed out after " + str(timeout) + " seconds."
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def waitForNewPaste(timeout=None):
|
| 715 |
+
"""This function call blocks until a new text string exists on the
|
| 716 |
+
clipboard that is different from the text that was there when the function
|
| 717 |
+
was first called. It returns this text.
|
| 718 |
+
|
| 719 |
+
This function raises PyperclipTimeoutException if timeout was set to
|
| 720 |
+
a number of seconds that has elapsed without non-empty text being put on
|
| 721 |
+
the clipboard."""
|
| 722 |
+
startTime = time.time()
|
| 723 |
+
originalText = paste()
|
| 724 |
+
while True:
|
| 725 |
+
currentText = paste()
|
| 726 |
+
if currentText != originalText:
|
| 727 |
+
return currentText
|
| 728 |
+
time.sleep(0.01)
|
| 729 |
+
|
| 730 |
+
if timeout is not None and time.time() > startTime + timeout:
|
| 731 |
+
raise PyperclipTimeoutException(
|
| 732 |
+
"waitForNewPaste() timed out after " + str(timeout) + " seconds."
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
__all__ = [
|
| 737 |
+
"copy",
|
| 738 |
+
"paste",
|
| 739 |
+
"waitForPaste",
|
| 740 |
+
"waitForNewPaste",
|
| 741 |
+
"set_clipboard",
|
| 742 |
+
"determine_clipboard",
|
| 743 |
+
]
|
| 744 |
+
|
| 745 |
+
# pandas aliases
|
| 746 |
+
clipboard_get = paste
|
| 747 |
+
clipboard_set = copy
|
moondream/lib/python3.10/site-packages/pandas/io/clipboard/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (19.6 kB). View file
|
|
|
moondream/lib/python3.10/site-packages/pandas/io/parsers/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pandas.io.parsers.readers import (
|
| 2 |
+
TextFileReader,
|
| 3 |
+
TextParser,
|
| 4 |
+
read_csv,
|
| 5 |
+
read_fwf,
|
| 6 |
+
read_table,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
__all__ = ["TextFileReader", "TextParser", "read_csv", "read_fwf", "read_table"]
|
moondream/lib/python3.10/site-packages/pandas/io/parsers/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (335 Bytes). View file
|
|
|
moondream/lib/python3.10/site-packages/pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-310.pyc
ADDED
|
Binary file (7.98 kB). View file
|
|
|
moondream/lib/python3.10/site-packages/pandas/io/parsers/__pycache__/base_parser.cpython-310.pyc
ADDED
|
Binary file (33.6 kB). View file
|
|
|
moondream/lib/python3.10/site-packages/pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-310.pyc
ADDED
|
Binary file (9.55 kB). View file
|
|
|