content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
"""\ntest_insert is specifically for the DataFrame.insert method; not to be\nconfused with tests with "insert" in their names that are really testing\n__setitem__.\n"""\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import PerformanceWarning\n\nfrom pandas import (\n DataFrame,\n Index,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameInsert:\n def test_insert(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)),\n index=np.arange(5),\n columns=["c", "b", "a"],\n )\n\n df.insert(0, "foo", df["a"])\n tm.assert_index_equal(df.columns, Index(["foo", "c", "b", "a"]))\n tm.assert_series_equal(df["a"], df["foo"], check_names=False)\n\n df.insert(2, "bar", df["c"])\n tm.assert_index_equal(df.columns, Index(["foo", "c", "bar", "b", "a"]))\n tm.assert_almost_equal(df["c"], df["bar"], check_names=False)\n\n with pytest.raises(ValueError, match="already exists"):\n df.insert(1, "a", df["b"])\n\n msg = "cannot insert c, already exists"\n with pytest.raises(ValueError, match=msg):\n df.insert(1, "c", df["b"])\n\n df.columns.name = "some_name"\n # preserve columns name field\n df.insert(0, "baz", df["c"])\n assert df.columns.name == "some_name"\n\n def test_insert_column_bug_4032(self):\n # GH#4032, inserting a column and renaming causing errors\n df = DataFrame({"b": [1.1, 2.2]})\n\n df = df.rename(columns={})\n df.insert(0, "a", [1, 2])\n result = df.rename(columns={})\n\n expected = DataFrame([[1, 1.1], [2, 2.2]], columns=["a", "b"])\n tm.assert_frame_equal(result, expected)\n\n df.insert(0, "c", [1.3, 2.3])\n result = df.rename(columns={})\n\n expected = DataFrame([[1.3, 1, 1.1], [2.3, 2, 2.2]], columns=["c", "a", "b"])\n tm.assert_frame_equal(result, expected)\n\n def test_insert_with_columns_dups(self):\n # GH#14291\n df = DataFrame()\n df.insert(0, "A", ["g", "h", "i"], allow_duplicates=True)\n df.insert(0, "A", ["d", "e", "f"], allow_duplicates=True)\n df.insert(0, "A", ["a", "b", "c"], allow_duplicates=True)\n exp = DataFrame(\n [["a", "d", "g"], ["b", "e", "h"], ["c", "f", "i"]],\n columns=Index(["A", "A", "A"], dtype=object),\n )\n tm.assert_frame_equal(df, exp)\n\n def test_insert_item_cache(self, using_array_manager, using_copy_on_write):\n df = DataFrame(np.random.default_rng(2).standard_normal((4, 3)))\n ser = df[0]\n\n if using_array_manager:\n expected_warning = None\n else:\n # with BlockManager warn about high fragmentation of single dtype\n expected_warning = PerformanceWarning\n\n with tm.assert_produces_warning(expected_warning):\n for n in range(100):\n df[n + 3] = df[1] * n\n\n if using_copy_on_write:\n ser.iloc[0] = 99\n assert df.iloc[0, 0] == df[0][0]\n assert df.iloc[0, 0] != 99\n else:\n ser.values[0] = 99\n assert df.iloc[0, 0] == df[0][0]\n assert df.iloc[0, 0] == 99\n\n def test_insert_EA_no_warning(self):\n # PerformanceWarning about fragmented frame should not be raised when\n # using EAs (https://github.com/pandas-dev/pandas/issues/44098)\n df = DataFrame(\n np.random.default_rng(2).integers(0, 100, size=(3, 100)), dtype="Int64"\n )\n with tm.assert_produces_warning(None):\n df["a"] = np.array([1, 2, 3])\n\n def test_insert_frame(self):\n # GH#42403\n df = DataFrame({"col1": [1, 2], "col2": [3, 4]})\n\n msg = (\n "Expected a one-dimensional object, got a DataFrame with 2 columns instead."\n )\n with pytest.raises(ValueError, match=msg):\n df.insert(1, "newcol", df)\n\n def test_insert_int64_loc(self):\n # GH#53193\n df = DataFrame({"a": [1, 2]})\n df.insert(np.int64(0), "b", 0)\n tm.assert_frame_equal(df, DataFrame({"b": [0, 0], "a": [1, 2]}))\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\test_insert.py
test_insert.py
Python
4,108
0.95
0.099174
0.081633
vue-tools
935
2024-03-18T14:17:54.270388
GPL-3.0
true
c44cb6fe986f50b65ebd07fa6c104c85
"""\nTests for DataFrame.mask; tests DataFrame.where as a side-effect.\n"""\n\nimport numpy as np\n\nfrom pandas import (\n NA,\n DataFrame,\n Float64Dtype,\n Series,\n StringDtype,\n Timedelta,\n isna,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameMask:\n def test_mask(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))\n cond = df > 0\n\n rs = df.where(cond, np.nan)\n tm.assert_frame_equal(rs, df.mask(df <= 0))\n tm.assert_frame_equal(rs, df.mask(~cond))\n\n other = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))\n rs = df.where(cond, other)\n tm.assert_frame_equal(rs, df.mask(df <= 0, other))\n tm.assert_frame_equal(rs, df.mask(~cond, other))\n\n def test_mask2(self):\n # see GH#21891\n df = DataFrame([1, 2])\n res = df.mask([[True], [False]])\n\n exp = DataFrame([np.nan, 2])\n tm.assert_frame_equal(res, exp)\n\n def test_mask_inplace(self):\n # GH#8801\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))\n cond = df > 0\n\n rdf = df.copy()\n\n return_value = rdf.where(cond, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(rdf, df.where(cond))\n tm.assert_frame_equal(rdf, df.mask(~cond))\n\n rdf = df.copy()\n return_value = rdf.where(cond, -df, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(rdf, df.where(cond, -df))\n tm.assert_frame_equal(rdf, df.mask(~cond, -df))\n\n def test_mask_edge_case_1xN_frame(self):\n # GH#4071\n df = DataFrame([[1, 2]])\n res = df.mask(DataFrame([[True, False]]))\n expec = DataFrame([[np.nan, 2]])\n tm.assert_frame_equal(res, expec)\n\n def test_mask_callable(self):\n # GH#12533\n df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n result = df.mask(lambda x: x > 4, lambda x: x + 1)\n exp = DataFrame([[1, 2, 3], [4, 6, 7], [8, 9, 10]])\n tm.assert_frame_equal(result, exp)\n tm.assert_frame_equal(result, df.mask(df > 4, df + 1))\n\n # return ndarray and scalar\n result = df.mask(lambda x: (x % 2 == 0).values, lambda x: 99)\n exp = DataFrame([[1, 99, 3], [99, 5, 99], [7, 99, 9]])\n tm.assert_frame_equal(result, exp)\n tm.assert_frame_equal(result, df.mask(df % 2 == 0, 99))\n\n # chain\n result = (df + 2).mask(lambda x: x > 8, lambda x: x + 10)\n exp = DataFrame([[3, 4, 5], [6, 7, 8], [19, 20, 21]])\n tm.assert_frame_equal(result, exp)\n tm.assert_frame_equal(result, (df + 2).mask((df + 2) > 8, (df + 2) + 10))\n\n def test_mask_dtype_bool_conversion(self):\n # GH#3733\n df = DataFrame(data=np.random.default_rng(2).standard_normal((100, 50)))\n df = df.where(df > 0) # create nans\n bools = df > 0\n mask = isna(df)\n expected = bools.astype(object).mask(mask)\n result = bools.mask(mask)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_mask_stringdtype(frame_or_series):\n # GH 40824\n obj = DataFrame(\n {"A": ["foo", "bar", "baz", NA]},\n index=["id1", "id2", "id3", "id4"],\n dtype=StringDtype(),\n )\n filtered_obj = DataFrame(\n {"A": ["this", "that"]}, index=["id2", "id3"], dtype=StringDtype()\n )\n expected = DataFrame(\n {"A": [NA, "this", "that", NA]},\n index=["id1", "id2", "id3", "id4"],\n dtype=StringDtype(),\n )\n if frame_or_series is Series:\n obj = obj["A"]\n filtered_obj = filtered_obj["A"]\n expected = expected["A"]\n\n filter_ser = Series([False, True, True, False])\n result = obj.mask(filter_ser, filtered_obj)\n\n tm.assert_equal(result, expected)\n\n\ndef test_mask_where_dtype_timedelta():\n # https://github.com/pandas-dev/pandas/issues/39548\n df = DataFrame([Timedelta(i, unit="d") for i in range(5)])\n\n expected = DataFrame(np.full(5, np.nan, dtype="timedelta64[ns]"))\n tm.assert_frame_equal(df.mask(df.notna()), expected)\n\n expected = DataFrame(\n [np.nan, np.nan, np.nan, Timedelta("3 day"), Timedelta("4 day")]\n )\n tm.assert_frame_equal(df.where(df > Timedelta(2, unit="d")), expected)\n\n\ndef test_mask_return_dtype():\n # GH#50488\n ser = Series([0.0, 1.0, 2.0, 3.0], dtype=Float64Dtype())\n cond = ~ser.isna()\n other = Series([True, False, True, False])\n excepted = Series([1.0, 0.0, 1.0, 0.0], dtype=ser.dtype)\n result = ser.mask(cond, other)\n tm.assert_series_equal(result, excepted)\n\n\ndef test_mask_inplace_no_other():\n # GH#51685\n df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]})\n cond = DataFrame({"a": [True, False], "b": [False, True]})\n df.mask(cond, inplace=True)\n expected = DataFrame({"a": [np.nan, 2], "b": ["x", np.nan]})\n tm.assert_frame_equal(df, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\test_mask.py
test_mask.py
Python
4,862
0.95
0.092105
0.089431
python-kit
721
2024-05-09T22:21:50.793500
MIT
true
1fb020e6e8368a2013947d6d215c124f
from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nfrom pandas.core.dtypes.base import _registry as ea_registry\nfrom pandas.core.dtypes.common import is_object_dtype\nfrom pandas.core.dtypes.dtypes import (\n CategoricalDtype,\n DatetimeTZDtype,\n IntervalDtype,\n PeriodDtype,\n)\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n DatetimeIndex,\n Index,\n Interval,\n IntervalIndex,\n MultiIndex,\n NaT,\n Period,\n PeriodIndex,\n Series,\n Timestamp,\n cut,\n date_range,\n notna,\n period_range,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import SparseArray\n\nfrom pandas.tseries.offsets import BDay\n\n\nclass TestDataFrameSetItem:\n def test_setitem_str_subclass(self):\n # GH#37366\n class mystring(str):\n pass\n\n data = ["2020-10-22 01:21:00+00:00"]\n index = DatetimeIndex(data)\n df = DataFrame({"a": [1]}, index=index)\n df["b"] = 2\n df[mystring("c")] = 3\n expected = DataFrame({"a": [1], "b": [2], mystring("c"): [3]}, index=index)\n tm.assert_equal(df, expected)\n\n @pytest.mark.parametrize(\n "dtype", ["int32", "int64", "uint32", "uint64", "float32", "float64"]\n )\n def test_setitem_dtype(self, dtype, float_frame):\n # Use integers since casting negative floats to uints is undefined\n arr = np.random.default_rng(2).integers(1, 10, len(float_frame))\n\n float_frame[dtype] = np.array(arr, dtype=dtype)\n assert float_frame[dtype].dtype.name == dtype\n\n def test_setitem_list_not_dataframe(self, float_frame):\n data = np.random.default_rng(2).standard_normal((len(float_frame), 2))\n float_frame[["A", "B"]] = data\n tm.assert_almost_equal(float_frame[["A", "B"]].values, data)\n\n def test_setitem_error_msmgs(self):\n # GH 7432\n df = DataFrame(\n {"bar": [1, 2, 3], "baz": ["d", "e", "f"]},\n index=Index(["a", "b", "c"], name="foo"),\n )\n ser = Series(\n ["g", "h", "i", "j"],\n index=Index(["a", "b", "c", "a"], name="foo"),\n name="fiz",\n )\n msg = "cannot reindex on an axis with duplicate labels"\n with pytest.raises(ValueError, match=msg):\n df["newcol"] = ser\n\n # GH 4107, more descriptive error message\n df = DataFrame(\n np.random.default_rng(2).integers(0, 2, (4, 4)),\n columns=["a", "b", "c", "d"],\n )\n\n msg = "Cannot set a DataFrame with multiple columns to the single column gr"\n with pytest.raises(ValueError, match=msg):\n df["gr"] = df.groupby(["b", "c"]).count()\n\n # GH 55956, specific message for zero columns\n msg = "Cannot set a DataFrame without columns to the column gr"\n with pytest.raises(ValueError, match=msg):\n df["gr"] = DataFrame()\n\n def test_setitem_benchmark(self):\n # from the vb_suite/frame_methods/frame_insert_columns\n N = 10\n K = 5\n df = DataFrame(index=range(N))\n new_col = np.random.default_rng(2).standard_normal(N)\n for i in range(K):\n df[i] = new_col\n expected = DataFrame(np.repeat(new_col, K).reshape(N, K), index=range(N))\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_different_dtype(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)),\n index=np.arange(5),\n columns=["c", "b", "a"],\n )\n df.insert(0, "foo", df["a"])\n df.insert(2, "bar", df["c"])\n\n # diff dtype\n\n # new item\n df["x"] = df["a"].astype("float32")\n result = df.dtypes\n expected = Series(\n [np.dtype("float64")] * 5 + [np.dtype("float32")],\n index=["foo", "c", "bar", "b", "a", "x"],\n )\n tm.assert_series_equal(result, expected)\n\n # replacing current (in different block)\n df["a"] = df["a"].astype("float32")\n result = df.dtypes\n expected = Series(\n [np.dtype("float64")] * 4 + [np.dtype("float32")] * 2,\n index=["foo", "c", "bar", "b", "a", "x"],\n )\n tm.assert_series_equal(result, expected)\n\n df["y"] = df["a"].astype("int32")\n result = df.dtypes\n expected = Series(\n [np.dtype("float64")] * 4 + [np.dtype("float32")] * 2 + [np.dtype("int32")],\n index=["foo", "c", "bar", "b", "a", "x", "y"],\n )\n tm.assert_series_equal(result, expected)\n\n def test_setitem_empty_columns(self):\n # GH 13522\n df = DataFrame(index=["A", "B", "C"])\n df["X"] = df.index\n df["X"] = ["x", "y", "z"]\n exp = DataFrame(\n data={"X": ["x", "y", "z"]},\n index=["A", "B", "C"],\n columns=Index(["X"], dtype=object),\n )\n tm.assert_frame_equal(df, exp)\n\n def test_setitem_dt64_index_empty_columns(self):\n rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s")\n df = DataFrame(index=np.arange(len(rng)))\n\n df["A"] = rng\n assert df["A"].dtype == np.dtype("M8[ns]")\n\n def test_setitem_timestamp_empty_columns(self):\n # GH#19843\n df = DataFrame(index=range(3))\n df["now"] = Timestamp("20130101", tz="UTC").as_unit("ns")\n\n expected = DataFrame(\n [[Timestamp("20130101", tz="UTC")]] * 3,\n index=range(3),\n columns=Index(["now"], dtype=object),\n )\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_wrong_length_categorical_dtype_raises(self):\n # GH#29523\n cat = Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"])\n df = DataFrame(range(10), columns=["bar"])\n\n msg = (\n rf"Length of values \({len(cat)}\) "\n rf"does not match length of index \({len(df)}\)"\n )\n with pytest.raises(ValueError, match=msg):\n df["foo"] = cat\n\n def test_setitem_with_sparse_value(self):\n # GH#8131\n df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]})\n sp_array = SparseArray([0, 0, 1])\n df["new_column"] = sp_array\n\n expected = Series(sp_array, name="new_column")\n tm.assert_series_equal(df["new_column"], expected)\n\n def test_setitem_with_unaligned_sparse_value(self):\n df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]})\n sp_series = Series(SparseArray([0, 0, 1]), index=[2, 1, 0])\n\n df["new_column"] = sp_series\n expected = Series(SparseArray([1, 0, 0]), name="new_column")\n tm.assert_series_equal(df["new_column"], expected)\n\n def test_setitem_period_preserves_dtype(self):\n # GH: 26861\n data = [Period("2003-12", "D")]\n result = DataFrame([])\n result["a"] = data\n\n expected = DataFrame({"a": data}, columns=Index(["a"], dtype=object))\n\n tm.assert_frame_equal(result, expected)\n\n def test_setitem_dict_preserves_dtypes(self):\n # https://github.com/pandas-dev/pandas/issues/34573\n expected = DataFrame(\n {\n "a": Series([0, 1, 2], dtype="int64"),\n "b": Series([1, 2, 3], dtype=float),\n "c": Series([1, 2, 3], dtype=float),\n "d": Series([1, 2, 3], dtype="uint32"),\n }\n )\n df = DataFrame(\n {\n "a": Series([], dtype="int64"),\n "b": Series([], dtype=float),\n "c": Series([], dtype=float),\n "d": Series([], dtype="uint32"),\n }\n )\n for idx, b in enumerate([1, 2, 3]):\n df.loc[df.shape[0]] = {\n "a": int(idx),\n "b": float(b),\n "c": float(b),\n "d": np.uint32(b),\n }\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize(\n "obj,dtype",\n [\n (Period("2020-01"), PeriodDtype("M")),\n (Interval(left=0, right=5), IntervalDtype("int64", "right")),\n (\n Timestamp("2011-01-01", tz="US/Eastern"),\n DatetimeTZDtype(unit="s", tz="US/Eastern"),\n ),\n ],\n )\n def test_setitem_extension_types(self, obj, dtype):\n # GH: 34832\n expected = DataFrame({"idx": [1, 2, 3], "obj": Series([obj] * 3, dtype=dtype)})\n\n df = DataFrame({"idx": [1, 2, 3]})\n df["obj"] = obj\n\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize(\n "ea_name",\n [\n dtype.name\n for dtype in ea_registry.dtypes\n # property would require instantiation\n if not isinstance(dtype.name, property)\n ]\n + ["datetime64[ns, UTC]", "period[D]"],\n )\n def test_setitem_with_ea_name(self, ea_name):\n # GH 38386\n result = DataFrame([0])\n result[ea_name] = [1]\n expected = DataFrame({0: [0], ea_name: [1]})\n tm.assert_frame_equal(result, expected)\n\n def test_setitem_dt64_ndarray_with_NaT_and_diff_time_units(self):\n # GH#7492\n data_ns = np.array([1, "nat"], dtype="datetime64[ns]")\n result = Series(data_ns).to_frame()\n result["new"] = data_ns\n expected = DataFrame({0: [1, None], "new": [1, None]}, dtype="datetime64[ns]")\n tm.assert_frame_equal(result, expected)\n\n # OutOfBoundsDatetime error shouldn't occur; as of 2.0 we preserve "M8[s]"\n data_s = np.array([1, "nat"], dtype="datetime64[s]")\n result["new"] = data_s\n tm.assert_series_equal(result[0], expected[0])\n tm.assert_numpy_array_equal(result["new"].to_numpy(), data_s)\n\n @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"])\n def test_frame_setitem_datetime64_col_other_units(self, unit):\n # Check that non-nano dt64 values get cast to dt64 on setitem\n # into a not-yet-existing column\n n = 100\n\n dtype = np.dtype(f"M8[{unit}]")\n vals = np.arange(n, dtype=np.int64).view(dtype)\n if unit in ["s", "ms"]:\n # supported unit\n ex_vals = vals\n else:\n # we get the nearest supported units, i.e. "s"\n ex_vals = vals.astype("datetime64[s]")\n\n df = DataFrame({"ints": np.arange(n)}, index=np.arange(n))\n df[unit] = vals\n\n assert df[unit].dtype == ex_vals.dtype\n assert (df[unit].values == ex_vals).all()\n\n @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"])\n def test_frame_setitem_existing_datetime64_col_other_units(self, unit):\n # Check that non-nano dt64 values get cast to dt64 on setitem\n # into an already-existing dt64 column\n n = 100\n\n dtype = np.dtype(f"M8[{unit}]")\n vals = np.arange(n, dtype=np.int64).view(dtype)\n ex_vals = vals.astype("datetime64[ns]")\n\n df = DataFrame({"ints": np.arange(n)}, index=np.arange(n))\n df["dates"] = np.arange(n, dtype=np.int64).view("M8[ns]")\n\n # We overwrite existing dt64 column with new, non-nano dt64 vals\n df["dates"] = vals\n assert (df["dates"].values == ex_vals).all()\n\n def test_setitem_dt64tz(self, timezone_frame, using_copy_on_write):\n df = timezone_frame\n idx = df["B"].rename("foo")\n\n # setitem\n df["C"] = idx\n tm.assert_series_equal(df["C"], Series(idx, name="C"))\n\n df["D"] = "foo"\n df["D"] = idx\n tm.assert_series_equal(df["D"], Series(idx, name="D"))\n del df["D"]\n\n # assert that A & C are not sharing the same base (e.g. they\n # are copies)\n # Note: This does not hold with Copy on Write (because of lazy copying)\n v1 = df._mgr.arrays[1]\n v2 = df._mgr.arrays[2]\n tm.assert_extension_array_equal(v1, v2)\n v1base = v1._ndarray.base\n v2base = v2._ndarray.base\n if not using_copy_on_write:\n assert v1base is None or (id(v1base) != id(v2base))\n else:\n assert id(v1base) == id(v2base)\n\n # with nan\n df2 = df.copy()\n df2.iloc[1, 1] = NaT\n df2.iloc[1, 2] = NaT\n result = df2["B"]\n tm.assert_series_equal(notna(result), Series([True, False, True], name="B"))\n tm.assert_series_equal(df2.dtypes, df.dtypes)\n\n def test_setitem_periodindex(self):\n rng = period_range("1/1/2000", periods=5, name="index")\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)), index=rng)\n\n df["Index"] = rng\n rs = Index(df["Index"])\n tm.assert_index_equal(rs, rng, check_names=False)\n assert rs.name == "Index"\n assert rng.name == "index"\n\n rs = df.reset_index().set_index("index")\n assert isinstance(rs.index, PeriodIndex)\n tm.assert_index_equal(rs.index, rng)\n\n def test_setitem_complete_column_with_array(self):\n # GH#37954\n df = DataFrame({"a": ["one", "two", "three"], "b": [1, 2, 3]})\n arr = np.array([[1, 1], [3, 1], [5, 1]])\n df[["c", "d"]] = arr\n expected = DataFrame(\n {\n "a": ["one", "two", "three"],\n "b": [1, 2, 3],\n "c": [1, 3, 5],\n "d": [1, 1, 1],\n }\n )\n expected["c"] = expected["c"].astype(arr.dtype)\n expected["d"] = expected["d"].astype(arr.dtype)\n assert expected["c"].dtype == arr.dtype\n assert expected["d"].dtype == arr.dtype\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_period_d_dtype(self):\n # GH 39763\n rng = period_range("2016-01-01", periods=9, freq="D", name="A")\n result = DataFrame(rng)\n expected = DataFrame(\n {"A": ["NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT"]},\n dtype="period[D]",\n )\n result.iloc[:] = rng._na_value\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("dtype", ["f8", "i8", "u8"])\n def test_setitem_bool_with_numeric_index(self, dtype):\n # GH#36319\n cols = Index([1, 2, 3], dtype=dtype)\n df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)), columns=cols)\n\n df[False] = ["a", "b", "c"]\n\n expected_cols = Index([1, 2, 3, False], dtype=object)\n if dtype == "f8":\n expected_cols = Index([1.0, 2.0, 3.0, False], dtype=object)\n\n tm.assert_index_equal(df.columns, expected_cols)\n\n @pytest.mark.parametrize("indexer", ["B", ["B"]])\n def test_setitem_frame_length_0_str_key(self, indexer):\n # GH#38831\n df = DataFrame(columns=["A", "B"])\n other = DataFrame({"B": [1, 2]})\n df[indexer] = other\n expected = DataFrame({"A": [np.nan] * 2, "B": [1, 2]})\n expected["A"] = expected["A"].astype("object")\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_frame_duplicate_columns(self):\n # GH#15695\n cols = ["A", "B", "C"] * 2\n df = DataFrame(index=range(3), columns=cols)\n df.loc[0, "A"] = (0, 3)\n df.loc[:, "B"] = (1, 4)\n df["C"] = (2, 5)\n expected = DataFrame(\n [\n [0, 1, 2, 3, 4, 5],\n [np.nan, 1, 2, np.nan, 4, 5],\n [np.nan, 1, 2, np.nan, 4, 5],\n ],\n dtype="object",\n )\n\n # set these with unique columns to be extra-unambiguous\n expected[2] = expected[2].astype(np.int64)\n expected[5] = expected[5].astype(np.int64)\n expected.columns = cols\n\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_frame_duplicate_columns_size_mismatch(self):\n # GH#39510\n cols = ["A", "B", "C"] * 2\n df = DataFrame(index=range(3), columns=cols)\n with pytest.raises(ValueError, match="Columns must be same length as key"):\n df[["A"]] = (0, 3, 5)\n\n df2 = df.iloc[:, :3] # unique columns\n with pytest.raises(ValueError, match="Columns must be same length as key"):\n df2[["A"]] = (0, 3, 5)\n\n @pytest.mark.parametrize("cols", [["a", "b", "c"], ["a", "a", "a"]])\n def test_setitem_df_wrong_column_number(self, cols):\n # GH#38604\n df = DataFrame([[1, 2, 3]], columns=cols)\n rhs = DataFrame([[10, 11]], columns=["d", "e"])\n msg = "Columns must be same length as key"\n with pytest.raises(ValueError, match=msg):\n df["a"] = rhs\n\n def test_setitem_listlike_indexer_duplicate_columns(self):\n # GH#38604\n df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"])\n rhs = DataFrame([[10, 11, 12]], columns=["a", "b", "b"])\n df[["a", "b"]] = rhs\n expected = DataFrame([[10, 11, 12]], columns=["a", "b", "b"])\n tm.assert_frame_equal(df, expected)\n\n df[["c", "b"]] = rhs\n expected = DataFrame([[10, 11, 12, 10]], columns=["a", "b", "b", "c"])\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_listlike_indexer_duplicate_columns_not_equal_length(self):\n # GH#39403\n df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"])\n rhs = DataFrame([[10, 11]], columns=["a", "b"])\n msg = "Columns must be same length as key"\n with pytest.raises(ValueError, match=msg):\n df[["a", "b"]] = rhs\n\n def test_setitem_intervals(self):\n df = DataFrame({"A": range(10)})\n ser = cut(df["A"], 5)\n assert isinstance(ser.cat.categories, IntervalIndex)\n\n # B & D end up as Categoricals\n # the remainder are converted to in-line objects\n # containing an IntervalIndex.values\n df["B"] = ser\n df["C"] = np.array(ser)\n df["D"] = ser.values\n df["E"] = np.array(ser.values)\n df["F"] = ser.astype(object)\n\n assert isinstance(df["B"].dtype, CategoricalDtype)\n assert isinstance(df["B"].cat.categories.dtype, IntervalDtype)\n assert isinstance(df["D"].dtype, CategoricalDtype)\n assert isinstance(df["D"].cat.categories.dtype, IntervalDtype)\n\n # These go through the Series constructor and so get inferred back\n # to IntervalDtype\n assert isinstance(df["C"].dtype, IntervalDtype)\n assert isinstance(df["E"].dtype, IntervalDtype)\n\n # But the Series constructor doesn't do inference on Series objects,\n # so setting df["F"] doesn't get cast back to IntervalDtype\n assert is_object_dtype(df["F"])\n\n # they compare equal as Index\n # when converted to numpy objects\n c = lambda x: Index(np.array(x))\n tm.assert_index_equal(c(df.B), c(df.B))\n tm.assert_index_equal(c(df.B), c(df.C), check_names=False)\n tm.assert_index_equal(c(df.B), c(df.D), check_names=False)\n tm.assert_index_equal(c(df.C), c(df.D), check_names=False)\n\n # B & D are the same Series\n tm.assert_series_equal(df["B"], df["B"])\n tm.assert_series_equal(df["B"], df["D"], check_names=False)\n\n # C & E are the same Series\n tm.assert_series_equal(df["C"], df["C"])\n tm.assert_series_equal(df["C"], df["E"], check_names=False)\n\n def test_setitem_categorical(self):\n # GH#35369\n df = DataFrame({"h": Series(list("mn")).astype("category")})\n df.h = df.h.cat.reorder_categories(["n", "m"])\n expected = DataFrame(\n {"h": Categorical(["m", "n"]).reorder_categories(["n", "m"])}\n )\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_with_empty_listlike(self):\n # GH#17101\n index = Index([], name="idx")\n result = DataFrame(columns=["A"], index=index)\n result["A"] = []\n expected = DataFrame(columns=["A"], index=index)\n tm.assert_index_equal(result.index, expected.index)\n\n @pytest.mark.parametrize(\n "cols, values, expected",\n [\n (["C", "D", "D", "a"], [1, 2, 3, 4], 4), # with duplicates\n (["D", "C", "D", "a"], [1, 2, 3, 4], 4), # mixed order\n (["C", "B", "B", "a"], [1, 2, 3, 4], 4), # other duplicate cols\n (["C", "B", "a"], [1, 2, 3], 3), # no duplicates\n (["B", "C", "a"], [3, 2, 1], 1), # alphabetical order\n (["C", "a", "B"], [3, 2, 1], 2), # in the middle\n ],\n )\n def test_setitem_same_column(self, cols, values, expected):\n # GH#23239\n df = DataFrame([values], columns=cols)\n df["a"] = df["a"]\n result = df["a"].values[0]\n assert result == expected\n\n def test_setitem_multi_index(self):\n # GH#7655, test that assigning to a sub-frame of a frame\n # with multi-index columns aligns both rows and columns\n it = ["jim", "joe", "jolie"], ["first", "last"], ["left", "center", "right"]\n\n cols = MultiIndex.from_product(it)\n index = date_range("20141006", periods=20)\n vals = np.random.default_rng(2).integers(1, 1000, (len(index), len(cols)))\n df = DataFrame(vals, columns=cols, index=index)\n\n i, j = df.index.values.copy(), it[-1][:]\n\n np.random.default_rng(2).shuffle(i)\n df["jim"] = df["jolie"].loc[i, ::-1]\n tm.assert_frame_equal(df["jim"], df["jolie"])\n\n np.random.default_rng(2).shuffle(j)\n df[("joe", "first")] = df[("jolie", "last")].loc[i, j]\n tm.assert_frame_equal(df[("joe", "first")], df[("jolie", "last")])\n\n np.random.default_rng(2).shuffle(j)\n df[("joe", "last")] = df[("jolie", "first")].loc[i, j]\n tm.assert_frame_equal(df[("joe", "last")], df[("jolie", "first")])\n\n @pytest.mark.parametrize(\n "columns,box,expected",\n [\n (\n ["A", "B", "C", "D"],\n 7,\n DataFrame(\n [[7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7]],\n columns=["A", "B", "C", "D"],\n ),\n ),\n (\n ["C", "D"],\n [7, 8],\n DataFrame(\n [[1, 2, 7, 8], [3, 4, 7, 8], [5, 6, 7, 8]],\n columns=["A", "B", "C", "D"],\n ),\n ),\n (\n ["A", "B", "C"],\n np.array([7, 8, 9], dtype=np.int64),\n DataFrame([[7, 8, 9], [7, 8, 9], [7, 8, 9]], columns=["A", "B", "C"]),\n ),\n (\n ["B", "C", "D"],\n [[7, 8, 9], [10, 11, 12], [13, 14, 15]],\n DataFrame(\n [[1, 7, 8, 9], [3, 10, 11, 12], [5, 13, 14, 15]],\n columns=["A", "B", "C", "D"],\n ),\n ),\n (\n ["C", "A", "D"],\n np.array([[7, 8, 9], [10, 11, 12], [13, 14, 15]], dtype=np.int64),\n DataFrame(\n [[8, 2, 7, 9], [11, 4, 10, 12], [14, 6, 13, 15]],\n columns=["A", "B", "C", "D"],\n ),\n ),\n (\n ["A", "C"],\n DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]),\n DataFrame(\n [[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"]\n ),\n ),\n ],\n )\n def test_setitem_list_missing_columns(self, columns, box, expected):\n # GH#29334\n df = DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"])\n df[columns] = box\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_list_of_tuples(self, float_frame):\n tuples = list(zip(float_frame["A"], float_frame["B"]))\n float_frame["tuples"] = tuples\n\n result = float_frame["tuples"]\n expected = Series(tuples, index=float_frame.index, name="tuples")\n tm.assert_series_equal(result, expected)\n\n def test_setitem_iloc_generator(self):\n # GH#39614\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n indexer = (x for x in [1, 2])\n df.iloc[indexer] = 1\n expected = DataFrame({"a": [1, 1, 1], "b": [4, 1, 1]})\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_iloc_two_dimensional_generator(self):\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n indexer = (x for x in [1, 2])\n df.iloc[indexer, 1] = 1\n expected = DataFrame({"a": [1, 2, 3], "b": [4, 1, 1]})\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_dtypes_bytes_type_to_object(self):\n # GH 20734\n index = Series(name="id", dtype="S24")\n df = DataFrame(index=index, columns=Index([], dtype="str"))\n df["a"] = Series(name="a", index=index, dtype=np.uint32)\n df["b"] = Series(name="b", index=index, dtype="S64")\n df["c"] = Series(name="c", index=index, dtype="S64")\n df["d"] = Series(name="d", index=index, dtype=np.uint8)\n result = df.dtypes\n expected = Series([np.uint32, object, object, np.uint8], index=list("abcd"))\n tm.assert_series_equal(result, expected)\n\n def test_boolean_mask_nullable_int64(self):\n # GH 28928\n result = DataFrame({"a": [3, 4], "b": [5, 6]}).astype(\n {"a": "int64", "b": "Int64"}\n )\n mask = Series(False, index=result.index)\n result.loc[mask, "a"] = result["a"]\n result.loc[mask, "b"] = result["b"]\n expected = DataFrame({"a": [3, 4], "b": [5, 6]}).astype(\n {"a": "int64", "b": "Int64"}\n )\n tm.assert_frame_equal(result, expected)\n\n def test_setitem_ea_dtype_rhs_series(self):\n # GH#47425\n df = DataFrame({"a": [1, 2]})\n df["a"] = Series([1, 2], dtype="Int64")\n expected = DataFrame({"a": [1, 2]}, dtype="Int64")\n tm.assert_frame_equal(df, expected)\n\n # TODO(ArrayManager) set column with 2d column array, see #44788\n @td.skip_array_manager_not_yet_implemented\n def test_setitem_npmatrix_2d(self):\n # GH#42376\n # for use-case df["x"] = sparse.random((10, 10)).mean(axis=1)\n expected = DataFrame(\n {"np-array": np.ones(10), "np-matrix": np.ones(10)}, index=np.arange(10)\n )\n\n a = np.ones((10, 1))\n df = DataFrame(index=np.arange(10), columns=Index([], dtype="str"))\n df["np-array"] = a\n\n # Instantiation of `np.matrix` gives PendingDeprecationWarning\n with tm.assert_produces_warning(PendingDeprecationWarning):\n df["np-matrix"] = np.matrix(a)\n\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize("vals", [{}, {"d": "a"}])\n def test_setitem_aligning_dict_with_index(self, vals):\n # GH#47216\n df = DataFrame({"a": [1, 2], "b": [3, 4], **vals})\n df.loc[:, "a"] = {1: 100, 0: 200}\n df.loc[:, "c"] = {0: 5, 1: 6}\n df.loc[:, "e"] = {1: 5}\n expected = DataFrame(\n {"a": [200, 100], "b": [3, 4], **vals, "c": [5, 6], "e": [np.nan, 5]}\n )\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_rhs_dataframe(self):\n # GH#47578\n df = DataFrame({"a": [1, 2]})\n df["a"] = DataFrame({"a": [10, 11]}, index=[1, 2])\n expected = DataFrame({"a": [np.nan, 10]})\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame({"a": [1, 2]})\n df.isetitem(0, DataFrame({"a": [10, 11]}, index=[1, 2]))\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_frame_overwrite_with_ea_dtype(self, any_numeric_ea_dtype):\n # GH#46896\n df = DataFrame(columns=["a", "b"], data=[[1, 2], [3, 4]])\n df["a"] = DataFrame({"a": [10, 11]}, dtype=any_numeric_ea_dtype)\n expected = DataFrame(\n {\n "a": Series([10, 11], dtype=any_numeric_ea_dtype),\n "b": [2, 4],\n }\n )\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_string_option_object_index(self):\n # GH#55638\n pytest.importorskip("pyarrow")\n df = DataFrame({"a": [1, 2]})\n with pd.option_context("future.infer_string", True):\n df["b"] = Index(["a", "b"], dtype=object)\n expected = DataFrame({"a": [1, 2], "b": Series(["a", "b"], dtype=object)})\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_frame_midx_columns(self):\n # GH#49121\n df = DataFrame({("a", "b"): [10]})\n expected = df.copy()\n col_name = ("a", "b")\n df[col_name] = df[[col_name]]\n tm.assert_frame_equal(df, expected)\n\n def test_loc_setitem_ea_dtype(self):\n # GH#55604\n df = DataFrame({"a": np.array([10], dtype="i8")})\n df.loc[:, "a"] = Series([11], dtype="Int64")\n expected = DataFrame({"a": np.array([11], dtype="i8")})\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame({"a": np.array([10], dtype="i8")})\n df.iloc[:, 0] = Series([11], dtype="Int64")\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_object_inferring(self):\n # GH#56102\n idx = Index([Timestamp("2019-12-31")], dtype=object)\n df = DataFrame({"a": [1]})\n with tm.assert_produces_warning(FutureWarning, match="infer"):\n df.loc[:, "b"] = idx\n with tm.assert_produces_warning(FutureWarning, match="infer"):\n df["c"] = idx\n\n expected = DataFrame(\n {\n "a": [1],\n "b": Series([Timestamp("2019-12-31")], dtype="datetime64[ns]"),\n "c": Series([Timestamp("2019-12-31")], dtype="datetime64[ns]"),\n }\n )\n tm.assert_frame_equal(df, expected)\n\n\nclass TestSetitemTZAwareValues:\n @pytest.fixture\n def idx(self):\n naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B")\n idx = naive.tz_localize("US/Pacific")\n return idx\n\n @pytest.fixture\n def expected(self, idx):\n expected = Series(np.array(idx.tolist(), dtype="object"), name="B")\n assert expected.dtype == idx.dtype\n return expected\n\n def test_setitem_dt64series(self, idx, expected):\n # convert to utc\n df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"])\n df["B"] = idx\n df["B"] = idx.to_series(index=[0, 1]).dt.tz_convert(None)\n\n result = df["B"]\n comp = Series(idx.tz_convert("UTC").tz_localize(None), name="B")\n tm.assert_series_equal(result, comp)\n\n def test_setitem_datetimeindex(self, idx, expected):\n # setting a DataFrame column with a tzaware DTI retains the dtype\n df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"])\n\n # assign to frame\n df["B"] = idx\n result = df["B"]\n tm.assert_series_equal(result, expected)\n\n def test_setitem_object_array_of_tzaware_datetimes(self, idx, expected):\n # setting a DataFrame column with a tzaware DTI retains the dtype\n df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"])\n\n # object array of datetimes with a tz\n df["B"] = idx.to_pydatetime()\n result = df["B"]\n tm.assert_series_equal(result, expected)\n\n\nclass TestDataFrameSetItemWithExpansion:\n def test_setitem_listlike_views(self, using_copy_on_write, warn_copy_on_write):\n # GH#38148\n df = DataFrame({"a": [1, 2, 3], "b": [4, 4, 6]})\n\n # get one column as a view of df\n ser = df["a"]\n\n # add columns with list-like indexer\n df[["c", "d"]] = np.array([[0.1, 0.2], [0.3, 0.4], [0.4, 0.5]])\n\n # edit in place the first column to check view semantics\n with tm.assert_cow_warning(warn_copy_on_write):\n df.iloc[0, 0] = 100\n\n if using_copy_on_write:\n expected = Series([1, 2, 3], name="a")\n else:\n expected = Series([100, 2, 3], name="a")\n tm.assert_series_equal(ser, expected)\n\n def test_setitem_string_column_numpy_dtype_raising(self):\n # GH#39010\n df = DataFrame([[1, 2], [3, 4]])\n df["0 - Name"] = [5, 6]\n expected = DataFrame([[1, 2, 5], [3, 4, 6]], columns=[0, 1, "0 - Name"])\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_empty_df_duplicate_columns(self, using_copy_on_write):\n # GH#38521\n df = DataFrame(columns=["a", "b", "b"], dtype="float64")\n df.loc[:, "a"] = list(range(2))\n expected = DataFrame(\n [[0, np.nan, np.nan], [1, np.nan, np.nan]], columns=["a", "b", "b"]\n )\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_with_expansion_categorical_dtype(self):\n # assignment\n df = DataFrame(\n {\n "value": np.array(\n np.random.default_rng(2).integers(0, 10000, 100), dtype="int32"\n )\n }\n )\n labels = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)])\n\n df = df.sort_values(by=["value"], ascending=True)\n ser = cut(df.value, range(0, 10500, 500), right=False, labels=labels)\n cat = ser.values\n\n # setting with a Categorical\n df["D"] = cat\n result = df.dtypes\n expected = Series(\n [np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False)],\n index=["value", "D"],\n )\n tm.assert_series_equal(result, expected)\n\n # setting with a Series\n df["E"] = ser\n result = df.dtypes\n expected = Series(\n [\n np.dtype("int32"),\n CategoricalDtype(categories=labels, ordered=False),\n CategoricalDtype(categories=labels, ordered=False),\n ],\n index=["value", "D", "E"],\n )\n tm.assert_series_equal(result, expected)\n\n result1 = df["D"]\n result2 = df["E"]\n tm.assert_categorical_equal(result1._mgr.array, cat)\n\n # sorting\n ser.name = "E"\n tm.assert_series_equal(result2.sort_index(), ser.sort_index())\n\n def test_setitem_scalars_no_index(self):\n # GH#16823 / GH#17894\n df = DataFrame()\n df["foo"] = 1\n expected = DataFrame(columns=Index(["foo"], dtype=object)).astype(np.int64)\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_newcol_tuple_key(self, float_frame):\n assert (\n "A",\n "B",\n ) not in float_frame.columns\n float_frame["A", "B"] = float_frame["A"]\n assert ("A", "B") in float_frame.columns\n\n result = float_frame["A", "B"]\n expected = float_frame["A"]\n tm.assert_series_equal(result, expected, check_names=False)\n\n def test_frame_setitem_newcol_timestamp(self):\n # GH#2155\n columns = date_range(start="1/1/2012", end="2/1/2012", freq=BDay())\n data = DataFrame(columns=columns, index=range(10))\n t = datetime(2012, 11, 1)\n ts = Timestamp(t)\n data[ts] = np.nan # works, mostly a smoke-test\n assert np.isnan(data[ts]).all()\n\n def test_frame_setitem_rangeindex_into_new_col(self):\n # GH#47128\n df = DataFrame({"a": ["a", "b"]})\n df["b"] = df.index\n df.loc[[False, True], "b"] = 100\n result = df.loc[[1], :]\n expected = DataFrame({"a": ["b"], "b": [100]}, index=[1])\n tm.assert_frame_equal(result, expected)\n\n def test_setitem_frame_keep_ea_dtype(self, any_numeric_ea_dtype):\n # GH#46896\n df = DataFrame(columns=["a", "b"], data=[[1, 2], [3, 4]])\n df["c"] = DataFrame({"a": [10, 11]}, dtype=any_numeric_ea_dtype)\n expected = DataFrame(\n {\n "a": [1, 3],\n "b": [2, 4],\n "c": Series([10, 11], dtype=any_numeric_ea_dtype),\n }\n )\n tm.assert_frame_equal(df, expected)\n\n def test_loc_expansion_with_timedelta_type(self):\n result = DataFrame(columns=list("abc"))\n result.loc[0] = {\n "a": pd.to_timedelta(5, unit="s"),\n "b": pd.to_timedelta(72, unit="s"),\n "c": "23",\n }\n expected = DataFrame(\n [[pd.Timedelta("0 days 00:00:05"), pd.Timedelta("0 days 00:01:12"), "23"]],\n index=Index([0]),\n columns=(["a", "b", "c"]),\n )\n tm.assert_frame_equal(result, expected)\n\n\nclass TestDataFrameSetItemSlicing:\n def test_setitem_slice_position(self):\n # GH#31469\n df = DataFrame(np.zeros((100, 1)))\n df[-4:] = 1\n arr = np.zeros((100, 1))\n arr[-4:] = 1\n expected = DataFrame(arr)\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])\n @pytest.mark.parametrize("box", [Series, np.array, list, pd.array])\n @pytest.mark.parametrize("n", [1, 2, 3])\n def test_setitem_slice_indexer_broadcasting_rhs(self, n, box, indexer):\n # GH#40440\n df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"])\n indexer(df)[1:] = box([10, 11, 12])\n expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"])\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize("box", [Series, np.array, list, pd.array])\n @pytest.mark.parametrize("n", [1, 2, 3])\n def test_setitem_list_indexer_broadcasting_rhs(self, n, box):\n # GH#40440\n df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"])\n df.iloc[list(range(1, n + 1))] = box([10, 11, 12])\n expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"])\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc])\n @pytest.mark.parametrize("box", [Series, np.array, list, pd.array])\n @pytest.mark.parametrize("n", [1, 2, 3])\n def test_setitem_slice_broadcasting_rhs_mixed_dtypes(self, n, box, indexer):\n # GH#40440\n df = DataFrame(\n [[1, 3, 5], ["x", "y", "z"]] + [[2, 4, 6]] * n, columns=["a", "b", "c"]\n )\n indexer(df)[1:] = box([10, 11, 12])\n expected = DataFrame(\n [[1, 3, 5]] + [[10, 11, 12]] * (n + 1),\n columns=["a", "b", "c"],\n dtype="object",\n )\n tm.assert_frame_equal(df, expected)\n\n\nclass TestDataFrameSetItemCallable:\n def test_setitem_callable(self):\n # GH#12533\n df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]})\n df[lambda x: "A"] = [11, 12, 13, 14]\n\n exp = DataFrame({"A": [11, 12, 13, 14], "B": [5, 6, 7, 8]})\n tm.assert_frame_equal(df, exp)\n\n def test_setitem_other_callable(self):\n # GH#13299\n def inc(x):\n return x + 1\n\n # Set dtype object straight away to avoid upcast when setting inc below\n df = DataFrame([[-1, 1], [1, -1]], dtype=object)\n df[df > 0] = inc\n\n expected = DataFrame([[-1, inc], [inc, -1]])\n tm.assert_frame_equal(df, expected)\n\n\nclass TestDataFrameSetItemBooleanMask:\n @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values\n @pytest.mark.parametrize(\n "mask_type",\n [lambda df: df > np.abs(df) / 2, lambda df: (df > np.abs(df) / 2).values],\n ids=["dataframe", "array"],\n )\n def test_setitem_boolean_mask(self, mask_type, float_frame):\n # Test for issue #18582\n df = float_frame.copy()\n mask = mask_type(df)\n\n # index with boolean mask\n result = df.copy()\n result[mask] = np.nan\n\n expected = df.values.copy()\n expected[np.array(mask)] = np.nan\n expected = DataFrame(expected, index=df.index, columns=df.columns)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.xfail(reason="Currently empty indexers are treated as all False")\n @pytest.mark.parametrize("box", [list, np.array, Series])\n def test_setitem_loc_empty_indexer_raises_with_non_empty_value(self, box):\n # GH#37672\n df = DataFrame({"a": ["a"], "b": [1], "c": [1]})\n if box == Series:\n indexer = box([], dtype="object")\n else:\n indexer = box([])\n msg = "Must have equal len keys and value when setting with an iterable"\n with pytest.raises(ValueError, match=msg):\n df.loc[indexer, ["b"]] = [1]\n\n @pytest.mark.parametrize("box", [list, np.array, Series])\n def test_setitem_loc_only_false_indexer_dtype_changed(self, box):\n # GH#37550\n # Dtype is only changed when value to set is a Series and indexer is\n # empty/bool all False\n df = DataFrame({"a": ["a"], "b": [1], "c": [1]})\n indexer = box([False])\n df.loc[indexer, ["b"]] = 10 - df["c"]\n expected = DataFrame({"a": ["a"], "b": [1], "c": [1]})\n tm.assert_frame_equal(df, expected)\n\n df.loc[indexer, ["b"]] = 9\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize("indexer", [tm.setitem, tm.loc])\n def test_setitem_boolean_mask_aligning(self, indexer):\n # GH#39931\n df = DataFrame({"a": [1, 4, 2, 3], "b": [5, 6, 7, 8]})\n expected = df.copy()\n mask = df["a"] >= 3\n indexer(df)[mask] = indexer(df)[mask].sort_values("a")\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_mask_categorical(self):\n # assign multiple rows (mixed values) (-> array) -> exp_multi_row\n # changed multiple rows\n cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"])\n idx2 = Index(["h", "i", "j", "k", "l", "m", "n"])\n values2 = [1, 1, 2, 2, 1, 1, 1]\n exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2)\n\n catsf = Categorical(\n ["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"]\n )\n idxf = Index(["h", "i", "j", "k", "l", "m", "n"])\n valuesf = [1, 1, 3, 3, 1, 1, 1]\n df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf)\n\n exp_fancy = exp_multi_row.copy()\n exp_fancy["cats"] = exp_fancy["cats"].cat.set_categories(["a", "b", "c"])\n\n mask = df["cats"] == "c"\n df[mask] = ["b", 2]\n # category c is kept in .categories\n tm.assert_frame_equal(df, exp_fancy)\n\n @pytest.mark.parametrize("dtype", ["float", "int64"])\n @pytest.mark.parametrize("kwargs", [{}, {"index": [1]}, {"columns": ["A"]}])\n def test_setitem_empty_frame_with_boolean(self, dtype, kwargs):\n # see GH#10126\n kwargs["dtype"] = dtype\n df = DataFrame(**kwargs)\n\n df2 = df.copy()\n df[df > df2] = 47\n tm.assert_frame_equal(df, df2)\n\n def test_setitem_boolean_indexing(self):\n idx = list(range(3))\n cols = ["A", "B", "C"]\n df1 = DataFrame(\n index=idx,\n columns=cols,\n data=np.array(\n [[0.0, 0.5, 1.0], [1.5, 2.0, 2.5], [3.0, 3.5, 4.0]], dtype=float\n ),\n )\n df2 = DataFrame(index=idx, columns=cols, data=np.ones((len(idx), len(cols))))\n\n expected = DataFrame(\n index=idx,\n columns=cols,\n data=np.array([[0.0, 0.5, 1.0], [1.5, 2.0, -1], [-1, -1, -1]], dtype=float),\n )\n\n df1[df1 > 2.0 * df2] = -1\n tm.assert_frame_equal(df1, expected)\n with pytest.raises(ValueError, match="Item wrong length"):\n df1[df1.index[:-1] > 2] = -1\n\n def test_loc_setitem_all_false_boolean_two_blocks(self):\n # GH#40885\n df = DataFrame({"a": [1, 2], "b": [3, 4], "c": "a"})\n expected = df.copy()\n indexer = Series([False, False], name="c")\n df.loc[indexer, ["b"]] = DataFrame({"b": [5, 6]}, index=[0, 1])\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_ea_boolean_mask(self):\n # GH#47125\n df = DataFrame([[-1, 2], [3, -4]])\n expected = DataFrame([[0, 2], [3, 0]])\n boolean_indexer = DataFrame(\n {\n 0: Series([True, False], dtype="boolean"),\n 1: Series([pd.NA, True], dtype="boolean"),\n }\n )\n df[boolean_indexer] = 0\n tm.assert_frame_equal(df, expected)\n\n\nclass TestDataFrameSetitemCopyViewSemantics:\n def test_setitem_always_copy(self, float_frame):\n assert "E" not in float_frame.columns\n s = float_frame["A"].copy()\n float_frame["E"] = s\n\n float_frame.iloc[5:10, float_frame.columns.get_loc("E")] = np.nan\n assert notna(s[5:10]).all()\n\n @pytest.mark.parametrize("consolidate", [True, False])\n def test_setitem_partial_column_inplace(\n self, consolidate, using_array_manager, using_copy_on_write\n ):\n # This setting should be in-place, regardless of whether frame is\n # single-block or multi-block\n # GH#304 this used to be incorrectly not-inplace, in which case\n # we needed to ensure _item_cache was cleared.\n\n df = DataFrame(\n {"x": [1.1, 2.1, 3.1, 4.1], "y": [5.1, 6.1, 7.1, 8.1]}, index=[0, 1, 2, 3]\n )\n df.insert(2, "z", np.nan)\n if not using_array_manager:\n if consolidate:\n df._consolidate_inplace()\n assert len(df._mgr.blocks) == 1\n else:\n assert len(df._mgr.blocks) == 2\n\n zvals = df["z"]._values\n\n df.loc[2:, "z"] = 42\n\n expected = Series([np.nan, np.nan, 42, 42], index=df.index, name="z")\n tm.assert_series_equal(df["z"], expected)\n\n # check setting occurred in-place\n if not using_copy_on_write:\n tm.assert_numpy_array_equal(zvals, expected.values)\n assert np.shares_memory(zvals, df["z"]._values)\n\n def test_setitem_duplicate_columns_not_inplace(self):\n # GH#39510\n cols = ["A", "B"] * 2\n df = DataFrame(0.0, index=[0], columns=cols)\n df_copy = df.copy()\n df_view = df[:]\n df["B"] = (2, 5)\n\n expected = DataFrame([[0.0, 2, 0.0, 5]], columns=cols)\n tm.assert_frame_equal(df_view, df_copy)\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize(\n "value", [1, np.array([[1], [1]], dtype="int64"), [[1], [1]]]\n )\n def test_setitem_same_dtype_not_inplace(self, value, using_array_manager):\n # GH#39510\n cols = ["A", "B"]\n df = DataFrame(0, index=[0, 1], columns=cols)\n df_copy = df.copy()\n df_view = df[:]\n df[["B"]] = value\n\n expected = DataFrame([[0, 1], [0, 1]], columns=cols)\n tm.assert_frame_equal(df, expected)\n tm.assert_frame_equal(df_view, df_copy)\n\n @pytest.mark.parametrize("value", [1.0, np.array([[1.0], [1.0]]), [[1.0], [1.0]]])\n def test_setitem_listlike_key_scalar_value_not_inplace(self, value):\n # GH#39510\n cols = ["A", "B"]\n df = DataFrame(0, index=[0, 1], columns=cols)\n df_copy = df.copy()\n df_view = df[:]\n df[["B"]] = value\n\n expected = DataFrame([[0, 1.0], [0, 1.0]], columns=cols)\n tm.assert_frame_equal(df_view, df_copy)\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize(\n "indexer",\n [\n "a",\n ["a"],\n pytest.param(\n [True, False],\n marks=pytest.mark.xfail(\n reason="Boolean indexer incorrectly setting inplace",\n strict=False, # passing on some builds, no obvious pattern\n ),\n ),\n ],\n )\n @pytest.mark.parametrize(\n "value, set_value",\n [\n (1, 5),\n (1.0, 5.0),\n (Timestamp("2020-12-31"), Timestamp("2021-12-31")),\n ("a", "b"),\n ],\n )\n def test_setitem_not_operating_inplace(self, value, set_value, indexer):\n # GH#43406\n df = DataFrame({"a": value}, index=[0, 1])\n expected = df.copy()\n view = df[:]\n df[indexer] = set_value\n tm.assert_frame_equal(view, expected)\n\n @td.skip_array_manager_invalid_test\n def test_setitem_column_update_inplace(\n self, using_copy_on_write, warn_copy_on_write\n ):\n # https://github.com/pandas-dev/pandas/issues/47172\n\n labels = [f"c{i}" for i in range(10)]\n df = DataFrame({col: np.zeros(len(labels)) for col in labels}, index=labels)\n values = df._mgr.blocks[0].values\n\n with tm.raises_chained_assignment_error():\n for label in df.columns:\n df[label][label] = 1\n if not using_copy_on_write:\n # diagonal values all updated\n assert np.all(values[np.arange(10), np.arange(10)] == 1)\n else:\n # original dataframe not updated\n assert np.all(values[np.arange(10), np.arange(10)] == 0)\n\n def test_setitem_column_frame_as_category(self):\n # GH31581\n df = DataFrame([1, 2, 3])\n df["col1"] = DataFrame([1, 2, 3], dtype="category")\n df["col2"] = Series([1, 2, 3], dtype="category")\n\n expected_types = Series(\n ["int64", "category", "category"], index=[0, "col1", "col2"], dtype=object\n )\n tm.assert_series_equal(df.dtypes, expected_types)\n\n @pytest.mark.parametrize("dtype", ["int64", "Int64"])\n def test_setitem_iloc_with_numpy_array(self, dtype):\n # GH-33828\n df = DataFrame({"a": np.ones(3)}, dtype=dtype)\n df.iloc[np.array([0]), np.array([0])] = np.array([[2]])\n\n expected = DataFrame({"a": [2, 1, 1]}, dtype=dtype)\n tm.assert_frame_equal(df, expected)\n\n def test_setitem_frame_dup_cols_dtype(self):\n # GH#53143\n df = DataFrame([[1, 2, 3, 4], [4, 5, 6, 7]], columns=["a", "b", "a", "c"])\n rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"])\n df["a"] = rhs\n expected = DataFrame(\n [[0, 2, 1.5, 4], [2, 5, 2.5, 7]], columns=["a", "b", "a", "c"]\n )\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])\n rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"])\n df["a"] = rhs\n expected = DataFrame([[0, 1.5, 3], [2, 2.5, 6]], columns=["a", "a", "b"])\n tm.assert_frame_equal(df, expected)\n\n def test_frame_setitem_empty_dataframe(self):\n # GH#28871\n dti = DatetimeIndex(["2000-01-01"], dtype="M8[ns]", name="date")\n df = DataFrame({"date": dti}).set_index("date")\n df = df[0:0].copy()\n\n df["3010"] = None\n df["2010"] = None\n\n expected = DataFrame(\n [],\n columns=["3010", "2010"],\n index=dti[:0],\n )\n tm.assert_frame_equal(df, expected)\n\n\ndef test_full_setter_loc_incompatible_dtype():\n # https://github.com/pandas-dev/pandas/issues/55791\n df = DataFrame({"a": [1, 2]})\n with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):\n df.loc[:, "a"] = True\n expected = DataFrame({"a": [True, True]})\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame({"a": [1, 2]})\n with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):\n df.loc[:, "a"] = {0: 3.5, 1: 4.5}\n expected = DataFrame({"a": [3.5, 4.5]})\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame({"a": [1, 2]})\n df.loc[:, "a"] = {0: 3, 1: 4}\n expected = DataFrame({"a": [3, 4]})\n tm.assert_frame_equal(df, expected)\n\n\ndef test_setitem_partial_row_multiple_columns():\n # https://github.com/pandas-dev/pandas/issues/56503\n df = DataFrame({"A": [1, 2, 3], "B": [4.0, 5, 6]})\n # should not warn\n df.loc[df.index <= 1, ["F", "G"]] = (1, "abc")\n expected = DataFrame(\n {\n "A": [1, 2, 3],\n "B": [4.0, 5, 6],\n "F": [1.0, 1, float("nan")],\n "G": ["abc", "abc", float("nan")],\n }\n )\n tm.assert_frame_equal(df, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\test_setitem.py
test_setitem.py
Python
51,683
0.75
0.087018
0.108374
node-utils
995
2025-05-23T07:57:04.495659
BSD-3-Clause
true
adba7b7b980fae0c56ddd99ac3759240
import numpy as np\n\nfrom pandas.core.dtypes.common import is_float_dtype\n\nfrom pandas import (\n DataFrame,\n isna,\n)\nimport pandas._testing as tm\n\n\nclass TestSetValue:\n def test_set_value(self, float_frame):\n for idx in float_frame.index:\n for col in float_frame.columns:\n float_frame._set_value(idx, col, 1)\n assert float_frame[col][idx] == 1\n\n def test_set_value_resize(self, float_frame, using_infer_string):\n res = float_frame._set_value("foobar", "B", 0)\n assert res is None\n assert float_frame.index[-1] == "foobar"\n assert float_frame._get_value("foobar", "B") == 0\n\n float_frame.loc["foobar", "qux"] = 0\n assert float_frame._get_value("foobar", "qux") == 0\n\n res = float_frame.copy()\n res._set_value("foobar", "baz", "sam")\n if using_infer_string:\n assert res["baz"].dtype == "str"\n else:\n assert res["baz"].dtype == np.object_\n res = float_frame.copy()\n res._set_value("foobar", "baz", True)\n assert res["baz"].dtype == np.object_\n\n res = float_frame.copy()\n res._set_value("foobar", "baz", 5)\n assert is_float_dtype(res["baz"])\n assert isna(res["baz"].drop(["foobar"])).all()\n\n with tm.assert_produces_warning(\n FutureWarning, match="Setting an item of incompatible dtype"\n ):\n res._set_value("foobar", "baz", "sam")\n assert res.loc["foobar", "baz"] == "sam"\n\n def test_set_value_with_index_dtype_change(self):\n df_orig = DataFrame(\n np.random.default_rng(2).standard_normal((3, 3)),\n index=range(3),\n columns=list("ABC"),\n )\n\n # this is actually ambiguous as the 2 is interpreted as a positional\n # so column is not created\n df = df_orig.copy()\n df._set_value("C", 2, 1.0)\n assert list(df.index) == list(df_orig.index) + ["C"]\n # assert list(df.columns) == list(df_orig.columns) + [2]\n\n df = df_orig.copy()\n df.loc["C", 2] = 1.0\n assert list(df.index) == list(df_orig.index) + ["C"]\n # assert list(df.columns) == list(df_orig.columns) + [2]\n\n # create both new\n df = df_orig.copy()\n df._set_value("C", "D", 1.0)\n assert list(df.index) == list(df_orig.index) + ["C"]\n assert list(df.columns) == list(df_orig.columns) + ["D"]\n\n df = df_orig.copy()\n df.loc["C", "D"] = 1.0\n assert list(df.index) == list(df_orig.index) + ["C"]\n assert list(df.columns) == list(df_orig.columns) + ["D"]\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\test_set_value.py
test_set_value.py
Python
2,619
0.95
0.090909
0.079365
python-kit
528
2024-10-06T19:09:04.942546
MIT
true
bb450e41edd485c1e4e55fd39d9747ff
import pytest\n\nimport pandas._testing as tm\n\n\nclass TestDataFrameTake:\n def test_take_slices_deprecated(self, float_frame):\n # GH#51539\n df = float_frame\n\n slc = slice(0, 4, 1)\n with tm.assert_produces_warning(FutureWarning):\n df.take(slc, axis=0)\n with tm.assert_produces_warning(FutureWarning):\n df.take(slc, axis=1)\n\n def test_take(self, float_frame):\n # homogeneous\n order = [3, 1, 2, 0]\n for df in [float_frame]:\n result = df.take(order, axis=0)\n expected = df.reindex(df.index.take(order))\n tm.assert_frame_equal(result, expected)\n\n # axis = 1\n result = df.take(order, axis=1)\n expected = df.loc[:, ["D", "B", "C", "A"]]\n tm.assert_frame_equal(result, expected, check_names=False)\n\n # negative indices\n order = [2, 1, -1]\n for df in [float_frame]:\n result = df.take(order, axis=0)\n expected = df.reindex(df.index.take(order))\n tm.assert_frame_equal(result, expected)\n\n result = df.take(order, axis=0)\n tm.assert_frame_equal(result, expected)\n\n # axis = 1\n result = df.take(order, axis=1)\n expected = df.loc[:, ["C", "B", "D"]]\n tm.assert_frame_equal(result, expected, check_names=False)\n\n # illegal indices\n msg = "indices are out-of-bounds"\n with pytest.raises(IndexError, match=msg):\n df.take([3, 1, 2, 30], axis=0)\n with pytest.raises(IndexError, match=msg):\n df.take([3, 1, 2, -31], axis=0)\n with pytest.raises(IndexError, match=msg):\n df.take([3, 1, 2, 5], axis=1)\n with pytest.raises(IndexError, match=msg):\n df.take([3, 1, 2, -5], axis=1)\n\n def test_take_mixed_type(self, float_string_frame):\n # mixed-dtype\n order = [4, 1, 2, 0, 3]\n for df in [float_string_frame]:\n result = df.take(order, axis=0)\n expected = df.reindex(df.index.take(order))\n tm.assert_frame_equal(result, expected)\n\n # axis = 1\n result = df.take(order, axis=1)\n expected = df.loc[:, ["foo", "B", "C", "A", "D"]]\n tm.assert_frame_equal(result, expected)\n\n # negative indices\n order = [4, 1, -2]\n for df in [float_string_frame]:\n result = df.take(order, axis=0)\n expected = df.reindex(df.index.take(order))\n tm.assert_frame_equal(result, expected)\n\n # axis = 1\n result = df.take(order, axis=1)\n expected = df.loc[:, ["foo", "B", "D"]]\n tm.assert_frame_equal(result, expected)\n\n def test_take_mixed_numeric(self, mixed_float_frame, mixed_int_frame):\n # by dtype\n order = [1, 2, 0, 3]\n for df in [mixed_float_frame, mixed_int_frame]:\n result = df.take(order, axis=0)\n expected = df.reindex(df.index.take(order))\n tm.assert_frame_equal(result, expected)\n\n # axis = 1\n result = df.take(order, axis=1)\n expected = df.loc[:, ["B", "C", "A", "D"]]\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\test_take.py
test_take.py
Python
3,230
0.95
0.108696
0.157895
awesome-app
295
2024-09-30T17:17:08.977286
Apache-2.0
true
c65470bd34153b61cc22f71303222a48
from datetime import datetime\n\nfrom hypothesis import given\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.common import is_scalar\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n DatetimeIndex,\n Index,\n Series,\n StringDtype,\n Timestamp,\n date_range,\n isna,\n)\nimport pandas._testing as tm\nfrom pandas._testing._hypothesis import OPTIONAL_ONE_OF_ALL\n\n\n@pytest.fixture(params=["default", "float_string", "mixed_float", "mixed_int"])\ndef where_frame(request, float_string_frame, mixed_float_frame, mixed_int_frame):\n if request.param == "default":\n return DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)), columns=["A", "B", "C"]\n )\n if request.param == "float_string":\n return float_string_frame\n if request.param == "mixed_float":\n return mixed_float_frame\n if request.param == "mixed_int":\n return mixed_int_frame\n\n\ndef _safe_add(df):\n # only add to the numeric items\n def is_ok(s):\n return (\n issubclass(s.dtype.type, (np.integer, np.floating)) and s.dtype != "uint8"\n )\n\n return DataFrame(dict((c, s + 1) if is_ok(s) else (c, s) for c, s in df.items()))\n\n\nclass TestDataFrameIndexingWhere:\n def test_where_get(self, where_frame, float_string_frame):\n def _check_get(df, cond, check_dtypes=True):\n other1 = _safe_add(df)\n rs = df.where(cond, other1)\n rs2 = df.where(cond.values, other1)\n for k, v in rs.items():\n exp = Series(np.where(cond[k], df[k], other1[k]), index=v.index)\n tm.assert_series_equal(v, exp, check_names=False)\n tm.assert_frame_equal(rs, rs2)\n\n # dtypes\n if check_dtypes:\n assert (rs.dtypes == df.dtypes).all()\n\n # check getting\n df = where_frame\n if df is float_string_frame:\n msg = (\n "'>' not supported between instances of 'str' and 'int'"\n "|Invalid comparison"\n )\n with pytest.raises(TypeError, match=msg):\n df > 0\n return\n cond = df > 0\n _check_get(df, cond)\n\n def test_where_upcasting(self):\n # upcasting case (GH # 2794)\n df = DataFrame(\n {\n c: Series([1] * 3, dtype=c)\n for c in ["float32", "float64", "int32", "int64"]\n }\n )\n df.iloc[1, :] = 0\n result = df.dtypes\n expected = Series(\n [\n np.dtype("float32"),\n np.dtype("float64"),\n np.dtype("int32"),\n np.dtype("int64"),\n ],\n index=["float32", "float64", "int32", "int64"],\n )\n\n # when we don't preserve boolean casts\n #\n # expected = Series({ 'float32' : 1, 'float64' : 3 })\n\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning")\n def test_where_alignment(self, where_frame, float_string_frame):\n # aligning\n def _check_align(df, cond, other, check_dtypes=True):\n rs = df.where(cond, other)\n for i, k in enumerate(rs.columns):\n result = rs[k]\n d = df[k].values\n c = cond[k].reindex(df[k].index).fillna(False).values\n\n if is_scalar(other):\n o = other\n elif isinstance(other, np.ndarray):\n o = Series(other[:, i], index=result.index).values\n else:\n o = other[k].values\n\n new_values = d if c.all() else np.where(c, d, o)\n expected = Series(new_values, index=result.index, name=k)\n\n # since we can't always have the correct numpy dtype\n # as numpy doesn't know how to downcast, don't check\n tm.assert_series_equal(result, expected, check_dtype=False)\n\n # dtypes\n # can't check dtype when other is an ndarray\n\n if check_dtypes and not isinstance(other, np.ndarray):\n assert (rs.dtypes == df.dtypes).all()\n\n df = where_frame\n if df is float_string_frame:\n msg = (\n "'>' not supported between instances of 'str' and 'int'"\n "|Invalid comparison"\n )\n with pytest.raises(TypeError, match=msg):\n df > 0\n return\n\n # other is a frame\n cond = (df > 0)[1:]\n _check_align(df, cond, _safe_add(df))\n\n # check other is ndarray\n cond = df > 0\n _check_align(df, cond, (_safe_add(df).values))\n\n # integers are upcast, so don't check the dtypes\n cond = df > 0\n check_dtypes = all(not issubclass(s.type, np.integer) for s in df.dtypes)\n _check_align(df, cond, np.nan, check_dtypes=check_dtypes)\n\n # Ignore deprecation warning in Python 3.12 for inverting a bool\n @pytest.mark.filterwarnings("ignore::DeprecationWarning")\n def test_where_invalid(self):\n # invalid conditions\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)), columns=["A", "B", "C"]\n )\n cond = df > 0\n\n err1 = (df + 1).values[0:2, :]\n msg = "other must be the same shape as self when an ndarray"\n with pytest.raises(ValueError, match=msg):\n df.where(cond, err1)\n\n err2 = cond.iloc[:2, :].values\n other1 = _safe_add(df)\n msg = "Array conditional must be same shape as self"\n with pytest.raises(ValueError, match=msg):\n df.where(err2, other1)\n\n with pytest.raises(ValueError, match=msg):\n df.mask(True)\n with pytest.raises(ValueError, match=msg):\n df.mask(0)\n\n @pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning")\n def test_where_set(self, where_frame, float_string_frame, mixed_int_frame):\n # where inplace\n\n def _check_set(df, cond, check_dtypes=True):\n dfi = df.copy()\n econd = cond.reindex_like(df).fillna(True).infer_objects(copy=False)\n expected = dfi.mask(~econd)\n\n return_value = dfi.where(cond, np.nan, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(dfi, expected)\n\n # dtypes (and confirm upcasts)x\n if check_dtypes:\n for k, v in df.dtypes.items():\n if issubclass(v.type, np.integer) and not cond[k].all():\n v = np.dtype("float64")\n assert dfi[k].dtype == v\n\n df = where_frame\n if df is float_string_frame:\n msg = (\n "'>' not supported between instances of 'str' and 'int'"\n "|Invalid comparison"\n )\n with pytest.raises(TypeError, match=msg):\n df > 0\n return\n if df is mixed_int_frame:\n df = df.astype("float64")\n\n cond = df > 0\n _check_set(df, cond)\n\n cond = df >= 0\n _check_set(df, cond)\n\n # aligning\n cond = (df >= 0)[1:]\n _check_set(df, cond)\n\n def test_where_series_slicing(self):\n # GH 10218\n # test DataFrame.where with Series slicing\n df = DataFrame({"a": range(3), "b": range(4, 7)})\n result = df.where(df["a"] == 1)\n expected = df[df["a"] == 1].reindex(df.index)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("klass", [list, tuple, np.array])\n def test_where_array_like(self, klass):\n # see gh-15414\n df = DataFrame({"a": [1, 2, 3]})\n cond = [[False], [True], [True]]\n expected = DataFrame({"a": [np.nan, 2, 3]})\n\n result = df.where(klass(cond))\n tm.assert_frame_equal(result, expected)\n\n df["b"] = 2\n expected["b"] = [2, np.nan, 2]\n cond = [[False, True], [True, False], [True, True]]\n\n result = df.where(klass(cond))\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "cond",\n [\n [[1], [0], [1]],\n Series([[2], [5], [7]]),\n DataFrame({"a": [2, 5, 7]}),\n [["True"], ["False"], ["True"]],\n [[Timestamp("2017-01-01")], [pd.NaT], [Timestamp("2017-01-02")]],\n ],\n )\n def test_where_invalid_input_single(self, cond):\n # see gh-15414: only boolean arrays accepted\n df = DataFrame({"a": [1, 2, 3]})\n msg = "Boolean array expected for the condition"\n\n with pytest.raises(ValueError, match=msg):\n df.where(cond)\n\n @pytest.mark.parametrize(\n "cond",\n [\n [[0, 1], [1, 0], [1, 1]],\n Series([[0, 2], [5, 0], [4, 7]]),\n [["False", "True"], ["True", "False"], ["True", "True"]],\n DataFrame({"a": [2, 5, 7], "b": [4, 8, 9]}),\n [\n [pd.NaT, Timestamp("2017-01-01")],\n [Timestamp("2017-01-02"), pd.NaT],\n [Timestamp("2017-01-03"), Timestamp("2017-01-03")],\n ],\n ],\n )\n def test_where_invalid_input_multiple(self, cond):\n # see gh-15414: only boolean arrays accepted\n df = DataFrame({"a": [1, 2, 3], "b": [2, 2, 2]})\n msg = "Boolean array expected for the condition"\n\n with pytest.raises(ValueError, match=msg):\n df.where(cond)\n\n def test_where_dataframe_col_match(self):\n df = DataFrame([[1, 2, 3], [4, 5, 6]])\n cond = DataFrame([[True, False, True], [False, False, True]])\n\n result = df.where(cond)\n expected = DataFrame([[1.0, np.nan, 3], [np.nan, np.nan, 6]])\n tm.assert_frame_equal(result, expected)\n\n # this *does* align, though has no matching columns\n cond.columns = ["a", "b", "c"]\n result = df.where(cond)\n expected = DataFrame(np.nan, index=df.index, columns=df.columns)\n tm.assert_frame_equal(result, expected)\n\n def test_where_ndframe_align(self):\n msg = "Array conditional must be same shape as self"\n df = DataFrame([[1, 2, 3], [4, 5, 6]])\n\n cond = [True]\n with pytest.raises(ValueError, match=msg):\n df.where(cond)\n\n expected = DataFrame([[1, 2, 3], [np.nan, np.nan, np.nan]])\n\n out = df.where(Series(cond))\n tm.assert_frame_equal(out, expected)\n\n cond = np.array([False, True, False, True])\n with pytest.raises(ValueError, match=msg):\n df.where(cond)\n\n expected = DataFrame([[np.nan, np.nan, np.nan], [4, 5, 6]])\n\n out = df.where(Series(cond))\n tm.assert_frame_equal(out, expected)\n\n def test_where_bug(self):\n # see gh-2793\n df = DataFrame(\n {"a": [1.0, 2.0, 3.0, 4.0], "b": [4.0, 3.0, 2.0, 1.0]}, dtype="float64"\n )\n expected = DataFrame(\n {"a": [np.nan, np.nan, 3.0, 4.0], "b": [4.0, 3.0, np.nan, np.nan]},\n dtype="float64",\n )\n result = df.where(df > 2, np.nan)\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n return_value = result.where(result > 2, np.nan, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n def test_where_bug_mixed(self, any_signed_int_numpy_dtype):\n # see gh-2793\n df = DataFrame(\n {\n "a": np.array([1, 2, 3, 4], dtype=any_signed_int_numpy_dtype),\n "b": np.array([4.0, 3.0, 2.0, 1.0], dtype="float64"),\n }\n )\n\n expected = DataFrame(\n {"a": [-1, -1, 3, 4], "b": [4.0, 3.0, -1, -1]},\n ).astype({"a": any_signed_int_numpy_dtype, "b": "float64"})\n\n result = df.where(df > 2, -1)\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n return_value = result.where(result > 2, -1, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n def test_where_bug_transposition(self):\n # see gh-7506\n a = DataFrame({0: [1, 2], 1: [3, 4], 2: [5, 6]})\n b = DataFrame({0: [np.nan, 8], 1: [9, np.nan], 2: [np.nan, np.nan]})\n do_not_replace = b.isna() | (a > b)\n\n expected = a.copy()\n expected[~do_not_replace] = b\n\n msg = "Downcasting behavior in Series and DataFrame methods 'where'"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = a.where(do_not_replace, b)\n tm.assert_frame_equal(result, expected)\n\n a = DataFrame({0: [4, 6], 1: [1, 0]})\n b = DataFrame({0: [np.nan, 3], 1: [3, np.nan]})\n do_not_replace = b.isna() | (a > b)\n\n expected = a.copy()\n expected[~do_not_replace] = b\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = a.where(do_not_replace, b)\n tm.assert_frame_equal(result, expected)\n\n def test_where_datetime(self):\n # GH 3311\n df = DataFrame(\n {\n "A": date_range("20130102", periods=5),\n "B": date_range("20130104", periods=5),\n "C": np.random.default_rng(2).standard_normal(5),\n }\n )\n\n stamp = datetime(2013, 1, 3)\n msg = "'>' not supported between instances of 'float' and 'datetime.datetime'"\n with pytest.raises(TypeError, match=msg):\n df > stamp\n\n result = df[df.iloc[:, :-1] > stamp]\n\n expected = df.copy()\n expected.loc[[0, 1], "A"] = np.nan\n\n expected.loc[:, "C"] = np.nan\n tm.assert_frame_equal(result, expected)\n\n def test_where_none(self):\n # GH 4667\n # setting with None changes dtype\n df = DataFrame({"series": Series(range(10))}).astype(float)\n df[df > 7] = None\n expected = DataFrame(\n {"series": Series([0, 1, 2, 3, 4, 5, 6, 7, np.nan, np.nan])}\n )\n tm.assert_frame_equal(df, expected)\n\n # GH 7656\n df = DataFrame(\n [\n {"A": 1, "B": np.nan, "C": "Test"},\n {"A": np.nan, "B": "Test", "C": np.nan},\n ]\n )\n\n orig = df.copy()\n\n mask = ~isna(df)\n df.where(mask, None, inplace=True)\n expected = DataFrame(\n {\n "A": [1.0, np.nan],\n "B": [None, "Test"],\n "C": ["Test", None],\n }\n )\n tm.assert_frame_equal(df, expected)\n\n df = orig.copy()\n df[~mask] = None\n tm.assert_frame_equal(df, expected)\n\n def test_where_empty_df_and_empty_cond_having_non_bool_dtypes(self):\n # see gh-21947\n df = DataFrame(columns=["a"])\n cond = df\n assert (cond.dtypes == object).all()\n\n result = df.where(cond)\n tm.assert_frame_equal(result, df)\n\n def test_where_align(self):\n def create():\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 3)))\n df.iloc[3:5, 0] = np.nan\n df.iloc[4:6, 1] = np.nan\n df.iloc[5:8, 2] = np.nan\n return df\n\n # series\n df = create()\n expected = df.fillna(df.mean())\n result = df.where(pd.notna(df), df.mean(), axis="columns")\n tm.assert_frame_equal(result, expected)\n\n return_value = df.where(pd.notna(df), df.mean(), inplace=True, axis="columns")\n assert return_value is None\n tm.assert_frame_equal(df, expected)\n\n df = create().fillna(0)\n expected = df.apply(lambda x, y: x.where(x > 0, y), y=df[0])\n result = df.where(df > 0, df[0], axis="index")\n tm.assert_frame_equal(result, expected)\n result = df.where(df > 0, df[0], axis="rows")\n tm.assert_frame_equal(result, expected)\n\n # frame\n df = create()\n expected = df.fillna(1)\n result = df.where(\n pd.notna(df), DataFrame(1, index=df.index, columns=df.columns)\n )\n tm.assert_frame_equal(result, expected)\n\n def test_where_complex(self):\n # GH 6345\n expected = DataFrame([[1 + 1j, 2], [np.nan, 4 + 1j]], columns=["a", "b"])\n df = DataFrame([[1 + 1j, 2], [5 + 1j, 4 + 1j]], columns=["a", "b"])\n df[df.abs() >= 5] = np.nan\n tm.assert_frame_equal(df, expected)\n\n def test_where_axis(self):\n # GH 9736\n df = DataFrame(np.random.default_rng(2).standard_normal((2, 2)))\n mask = DataFrame([[False, False], [False, False]])\n ser = Series([0, 1])\n\n expected = DataFrame([[0, 0], [1, 1]], dtype="float64")\n result = df.where(mask, ser, axis="index")\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n return_value = result.where(mask, ser, axis="index", inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame([[0, 1], [0, 1]], dtype="float64")\n result = df.where(mask, ser, axis="columns")\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n return_value = result.where(mask, ser, axis="columns", inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n def test_where_axis_with_upcast(self):\n # Upcast needed\n df = DataFrame([[1, 2], [3, 4]], dtype="int64")\n mask = DataFrame([[False, False], [False, False]])\n ser = Series([0, np.nan])\n\n expected = DataFrame([[0, 0], [np.nan, np.nan]], dtype="float64")\n result = df.where(mask, ser, axis="index")\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):\n return_value = result.where(mask, ser, axis="index", inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame([[0, np.nan], [0, np.nan]])\n result = df.where(mask, ser, axis="columns")\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame(\n {\n 0: np.array([0, 0], dtype="int64"),\n 1: np.array([np.nan, np.nan], dtype="float64"),\n }\n )\n result = df.copy()\n with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):\n return_value = result.where(mask, ser, axis="columns", inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n def test_where_axis_multiple_dtypes(self):\n # Multiple dtypes (=> multiple Blocks)\n df = pd.concat(\n [\n DataFrame(np.random.default_rng(2).standard_normal((10, 2))),\n DataFrame(\n np.random.default_rng(2).integers(0, 10, size=(10, 2)),\n dtype="int64",\n ),\n ],\n ignore_index=True,\n axis=1,\n )\n mask = DataFrame(False, columns=df.columns, index=df.index)\n s1 = Series(1, index=df.columns)\n s2 = Series(2, index=df.index)\n\n result = df.where(mask, s1, axis="columns")\n expected = DataFrame(1.0, columns=df.columns, index=df.index)\n expected[2] = expected[2].astype("int64")\n expected[3] = expected[3].astype("int64")\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n return_value = result.where(mask, s1, axis="columns", inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n result = df.where(mask, s2, axis="index")\n expected = DataFrame(2.0, columns=df.columns, index=df.index)\n expected[2] = expected[2].astype("int64")\n expected[3] = expected[3].astype("int64")\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n return_value = result.where(mask, s2, axis="index", inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n # DataFrame vs DataFrame\n d1 = df.copy().drop(1, axis=0)\n # Explicit cast to avoid implicit cast when setting value to np.nan\n expected = df.copy().astype("float")\n expected.loc[1, :] = np.nan\n\n result = df.where(mask, d1)\n tm.assert_frame_equal(result, expected)\n result = df.where(mask, d1, axis="index")\n tm.assert_frame_equal(result, expected)\n result = df.copy()\n with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):\n return_value = result.where(mask, d1, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n result = df.copy()\n with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):\n return_value = result.where(mask, d1, inplace=True, axis="index")\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n d2 = df.copy().drop(1, axis=1)\n expected = df.copy()\n expected.loc[:, 1] = np.nan\n\n result = df.where(mask, d2)\n tm.assert_frame_equal(result, expected)\n result = df.where(mask, d2, axis="columns")\n tm.assert_frame_equal(result, expected)\n result = df.copy()\n return_value = result.where(mask, d2, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n result = df.copy()\n return_value = result.where(mask, d2, inplace=True, axis="columns")\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n def test_where_callable(self):\n # GH 12533\n df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n result = df.where(lambda x: x > 4, lambda x: x + 1)\n exp = DataFrame([[2, 3, 4], [5, 5, 6], [7, 8, 9]])\n tm.assert_frame_equal(result, exp)\n tm.assert_frame_equal(result, df.where(df > 4, df + 1))\n\n # return ndarray and scalar\n result = df.where(lambda x: (x % 2 == 0).values, lambda x: 99)\n exp = DataFrame([[99, 2, 99], [4, 99, 6], [99, 8, 99]])\n tm.assert_frame_equal(result, exp)\n tm.assert_frame_equal(result, df.where(df % 2 == 0, 99))\n\n # chain\n result = (df + 2).where(lambda x: x > 8, lambda x: x + 10)\n exp = DataFrame([[13, 14, 15], [16, 17, 18], [9, 10, 11]])\n tm.assert_frame_equal(result, exp)\n tm.assert_frame_equal(result, (df + 2).where((df + 2) > 8, (df + 2) + 10))\n\n def test_where_tz_values(self, tz_naive_fixture, frame_or_series):\n obj1 = DataFrame(\n DatetimeIndex(["20150101", "20150102", "20150103"], tz=tz_naive_fixture),\n columns=["date"],\n )\n obj2 = DataFrame(\n DatetimeIndex(["20150103", "20150104", "20150105"], tz=tz_naive_fixture),\n columns=["date"],\n )\n mask = DataFrame([True, True, False], columns=["date"])\n exp = DataFrame(\n DatetimeIndex(["20150101", "20150102", "20150105"], tz=tz_naive_fixture),\n columns=["date"],\n )\n if frame_or_series is Series:\n obj1 = obj1["date"]\n obj2 = obj2["date"]\n mask = mask["date"]\n exp = exp["date"]\n\n result = obj1.where(mask, obj2)\n tm.assert_equal(exp, result)\n\n def test_df_where_change_dtype(self):\n # GH#16979\n df = DataFrame(np.arange(2 * 3).reshape(2, 3), columns=list("ABC"))\n mask = np.array([[True, False, False], [False, False, True]])\n\n result = df.where(mask)\n expected = DataFrame(\n [[0, np.nan, np.nan], [np.nan, np.nan, 5]], columns=list("ABC")\n )\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("kwargs", [{}, {"other": None}])\n def test_df_where_with_category(self, kwargs):\n # GH#16979\n data = np.arange(2 * 3, dtype=np.int64).reshape(2, 3)\n df = DataFrame(data, columns=list("ABC"))\n mask = np.array([[True, False, False], [False, False, True]])\n\n # change type to category\n df.A = df.A.astype("category")\n df.B = df.B.astype("category")\n df.C = df.C.astype("category")\n\n result = df.where(mask, **kwargs)\n A = pd.Categorical([0, np.nan], categories=[0, 3])\n B = pd.Categorical([np.nan, np.nan], categories=[1, 4])\n C = pd.Categorical([np.nan, 5], categories=[2, 5])\n expected = DataFrame({"A": A, "B": B, "C": C})\n\n tm.assert_frame_equal(result, expected)\n\n # Check Series.where while we're here\n result = df.A.where(mask[:, 0], **kwargs)\n expected = Series(A, name="A")\n\n tm.assert_series_equal(result, expected)\n\n def test_where_categorical_filtering(self):\n # GH#22609 Verify filtering operations on DataFrames with categorical Series\n df = DataFrame(data=[[0, 0], [1, 1]], columns=["a", "b"])\n df["b"] = df["b"].astype("category")\n\n result = df.where(df["a"] > 0)\n # Explicitly cast to 'float' to avoid implicit cast when setting np.nan\n expected = df.copy().astype({"a": "float"})\n expected.loc[0, :] = np.nan\n\n tm.assert_equal(result, expected)\n\n def test_where_ea_other(self):\n # GH#38729/GH#38742\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})\n arr = pd.array([7, pd.NA, 9])\n ser = Series(arr)\n mask = np.ones(df.shape, dtype=bool)\n mask[1, :] = False\n\n # TODO: ideally we would get Int64 instead of object\n result = df.where(mask, ser, axis=0)\n expected = DataFrame({"A": [1, np.nan, 3], "B": [4, np.nan, 6]})\n tm.assert_frame_equal(result, expected)\n\n ser2 = Series(arr[:2], index=["A", "B"])\n expected = DataFrame({"A": [1, 7, 3], "B": [4, np.nan, 6]})\n result = df.where(mask, ser2, axis=1)\n tm.assert_frame_equal(result, expected)\n\n def test_where_interval_noop(self):\n # GH#44181\n df = DataFrame([pd.Interval(0, 0)])\n res = df.where(df.notna())\n tm.assert_frame_equal(res, df)\n\n ser = df[0]\n res = ser.where(ser.notna())\n tm.assert_series_equal(res, ser)\n\n def test_where_interval_fullop_downcast(self, frame_or_series):\n # GH#45768\n obj = frame_or_series([pd.Interval(0, 0)] * 2)\n other = frame_or_series([1.0, 2.0])\n\n msg = "Downcasting behavior in Series and DataFrame methods 'where'"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res = obj.where(~obj.notna(), other)\n\n # since all entries are being changed, we will downcast result\n # from object to ints (not floats)\n tm.assert_equal(res, other.astype(np.int64))\n\n # unlike where, Block.putmask does not downcast\n with tm.assert_produces_warning(\n FutureWarning, match="Setting an item of incompatible dtype"\n ):\n obj.mask(obj.notna(), other, inplace=True)\n tm.assert_equal(obj, other.astype(object))\n\n @pytest.mark.parametrize(\n "dtype",\n [\n "timedelta64[ns]",\n "datetime64[ns]",\n "datetime64[ns, Asia/Tokyo]",\n "Period[D]",\n ],\n )\n def test_where_datetimelike_noop(self, dtype):\n # GH#45135, analogue to GH#44181 for Period don't raise on no-op\n # For td64/dt64/dt64tz we already don't raise, but also are\n # checking that we don't unnecessarily upcast to object.\n with tm.assert_produces_warning(FutureWarning, match="is deprecated"):\n ser = Series(np.arange(3) * 10**9, dtype=np.int64).view(dtype)\n df = ser.to_frame()\n mask = np.array([False, False, False])\n\n res = ser.where(~mask, "foo")\n tm.assert_series_equal(res, ser)\n\n mask2 = mask.reshape(-1, 1)\n res2 = df.where(~mask2, "foo")\n tm.assert_frame_equal(res2, df)\n\n res3 = ser.mask(mask, "foo")\n tm.assert_series_equal(res3, ser)\n\n res4 = df.mask(mask2, "foo")\n tm.assert_frame_equal(res4, df)\n\n # opposite case where we are replacing *all* values -> we downcast\n # from object dtype # GH#45768\n msg = "Downcasting behavior in Series and DataFrame methods 'where'"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res5 = df.where(mask2, 4)\n expected = DataFrame(4, index=df.index, columns=df.columns)\n tm.assert_frame_equal(res5, expected)\n\n # unlike where, Block.putmask does not downcast\n with tm.assert_produces_warning(\n FutureWarning, match="Setting an item of incompatible dtype"\n ):\n df.mask(~mask2, 4, inplace=True)\n tm.assert_frame_equal(df, expected.astype(object))\n\n\ndef test_where_int_downcasting_deprecated():\n # GH#44597\n arr = np.arange(6).astype(np.int16).reshape(3, 2)\n df = DataFrame(arr)\n\n mask = np.zeros(arr.shape, dtype=bool)\n mask[:, 0] = True\n\n res = df.where(mask, 2**17)\n\n expected = DataFrame({0: arr[:, 0], 1: np.array([2**17] * 3, dtype=np.int32)})\n tm.assert_frame_equal(res, expected)\n\n\ndef test_where_copies_with_noop(frame_or_series):\n # GH-39595\n result = frame_or_series([1, 2, 3, 4])\n expected = result.copy()\n col = result[0] if frame_or_series is DataFrame else result\n\n where_res = result.where(col < 5)\n where_res *= 2\n\n tm.assert_equal(result, expected)\n\n where_res = result.where(col > 5, [1, 2, 3, 4])\n where_res *= 2\n\n tm.assert_equal(result, expected)\n\n\ndef test_where_string_dtype(frame_or_series):\n # GH40824\n obj = frame_or_series(\n ["a", "b", "c", "d"], index=["id1", "id2", "id3", "id4"], dtype=StringDtype()\n )\n filtered_obj = frame_or_series(\n ["b", "c"], index=["id2", "id3"], dtype=StringDtype()\n )\n filter_ser = Series([False, True, True, False])\n\n result = obj.where(filter_ser, filtered_obj)\n expected = frame_or_series(\n [pd.NA, "b", "c", pd.NA],\n index=["id1", "id2", "id3", "id4"],\n dtype=StringDtype(),\n )\n tm.assert_equal(result, expected)\n\n result = obj.mask(~filter_ser, filtered_obj)\n tm.assert_equal(result, expected)\n\n obj.mask(~filter_ser, filtered_obj, inplace=True)\n tm.assert_equal(result, expected)\n\n\ndef test_where_bool_comparison():\n # GH 10336\n df_mask = DataFrame(\n {"AAA": [True] * 4, "BBB": [False] * 4, "CCC": [True, False, True, False]}\n )\n result = df_mask.where(df_mask == False) # noqa: E712\n expected = DataFrame(\n {\n "AAA": np.array([np.nan] * 4, dtype=object),\n "BBB": [False] * 4,\n "CCC": [np.nan, False, np.nan, False],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_where_none_nan_coerce():\n # GH 15613\n expected = DataFrame(\n {\n "A": [Timestamp("20130101"), pd.NaT, Timestamp("20130103")],\n "B": [1, 2, np.nan],\n }\n )\n result = expected.where(expected.notnull(), None)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_where_duplicate_axes_mixed_dtypes():\n # GH 25399, verify manually masking is not affected anymore by dtype of column for\n # duplicate axes.\n result = DataFrame(data=[[0, np.nan]], columns=Index(["A", "A"]))\n index, columns = result.axes\n mask = DataFrame(data=[[True, True]], columns=columns, index=index)\n a = result.astype(object).where(mask)\n b = result.astype("f8").where(mask)\n c = result.T.where(mask.T).T\n d = result.where(mask) # used to fail with "cannot reindex from a duplicate axis"\n tm.assert_frame_equal(a.astype("f8"), b.astype("f8"))\n tm.assert_frame_equal(b.astype("f8"), c.astype("f8"))\n tm.assert_frame_equal(c.astype("f8"), d.astype("f8"))\n\n\ndef test_where_columns_casting():\n # GH 42295\n\n df = DataFrame({"a": [1.0, 2.0], "b": [3, np.nan]})\n expected = df.copy()\n result = df.where(pd.notnull(df), None)\n # make sure dtypes don't change\n tm.assert_frame_equal(expected, result)\n\n\n@pytest.mark.parametrize("as_cat", [True, False])\ndef test_where_period_invalid_na(frame_or_series, as_cat, request):\n # GH#44697\n idx = pd.period_range("2016-01-01", periods=3, freq="D")\n if as_cat:\n idx = idx.astype("category")\n obj = frame_or_series(idx)\n\n # NA value that we should *not* cast to Period dtype\n tdnat = pd.NaT.to_numpy("m8[ns]")\n\n mask = np.array([True, True, False], ndmin=obj.ndim).T\n\n if as_cat:\n msg = (\n r"Cannot setitem on a Categorical with a new category \(NaT\), "\n "set the categories first"\n )\n else:\n msg = "value should be a 'Period'"\n\n if as_cat:\n with pytest.raises(TypeError, match=msg):\n obj.where(mask, tdnat)\n\n with pytest.raises(TypeError, match=msg):\n obj.mask(mask, tdnat)\n\n with pytest.raises(TypeError, match=msg):\n obj.mask(mask, tdnat, inplace=True)\n\n else:\n # With PeriodDtype, ser[i] = tdnat coerces instead of raising,\n # so for consistency, ser[mask] = tdnat must as well\n expected = obj.astype(object).where(mask, tdnat)\n result = obj.where(mask, tdnat)\n tm.assert_equal(result, expected)\n\n expected = obj.astype(object).mask(mask, tdnat)\n result = obj.mask(mask, tdnat)\n tm.assert_equal(result, expected)\n\n with tm.assert_produces_warning(\n FutureWarning, match="Setting an item of incompatible dtype"\n ):\n obj.mask(mask, tdnat, inplace=True)\n tm.assert_equal(obj, expected)\n\n\ndef test_where_nullable_invalid_na(frame_or_series, any_numeric_ea_dtype):\n # GH#44697\n arr = pd.array([1, 2, 3], dtype=any_numeric_ea_dtype)\n obj = frame_or_series(arr)\n\n mask = np.array([True, True, False], ndmin=obj.ndim).T\n\n msg = r"Invalid value '.*' for dtype '(U?Int|Float)\d{1,2}'"\n\n for null in tm.NP_NAT_OBJECTS + [pd.NaT]:\n # NaT is an NA value that we should *not* cast to pd.NA dtype\n with pytest.raises(TypeError, match=msg):\n obj.where(mask, null)\n\n with pytest.raises(TypeError, match=msg):\n obj.mask(mask, null)\n\n\n@given(data=OPTIONAL_ONE_OF_ALL)\ndef test_where_inplace_casting(data):\n # GH 22051\n df = DataFrame({"a": data})\n df_copy = df.where(pd.notnull(df), None).copy()\n df.where(pd.notnull(df), None, inplace=True)\n tm.assert_equal(df, df_copy)\n\n\ndef test_where_downcast_to_td64():\n ser = Series([1, 2, 3])\n\n mask = np.array([False, False, False])\n\n td = pd.Timedelta(days=1)\n\n msg = "Downcasting behavior in Series and DataFrame methods 'where'"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res = ser.where(mask, td)\n expected = Series([td, td, td], dtype="m8[ns]")\n tm.assert_series_equal(res, expected)\n\n with pd.option_context("future.no_silent_downcasting", True):\n with tm.assert_produces_warning(None, match=msg):\n res2 = ser.where(mask, td)\n expected2 = expected.astype(object)\n tm.assert_series_equal(res2, expected2)\n\n\ndef _check_where_equivalences(df, mask, other, expected):\n # similar to tests.series.indexing.test_setitem.SetitemCastingEquivalences\n # but with DataFrame in mind and less fleshed-out\n res = df.where(mask, other)\n tm.assert_frame_equal(res, expected)\n\n res = df.mask(~mask, other)\n tm.assert_frame_equal(res, expected)\n\n # Note: frame.mask(~mask, other, inplace=True) takes some more work bc\n # Block.putmask does *not* downcast. The change to 'expected' here\n # is specific to the cases in test_where_dt64_2d.\n df = df.copy()\n df.mask(~mask, other, inplace=True)\n if not mask.all():\n # with mask.all(), Block.putmask is a no-op, so does not downcast\n expected = expected.copy()\n expected["A"] = expected["A"].astype(object)\n tm.assert_frame_equal(df, expected)\n\n\ndef test_where_dt64_2d():\n dti = date_range("2016-01-01", periods=6)\n dta = dti._data.reshape(3, 2)\n other = dta - dta[0, 0]\n\n df = DataFrame(dta, columns=["A", "B"])\n\n mask = np.asarray(df.isna()).copy()\n mask[:, 1] = True\n\n # setting all of one column, none of the other\n expected = DataFrame({"A": other[:, 0], "B": dta[:, 1]})\n with tm.assert_produces_warning(\n FutureWarning, match="Setting an item of incompatible dtype"\n ):\n _check_where_equivalences(df, mask, other, expected)\n\n # setting part of one column, none of the other\n mask[1, 0] = True\n expected = DataFrame(\n {\n "A": np.array([other[0, 0], dta[1, 0], other[2, 0]], dtype=object),\n "B": dta[:, 1],\n }\n )\n with tm.assert_produces_warning(\n FutureWarning, match="Setting an item of incompatible dtype"\n ):\n _check_where_equivalences(df, mask, other, expected)\n\n # setting nothing in either column\n mask[:] = True\n expected = df\n _check_where_equivalences(df, mask, other, expected)\n\n\ndef test_where_producing_ea_cond_for_np_dtype():\n # GH#44014\n df = DataFrame({"a": Series([1, pd.NA, 2], dtype="Int64"), "b": [1, 2, 3]})\n result = df.where(lambda x: x.apply(lambda y: y > 1, axis=1))\n expected = DataFrame(\n {"a": Series([pd.NA, pd.NA, 2], dtype="Int64"), "b": [np.nan, 2, 3]}\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "replacement", [0.001, True, "snake", None, datetime(2022, 5, 4)]\n)\ndef test_where_int_overflow(replacement):\n # GH 31687\n df = DataFrame([[1.0, 2e25, "nine"], [np.nan, 0.1, None]])\n result = df.where(pd.notnull(df), replacement)\n expected = DataFrame([[1.0, 2e25, "nine"], [replacement, 0.1, replacement]])\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_where_inplace_no_other():\n # GH#51685\n df = DataFrame({"a": [1.0, 2.0], "b": ["x", "y"]})\n cond = DataFrame({"a": [True, False], "b": [False, True]})\n df.where(cond, inplace=True)\n expected = DataFrame({"a": [1, np.nan], "b": [np.nan, "y"]})\n tm.assert_frame_equal(df, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\test_where.py
test_where.py
Python
38,119
0.95
0.082428
0.10245
python-kit
52
2023-10-09T01:41:31.391539
GPL-3.0
true
49ceec89297c18bcbd657193d7ec416e
import re\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import SettingWithCopyError\n\nfrom pandas import (\n DataFrame,\n Index,\n IndexSlice,\n MultiIndex,\n Series,\n concat,\n)\nimport pandas._testing as tm\n\nfrom pandas.tseries.offsets import BDay\n\n\n@pytest.fixture\ndef four_level_index_dataframe():\n arr = np.array(\n [\n [-0.5109, -2.3358, -0.4645, 0.05076, 0.364],\n [0.4473, 1.4152, 0.2834, 1.00661, 0.1744],\n [-0.6662, -0.5243, -0.358, 0.89145, 2.5838],\n ]\n )\n index = MultiIndex(\n levels=[["a", "x"], ["b", "q"], [10.0032, 20.0, 30.0], [3, 4, 5]],\n codes=[[0, 0, 1], [0, 1, 1], [0, 1, 2], [2, 1, 0]],\n names=["one", "two", "three", "four"],\n )\n return DataFrame(arr, index=index, columns=list("ABCDE"))\n\n\nclass TestXS:\n def test_xs(\n self, float_frame, datetime_frame, using_copy_on_write, warn_copy_on_write\n ):\n float_frame_orig = float_frame.copy()\n idx = float_frame.index[5]\n xs = float_frame.xs(idx)\n for item, value in xs.items():\n if np.isnan(value):\n assert np.isnan(float_frame[item][idx])\n else:\n assert value == float_frame[item][idx]\n\n # mixed-type xs\n test_data = {"A": {"1": 1, "2": 2}, "B": {"1": "1", "2": "2", "3": "3"}}\n frame = DataFrame(test_data)\n xs = frame.xs("1")\n assert xs.dtype == np.object_\n assert xs["A"] == 1\n assert xs["B"] == "1"\n\n with pytest.raises(\n KeyError, match=re.escape("Timestamp('1999-12-31 00:00:00')")\n ):\n datetime_frame.xs(datetime_frame.index[0] - BDay())\n\n # xs get column\n series = float_frame.xs("A", axis=1)\n expected = float_frame["A"]\n tm.assert_series_equal(series, expected)\n\n # view is returned if possible\n series = float_frame.xs("A", axis=1)\n with tm.assert_cow_warning(warn_copy_on_write):\n series[:] = 5\n if using_copy_on_write:\n # but with CoW the view shouldn't propagate mutations\n tm.assert_series_equal(float_frame["A"], float_frame_orig["A"])\n assert not (expected == 5).all()\n else:\n assert (expected == 5).all()\n\n def test_xs_corner(self):\n # pathological mixed-type reordering case\n df = DataFrame(index=[0], columns=Index([], dtype="str"))\n df["A"] = 1.0\n df["B"] = "foo"\n df["C"] = 2.0\n df["D"] = "bar"\n df["E"] = 3.0\n\n xs = df.xs(0)\n exp = Series([1.0, "foo", 2.0, "bar", 3.0], index=list("ABCDE"), name=0)\n tm.assert_series_equal(xs, exp)\n\n # no columns but Index(dtype=object)\n df = DataFrame(index=["a", "b", "c"])\n result = df.xs("a")\n expected = Series([], name="a", dtype=np.float64)\n tm.assert_series_equal(result, expected)\n\n def test_xs_duplicates(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)),\n index=["b", "b", "c", "b", "a"],\n )\n\n cross = df.xs("c")\n exp = df.iloc[2]\n tm.assert_series_equal(cross, exp)\n\n def test_xs_keep_level(self):\n df = DataFrame(\n {\n "day": {0: "sat", 1: "sun"},\n "flavour": {0: "strawberry", 1: "strawberry"},\n "sales": {0: 10, 1: 12},\n "year": {0: 2008, 1: 2008},\n }\n ).set_index(["year", "flavour", "day"])\n result = df.xs("sat", level="day", drop_level=False)\n expected = df[:1]\n tm.assert_frame_equal(result, expected)\n\n result = df.xs((2008, "sat"), level=["year", "day"], drop_level=False)\n tm.assert_frame_equal(result, expected)\n\n def test_xs_view(\n self, using_array_manager, using_copy_on_write, warn_copy_on_write\n ):\n # in 0.14 this will return a view if possible a copy otherwise, but\n # this is numpy dependent\n\n dm = DataFrame(np.arange(20.0).reshape(4, 5), index=range(4), columns=range(5))\n df_orig = dm.copy()\n\n if using_copy_on_write:\n with tm.raises_chained_assignment_error():\n dm.xs(2)[:] = 20\n tm.assert_frame_equal(dm, df_orig)\n elif using_array_manager:\n # INFO(ArrayManager) with ArrayManager getting a row as a view is\n # not possible\n msg = r"\nA value is trying to be set on a copy of a slice from a DataFrame"\n with pytest.raises(SettingWithCopyError, match=msg):\n dm.xs(2)[:] = 20\n assert not (dm.xs(2) == 20).any()\n else:\n with tm.raises_chained_assignment_error():\n dm.xs(2)[:] = 20\n assert (dm.xs(2) == 20).all()\n\n\nclass TestXSWithMultiIndex:\n def test_xs_doc_example(self):\n # TODO: more descriptive name\n # based on example in advanced.rst\n arrays = [\n ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n tuples = list(zip(*arrays))\n\n index = MultiIndex.from_tuples(tuples, names=["first", "second"])\n df = DataFrame(\n np.random.default_rng(2).standard_normal((3, 8)),\n index=["A", "B", "C"],\n columns=index,\n )\n\n result = df.xs(("one", "bar"), level=("second", "first"), axis=1)\n\n expected = df.iloc[:, [0]]\n tm.assert_frame_equal(result, expected)\n\n def test_xs_integer_key(self):\n # see GH#2107\n dates = range(20111201, 20111205)\n ids = list("abcde")\n index = MultiIndex.from_product([dates, ids], names=["date", "secid"])\n df = DataFrame(\n np.random.default_rng(2).standard_normal((len(index), 3)),\n index,\n ["X", "Y", "Z"],\n )\n\n result = df.xs(20111201, level="date")\n expected = df.loc[20111201, :]\n tm.assert_frame_equal(result, expected)\n\n def test_xs_level(self, multiindex_dataframe_random_data):\n df = multiindex_dataframe_random_data\n result = df.xs("two", level="second")\n expected = df[df.index.get_level_values(1) == "two"]\n expected.index = Index(["foo", "bar", "baz", "qux"], name="first")\n tm.assert_frame_equal(result, expected)\n\n def test_xs_level_eq_2(self):\n arr = np.random.default_rng(2).standard_normal((3, 5))\n index = MultiIndex(\n levels=[["a", "p", "x"], ["b", "q", "y"], ["c", "r", "z"]],\n codes=[[2, 0, 1], [2, 0, 1], [2, 0, 1]],\n )\n df = DataFrame(arr, index=index)\n expected = DataFrame(arr[1:2], index=[["a"], ["b"]])\n result = df.xs("c", level=2)\n tm.assert_frame_equal(result, expected)\n\n def test_xs_setting_with_copy_error(\n self,\n multiindex_dataframe_random_data,\n using_copy_on_write,\n warn_copy_on_write,\n ):\n # this is a copy in 0.14\n df = multiindex_dataframe_random_data\n df_orig = df.copy()\n result = df.xs("two", level="second")\n\n if using_copy_on_write or warn_copy_on_write:\n result[:] = 10\n else:\n # setting this will give a SettingWithCopyError\n # as we are trying to write a view\n msg = "A value is trying to be set on a copy of a slice from a DataFrame"\n with pytest.raises(SettingWithCopyError, match=msg):\n result[:] = 10\n tm.assert_frame_equal(df, df_orig)\n\n def test_xs_setting_with_copy_error_multiple(\n self, four_level_index_dataframe, using_copy_on_write, warn_copy_on_write\n ):\n # this is a copy in 0.14\n df = four_level_index_dataframe\n df_orig = df.copy()\n result = df.xs(("a", 4), level=["one", "four"])\n\n if using_copy_on_write or warn_copy_on_write:\n result[:] = 10\n else:\n # setting this will give a SettingWithCopyError\n # as we are trying to write a view\n msg = "A value is trying to be set on a copy of a slice from a DataFrame"\n with pytest.raises(SettingWithCopyError, match=msg):\n result[:] = 10\n tm.assert_frame_equal(df, df_orig)\n\n @pytest.mark.parametrize("key, level", [("one", "second"), (["one"], ["second"])])\n def test_xs_with_duplicates(self, key, level, multiindex_dataframe_random_data):\n # see GH#13719\n frame = multiindex_dataframe_random_data\n df = concat([frame] * 2)\n assert df.index.is_unique is False\n expected = concat([frame.xs("one", level="second")] * 2)\n\n if isinstance(key, list):\n result = df.xs(tuple(key), level=level)\n else:\n result = df.xs(key, level=level)\n tm.assert_frame_equal(result, expected)\n\n def test_xs_missing_values_in_index(self):\n # see GH#6574\n # missing values in returned index should be preserved\n acc = [\n ("a", "abcde", 1),\n ("b", "bbcde", 2),\n ("y", "yzcde", 25),\n ("z", "xbcde", 24),\n ("z", None, 26),\n ("z", "zbcde", 25),\n ("z", "ybcde", 26),\n ]\n df = DataFrame(acc, columns=["a1", "a2", "cnt"]).set_index(["a1", "a2"])\n expected = DataFrame(\n {"cnt": [24, 26, 25, 26]},\n index=Index(["xbcde", np.nan, "zbcde", "ybcde"], name="a2"),\n )\n\n result = df.xs("z", level="a1")\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "key, level, exp_arr, exp_index",\n [\n ("a", "lvl0", lambda x: x[:, 0:2], Index(["bar", "foo"], name="lvl1")),\n ("foo", "lvl1", lambda x: x[:, 1:2], Index(["a"], name="lvl0")),\n ],\n )\n def test_xs_named_levels_axis_eq_1(self, key, level, exp_arr, exp_index):\n # see GH#2903\n arr = np.random.default_rng(2).standard_normal((4, 4))\n index = MultiIndex(\n levels=[["a", "b"], ["bar", "foo", "hello", "world"]],\n codes=[[0, 0, 1, 1], [0, 1, 2, 3]],\n names=["lvl0", "lvl1"],\n )\n df = DataFrame(arr, columns=index)\n result = df.xs(key, level=level, axis=1)\n expected = DataFrame(exp_arr(arr), columns=exp_index)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "indexer",\n [\n lambda df: df.xs(("a", 4), level=["one", "four"]),\n lambda df: df.xs("a").xs(4, level="four"),\n ],\n )\n def test_xs_level_multiple(self, indexer, four_level_index_dataframe):\n df = four_level_index_dataframe\n expected_values = [[0.4473, 1.4152, 0.2834, 1.00661, 0.1744]]\n expected_index = MultiIndex(\n levels=[["q"], [20.0]], codes=[[0], [0]], names=["two", "three"]\n )\n expected = DataFrame(\n expected_values, index=expected_index, columns=list("ABCDE")\n )\n result = indexer(df)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "indexer", [lambda df: df.xs("a", level=0), lambda df: df.xs("a")]\n )\n def test_xs_level0(self, indexer, four_level_index_dataframe):\n df = four_level_index_dataframe\n expected_values = [\n [-0.5109, -2.3358, -0.4645, 0.05076, 0.364],\n [0.4473, 1.4152, 0.2834, 1.00661, 0.1744],\n ]\n expected_index = MultiIndex(\n levels=[["b", "q"], [10.0032, 20.0], [4, 5]],\n codes=[[0, 1], [0, 1], [1, 0]],\n names=["two", "three", "four"],\n )\n expected = DataFrame(\n expected_values, index=expected_index, columns=list("ABCDE")\n )\n\n result = indexer(df)\n tm.assert_frame_equal(result, expected)\n\n def test_xs_values(self, multiindex_dataframe_random_data):\n df = multiindex_dataframe_random_data\n result = df.xs(("bar", "two")).values\n expected = df.values[4]\n tm.assert_almost_equal(result, expected)\n\n def test_xs_loc_equality(self, multiindex_dataframe_random_data):\n df = multiindex_dataframe_random_data\n result = df.xs(("bar", "two"))\n expected = df.loc[("bar", "two")]\n tm.assert_series_equal(result, expected)\n\n def test_xs_IndexSlice_argument_not_implemented(self, frame_or_series):\n # GH#35301\n\n index = MultiIndex(\n levels=[[("foo", "bar", 0), ("foo", "baz", 0), ("foo", "qux", 0)], [0, 1]],\n codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],\n )\n\n obj = DataFrame(np.random.default_rng(2).standard_normal((6, 4)), index=index)\n if frame_or_series is Series:\n obj = obj[0]\n\n expected = obj.iloc[-2:].droplevel(0)\n\n result = obj.xs(IndexSlice[("foo", "qux", 0), :])\n tm.assert_equal(result, expected)\n\n result = obj.loc[IndexSlice[("foo", "qux", 0), :]]\n tm.assert_equal(result, expected)\n\n def test_xs_levels_raises(self, frame_or_series):\n obj = DataFrame({"A": [1, 2, 3]})\n if frame_or_series is Series:\n obj = obj["A"]\n\n msg = "Index must be a MultiIndex"\n with pytest.raises(TypeError, match=msg):\n obj.xs(0, level="as")\n\n def test_xs_multiindex_droplevel_false(self):\n # GH#19056\n mi = MultiIndex.from_tuples(\n [("a", "x"), ("a", "y"), ("b", "x")], names=["level1", "level2"]\n )\n df = DataFrame([[1, 2, 3]], columns=mi)\n result = df.xs("a", axis=1, drop_level=False)\n expected = DataFrame(\n [[1, 2]],\n columns=MultiIndex.from_tuples(\n [("a", "x"), ("a", "y")], names=["level1", "level2"]\n ),\n )\n tm.assert_frame_equal(result, expected)\n\n def test_xs_droplevel_false(self):\n # GH#19056\n df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))\n result = df.xs("a", axis=1, drop_level=False)\n expected = DataFrame({"a": [1]})\n tm.assert_frame_equal(result, expected)\n\n def test_xs_droplevel_false_view(\n self, using_array_manager, using_copy_on_write, warn_copy_on_write\n ):\n # GH#37832\n df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))\n result = df.xs("a", axis=1, drop_level=False)\n # check that result still views the same data as df\n assert np.shares_memory(result.iloc[:, 0]._values, df.iloc[:, 0]._values)\n\n with tm.assert_cow_warning(warn_copy_on_write):\n df.iloc[0, 0] = 2\n if using_copy_on_write:\n # with copy on write the subset is never modified\n expected = DataFrame({"a": [1]})\n else:\n # modifying original df also modifies result when having a single block\n expected = DataFrame({"a": [2]})\n tm.assert_frame_equal(result, expected)\n\n # with mixed dataframe, modifying the parent doesn't modify result\n # TODO the "split" path behaves differently here as with single block\n df = DataFrame([[1, 2.5, "a"]], columns=Index(["a", "b", "c"]))\n result = df.xs("a", axis=1, drop_level=False)\n df.iloc[0, 0] = 2\n if using_copy_on_write:\n # with copy on write the subset is never modified\n expected = DataFrame({"a": [1]})\n elif using_array_manager:\n # Here the behavior is consistent\n expected = DataFrame({"a": [2]})\n else:\n # FIXME: iloc does not update the array inplace using\n # "split" path\n expected = DataFrame({"a": [1]})\n tm.assert_frame_equal(result, expected)\n\n def test_xs_list_indexer_droplevel_false(self):\n # GH#41760\n mi = MultiIndex.from_tuples([("x", "m", "a"), ("x", "n", "b"), ("y", "o", "c")])\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi)\n with pytest.raises(KeyError, match="y"):\n df.xs(("x", "y"), drop_level=False, axis=1)\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\test_xs.py
test_xs.py
Python
16,012
0.95
0.09009
0.096104
react-lib
338
2024-06-17T02:38:28.605287
GPL-3.0
true
e84cbca5133b3e8ef200b22ff4be48db
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_coercion.cpython-313.pyc
test_coercion.cpython-313.pyc
Other
10,225
0.8
0.008475
0
node-utils
357
2024-04-12T16:48:22.661061
BSD-3-Clause
true
4026cc0504291b6536d489ea690dd405
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_delitem.cpython-313.pyc
test_delitem.cpython-313.pyc
Other
3,615
0.8
0
0
python-kit
740
2025-05-09T12:05:29.656375
MIT
true
c85aac8d99528067e0d2ff3fdb76580b
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_get.cpython-313.pyc
test_get.cpython-313.pyc
Other
1,497
0.8
0
0
awesome-app
132
2024-09-06T01:43:25.718426
MIT
true
effca2398dd400dd5c09ee26a1e195c4
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_getitem.cpython-313.pyc
test_getitem.cpython-313.pyc
Other
24,137
0.8
0
0.003831
awesome-app
331
2023-09-23T03:08:49.723335
Apache-2.0
true
83b4d2603bae06c99d523150db47f335
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_get_value.cpython-313.pyc
test_get_value.cpython-313.pyc
Other
1,588
0.8
0
0
vue-tools
744
2024-04-11T01:56:20.312312
Apache-2.0
true
cc3ccaa1640d542dff7f8e55fb908357
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_insert.cpython-313.pyc
test_insert.cpython-313.pyc
Other
7,248
0.8
0.009091
0
vue-tools
665
2025-01-04T03:21:21.386425
GPL-3.0
true
a4ff61d1e3676bea26af4340f617e7c5
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_mask.cpython-313.pyc
test_mask.cpython-313.pyc
Other
9,543
0.8
0.012195
0.012346
vue-tools
411
2024-06-27T19:19:58.351638
MIT
true
c127b558b53bcc320056a3fce6f87767
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_setitem.cpython-313.pyc
test_setitem.cpython-313.pyc
Other
81,368
0.75
0
0.006443
python-kit
8
2025-04-19T10:32:39.467988
Apache-2.0
true
3b63072fa43ab80c56d50099eebf562f
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_set_value.cpython-313.pyc
test_set_value.cpython-313.pyc
Other
4,612
0.8
0
0
node-utils
244
2025-01-16T22:14:51.091350
BSD-3-Clause
true
b84b81ba15096bbedff1884f6a0250f7
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_take.cpython-313.pyc
test_take.cpython-313.pyc
Other
5,362
0.7
0
0
node-utils
454
2024-07-12T04:48:52.163815
BSD-3-Clause
true
57c791730a28b8991f844b6b290efc45
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_where.cpython-313.pyc
test_where.cpython-313.pyc
Other
59,861
0.6
0.002999
0.00916
awesome-app
711
2023-12-09T13:08:36.197208
BSD-3-Clause
true
60e8946665b4102efd68a026cee0c631
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\test_xs.cpython-313.pyc
test_xs.cpython-313.pyc
Other
22,731
0.8
0
0.025105
python-kit
231
2023-08-03T20:24:37.221441
GPL-3.0
true
c91f16a36255a7344db8eaf96b8be12e
\n\n
.venv\Lib\site-packages\pandas\tests\frame\indexing\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
202
0.7
0
0
awesome-app
722
2024-07-07T21:41:11.190757
Apache-2.0
true
4297f422e4a43e5bb3f8914934ca2cb3
import pytest\n\nfrom pandas import Index\nimport pandas._testing as tm\n\n\ndef test_add_prefix_suffix(float_frame):\n with_prefix = float_frame.add_prefix("foo#")\n expected = Index([f"foo#{c}" for c in float_frame.columns])\n tm.assert_index_equal(with_prefix.columns, expected)\n\n with_suffix = float_frame.add_suffix("#foo")\n expected = Index([f"{c}#foo" for c in float_frame.columns])\n tm.assert_index_equal(with_suffix.columns, expected)\n\n with_pct_prefix = float_frame.add_prefix("%")\n expected = Index([f"%{c}" for c in float_frame.columns])\n tm.assert_index_equal(with_pct_prefix.columns, expected)\n\n with_pct_suffix = float_frame.add_suffix("%")\n expected = Index([f"{c}%" for c in float_frame.columns])\n tm.assert_index_equal(with_pct_suffix.columns, expected)\n\n\ndef test_add_prefix_suffix_axis(float_frame):\n # GH 47819\n with_prefix = float_frame.add_prefix("foo#", axis=0)\n expected = Index([f"foo#{c}" for c in float_frame.index])\n tm.assert_index_equal(with_prefix.index, expected)\n\n with_prefix = float_frame.add_prefix("foo#", axis=1)\n expected = Index([f"foo#{c}" for c in float_frame.columns])\n tm.assert_index_equal(with_prefix.columns, expected)\n\n with_pct_suffix = float_frame.add_suffix("#foo", axis=0)\n expected = Index([f"{c}#foo" for c in float_frame.index])\n tm.assert_index_equal(with_pct_suffix.index, expected)\n\n with_pct_suffix = float_frame.add_suffix("#foo", axis=1)\n expected = Index([f"{c}#foo" for c in float_frame.columns])\n tm.assert_index_equal(with_pct_suffix.columns, expected)\n\n\ndef test_add_prefix_suffix_invalid_axis(float_frame):\n with pytest.raises(ValueError, match="No axis named 2 for object type DataFrame"):\n float_frame.add_prefix("foo#", axis=2)\n\n with pytest.raises(ValueError, match="No axis named 2 for object type DataFrame"):\n float_frame.add_suffix("foo#", axis=2)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_add_prefix_suffix.py
test_add_prefix_suffix.py
Python
1,910
0.95
0.265306
0.028571
python-kit
575
2024-09-06T17:35:23.143408
MIT
true
01ffd51fd8b64a3c417cae477d997395
from datetime import timezone\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameAlign:\n def test_align_asfreq_method_raises(self):\n df = DataFrame({"A": [1, np.nan, 2]})\n msg = "Invalid fill method"\n msg2 = "The 'method', 'limit', and 'fill_axis' keywords"\n with pytest.raises(ValueError, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=msg2):\n df.align(df.iloc[::-1], method="asfreq")\n\n def test_frame_align_aware(self):\n idx1 = date_range("2001", periods=5, freq="h", tz="US/Eastern")\n idx2 = date_range("2001", periods=5, freq="2h", tz="US/Eastern")\n df1 = DataFrame(np.random.default_rng(2).standard_normal((len(idx1), 3)), idx1)\n df2 = DataFrame(np.random.default_rng(2).standard_normal((len(idx2), 3)), idx2)\n new1, new2 = df1.align(df2)\n assert df1.index.tz == new1.index.tz\n assert df2.index.tz == new2.index.tz\n\n # different timezones convert to UTC\n\n # frame with frame\n df1_central = df1.tz_convert("US/Central")\n new1, new2 = df1.align(df1_central)\n assert new1.index.tz is timezone.utc\n assert new2.index.tz is timezone.utc\n\n # frame with Series\n new1, new2 = df1.align(df1_central[0], axis=0)\n assert new1.index.tz is timezone.utc\n assert new2.index.tz is timezone.utc\n\n df1[0].align(df1_central, axis=0)\n assert new1.index.tz is timezone.utc\n assert new2.index.tz is timezone.utc\n\n def test_align_float(self, float_frame, using_copy_on_write):\n af, bf = float_frame.align(float_frame)\n assert af._mgr is not float_frame._mgr\n\n af, bf = float_frame.align(float_frame, copy=False)\n if not using_copy_on_write:\n assert af._mgr is float_frame._mgr\n else:\n assert af._mgr is not float_frame._mgr\n\n # axis = 0\n other = float_frame.iloc[:-5, :3]\n af, bf = float_frame.align(other, axis=0, fill_value=-1)\n\n tm.assert_index_equal(bf.columns, other.columns)\n\n # test fill value\n join_idx = float_frame.index.join(other.index)\n diff_a = float_frame.index.difference(join_idx)\n diff_a_vals = af.reindex(diff_a).values\n assert (diff_a_vals == -1).all()\n\n af, bf = float_frame.align(other, join="right", axis=0)\n tm.assert_index_equal(bf.columns, other.columns)\n tm.assert_index_equal(bf.index, other.index)\n tm.assert_index_equal(af.index, other.index)\n\n # axis = 1\n other = float_frame.iloc[:-5, :3].copy()\n af, bf = float_frame.align(other, axis=1)\n tm.assert_index_equal(bf.columns, float_frame.columns)\n tm.assert_index_equal(bf.index, other.index)\n\n # test fill value\n join_idx = float_frame.index.join(other.index)\n diff_a = float_frame.index.difference(join_idx)\n diff_a_vals = af.reindex(diff_a).values\n\n assert (diff_a_vals == -1).all()\n\n af, bf = float_frame.align(other, join="inner", axis=1)\n tm.assert_index_equal(bf.columns, other.columns)\n\n msg = (\n "The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "\n "are deprecated"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n af, bf = float_frame.align(other, join="inner", axis=1, method="pad")\n tm.assert_index_equal(bf.columns, other.columns)\n\n msg = (\n "The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "\n "are deprecated"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n af, bf = float_frame.align(\n other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=None\n )\n tm.assert_index_equal(bf.index, Index([]).astype(bf.index.dtype))\n\n msg = (\n "The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "\n "are deprecated"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n af, bf = float_frame.align(\n other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0\n )\n tm.assert_index_equal(bf.index, Index([]).astype(bf.index.dtype))\n\n # Try to align DataFrame to Series along bad axis\n msg = "No axis named 2 for object type DataFrame"\n with pytest.raises(ValueError, match=msg):\n float_frame.align(af.iloc[0, :3], join="inner", axis=2)\n\n def test_align_frame_with_series(self, float_frame):\n # align dataframe to series with broadcast or not\n idx = float_frame.index\n s = Series(range(len(idx)), index=idx)\n\n left, right = float_frame.align(s, axis=0)\n tm.assert_index_equal(left.index, float_frame.index)\n tm.assert_index_equal(right.index, float_frame.index)\n assert isinstance(right, Series)\n\n msg = "The 'broadcast_axis' keyword in DataFrame.align is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n left, right = float_frame.align(s, broadcast_axis=1)\n tm.assert_index_equal(left.index, float_frame.index)\n expected = {c: s for c in float_frame.columns}\n expected = DataFrame(\n expected, index=float_frame.index, columns=float_frame.columns\n )\n tm.assert_frame_equal(right, expected)\n\n def test_align_series_condition(self):\n # see gh-9558\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n result = df[df["a"] == 2]\n expected = DataFrame([[2, 5]], index=[1], columns=["a", "b"])\n tm.assert_frame_equal(result, expected)\n\n result = df.where(df["a"] == 2, 0)\n expected = DataFrame({"a": [0, 2, 0], "b": [0, 5, 0]})\n tm.assert_frame_equal(result, expected)\n\n def test_align_int(self, int_frame):\n # test other non-float types\n other = DataFrame(index=range(5), columns=["A", "B", "C"])\n\n msg = (\n "The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "\n "are deprecated"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n af, bf = int_frame.align(other, join="inner", axis=1, method="pad")\n tm.assert_index_equal(bf.columns, other.columns)\n\n def test_align_mixed_type(self, float_string_frame):\n msg = (\n "The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "\n "are deprecated"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n af, bf = float_string_frame.align(\n float_string_frame, join="inner", axis=1, method="pad"\n )\n tm.assert_index_equal(bf.columns, float_string_frame.columns)\n\n def test_align_mixed_float(self, mixed_float_frame):\n # mixed floats/ints\n other = DataFrame(index=range(5), columns=["A", "B", "C"])\n\n msg = (\n "The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "\n "are deprecated"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n af, bf = mixed_float_frame.align(\n other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0\n )\n tm.assert_index_equal(bf.index, Index([]))\n\n def test_align_mixed_int(self, mixed_int_frame):\n other = DataFrame(index=range(5), columns=["A", "B", "C"])\n\n msg = (\n "The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "\n "are deprecated"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n af, bf = mixed_int_frame.align(\n other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0\n )\n tm.assert_index_equal(bf.index, Index([]))\n\n @pytest.mark.parametrize(\n "l_ordered,r_ordered,expected",\n [\n [True, True, pd.CategoricalIndex],\n [True, False, Index],\n [False, True, Index],\n [False, False, pd.CategoricalIndex],\n ],\n )\n def test_align_categorical(self, l_ordered, r_ordered, expected):\n # GH-28397\n df_1 = DataFrame(\n {\n "A": np.arange(6, dtype="int64"),\n "B": Series(list("aabbca")).astype(\n pd.CategoricalDtype(list("cab"), ordered=l_ordered)\n ),\n }\n ).set_index("B")\n df_2 = DataFrame(\n {\n "A": np.arange(5, dtype="int64"),\n "B": Series(list("babca")).astype(\n pd.CategoricalDtype(list("cab"), ordered=r_ordered)\n ),\n }\n ).set_index("B")\n\n aligned_1, aligned_2 = df_1.align(df_2)\n assert isinstance(aligned_1.index, expected)\n assert isinstance(aligned_2.index, expected)\n tm.assert_index_equal(aligned_1.index, aligned_2.index)\n\n def test_align_multiindex(self):\n # GH#10665\n # same test cases as test_align_multiindex in test_series.py\n\n midx = pd.MultiIndex.from_product(\n [range(2), range(3), range(2)], names=("a", "b", "c")\n )\n idx = Index(range(2), name="b")\n df1 = DataFrame(np.arange(12, dtype="int64"), index=midx)\n df2 = DataFrame(np.arange(2, dtype="int64"), index=idx)\n\n # these must be the same results (but flipped)\n res1l, res1r = df1.align(df2, join="left")\n res2l, res2r = df2.align(df1, join="right")\n\n expl = df1\n tm.assert_frame_equal(expl, res1l)\n tm.assert_frame_equal(expl, res2r)\n expr = DataFrame([0, 0, 1, 1, np.nan, np.nan] * 2, index=midx)\n tm.assert_frame_equal(expr, res1r)\n tm.assert_frame_equal(expr, res2l)\n\n res1l, res1r = df1.align(df2, join="right")\n res2l, res2r = df2.align(df1, join="left")\n\n exp_idx = pd.MultiIndex.from_product(\n [range(2), range(2), range(2)], names=("a", "b", "c")\n )\n expl = DataFrame([0, 1, 2, 3, 6, 7, 8, 9], index=exp_idx)\n tm.assert_frame_equal(expl, res1l)\n tm.assert_frame_equal(expl, res2r)\n expr = DataFrame([0, 0, 1, 1] * 2, index=exp_idx)\n tm.assert_frame_equal(expr, res1r)\n tm.assert_frame_equal(expr, res2l)\n\n def test_align_series_combinations(self):\n df = DataFrame({"a": [1, 3, 5], "b": [1, 3, 5]}, index=list("ACE"))\n s = Series([1, 2, 4], index=list("ABD"), name="x")\n\n # frame + series\n res1, res2 = df.align(s, axis=0)\n exp1 = DataFrame(\n {"a": [1, np.nan, 3, np.nan, 5], "b": [1, np.nan, 3, np.nan, 5]},\n index=list("ABCDE"),\n )\n exp2 = Series([1, 2, np.nan, 4, np.nan], index=list("ABCDE"), name="x")\n\n tm.assert_frame_equal(res1, exp1)\n tm.assert_series_equal(res2, exp2)\n\n # series + frame\n res1, res2 = s.align(df)\n tm.assert_series_equal(res1, exp2)\n tm.assert_frame_equal(res2, exp1)\n\n def test_multiindex_align_to_series_with_common_index_level(self):\n # GH-46001\n foo_index = Index([1, 2, 3], name="foo")\n bar_index = Index([1, 2], name="bar")\n\n series = Series([1, 2], index=bar_index, name="foo_series")\n df = DataFrame(\n {"col": np.arange(6)},\n index=pd.MultiIndex.from_product([foo_index, bar_index]),\n )\n\n expected_r = Series([1, 2] * 3, index=df.index, name="foo_series")\n result_l, result_r = df.align(series, axis=0)\n\n tm.assert_frame_equal(result_l, df)\n tm.assert_series_equal(result_r, expected_r)\n\n def test_multiindex_align_to_series_with_common_index_level_missing_in_left(self):\n # GH-46001\n foo_index = Index([1, 2, 3], name="foo")\n bar_index = Index([1, 2], name="bar")\n\n series = Series(\n [1, 2, 3, 4], index=Index([1, 2, 3, 4], name="bar"), name="foo_series"\n )\n df = DataFrame(\n {"col": np.arange(6)},\n index=pd.MultiIndex.from_product([foo_index, bar_index]),\n )\n\n expected_r = Series([1, 2] * 3, index=df.index, name="foo_series")\n result_l, result_r = df.align(series, axis=0)\n\n tm.assert_frame_equal(result_l, df)\n tm.assert_series_equal(result_r, expected_r)\n\n def test_multiindex_align_to_series_with_common_index_level_missing_in_right(self):\n # GH-46001\n foo_index = Index([1, 2, 3], name="foo")\n bar_index = Index([1, 2, 3, 4], name="bar")\n\n series = Series([1, 2], index=Index([1, 2], name="bar"), name="foo_series")\n df = DataFrame(\n {"col": np.arange(12)},\n index=pd.MultiIndex.from_product([foo_index, bar_index]),\n )\n\n expected_r = Series(\n [1, 2, np.nan, np.nan] * 3, index=df.index, name="foo_series"\n )\n result_l, result_r = df.align(series, axis=0)\n\n tm.assert_frame_equal(result_l, df)\n tm.assert_series_equal(result_r, expected_r)\n\n def test_multiindex_align_to_series_with_common_index_level_missing_in_both(self):\n # GH-46001\n foo_index = Index([1, 2, 3], name="foo")\n bar_index = Index([1, 3, 4], name="bar")\n\n series = Series(\n [1, 2, 3], index=Index([1, 2, 4], name="bar"), name="foo_series"\n )\n df = DataFrame(\n {"col": np.arange(9)},\n index=pd.MultiIndex.from_product([foo_index, bar_index]),\n )\n\n expected_r = Series([1, np.nan, 3] * 3, index=df.index, name="foo_series")\n result_l, result_r = df.align(series, axis=0)\n\n tm.assert_frame_equal(result_l, df)\n tm.assert_series_equal(result_r, expected_r)\n\n def test_multiindex_align_to_series_with_common_index_level_non_unique_cols(self):\n # GH-46001\n foo_index = Index([1, 2, 3], name="foo")\n bar_index = Index([1, 2], name="bar")\n\n series = Series([1, 2], index=bar_index, name="foo_series")\n df = DataFrame(\n np.arange(18).reshape(6, 3),\n index=pd.MultiIndex.from_product([foo_index, bar_index]),\n )\n df.columns = ["cfoo", "cbar", "cfoo"]\n\n expected = Series([1, 2] * 3, index=df.index, name="foo_series")\n result_left, result_right = df.align(series, axis=0)\n\n tm.assert_series_equal(result_right, expected)\n tm.assert_index_equal(result_left.columns, df.columns)\n\n def test_missing_axis_specification_exception(self):\n df = DataFrame(np.arange(50).reshape((10, 5)))\n series = Series(np.arange(5))\n\n with pytest.raises(ValueError, match=r"axis=0 or 1"):\n df.align(series)\n\n @pytest.mark.parametrize("method", ["pad", "bfill"])\n @pytest.mark.parametrize("axis", [0, 1, None])\n @pytest.mark.parametrize("fill_axis", [0, 1])\n @pytest.mark.parametrize("how", ["inner", "outer", "left", "right"])\n @pytest.mark.parametrize(\n "left_slice",\n [\n [slice(4), slice(10)],\n [slice(0), slice(0)],\n ],\n )\n @pytest.mark.parametrize(\n "right_slice",\n [\n [slice(2, None), slice(6, None)],\n [slice(0), slice(0)],\n ],\n )\n @pytest.mark.parametrize("limit", [1, None])\n def test_align_fill_method(\n self, how, method, axis, fill_axis, float_frame, left_slice, right_slice, limit\n ):\n frame = float_frame\n left = frame.iloc[left_slice[0], left_slice[1]]\n right = frame.iloc[right_slice[0], right_slice[1]]\n\n msg = (\n "The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "\n "are deprecated"\n )\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n aa, ab = left.align(\n right,\n axis=axis,\n join=how,\n method=method,\n limit=limit,\n fill_axis=fill_axis,\n )\n\n join_index, join_columns = None, None\n\n ea, eb = left, right\n if axis is None or axis == 0:\n join_index = left.index.join(right.index, how=how)\n ea = ea.reindex(index=join_index)\n eb = eb.reindex(index=join_index)\n\n if axis is None or axis == 1:\n join_columns = left.columns.join(right.columns, how=how)\n ea = ea.reindex(columns=join_columns)\n eb = eb.reindex(columns=join_columns)\n\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n ea = ea.fillna(axis=fill_axis, method=method, limit=limit)\n eb = eb.fillna(axis=fill_axis, method=method, limit=limit)\n\n tm.assert_frame_equal(aa, ea)\n tm.assert_frame_equal(ab, eb)\n\n def test_align_series_check_copy(self):\n # GH#\n df = DataFrame({0: [1, 2]})\n ser = Series([1], name=0)\n expected = ser.copy()\n result, other = df.align(ser, axis=1)\n ser.iloc[0] = 100\n tm.assert_series_equal(other, expected)\n\n def test_align_identical_different_object(self):\n # GH#51032\n df = DataFrame({"a": [1, 2]})\n ser = Series([3, 4])\n result, result2 = df.align(ser, axis=0)\n tm.assert_frame_equal(result, df)\n tm.assert_series_equal(result2, ser)\n assert df is not result\n assert ser is not result2\n\n def test_align_identical_different_object_columns(self):\n # GH#51032\n df = DataFrame({"a": [1, 2]})\n ser = Series([1], index=["a"])\n result, result2 = df.align(ser, axis=1)\n tm.assert_frame_equal(result, df)\n tm.assert_series_equal(result2, ser)\n assert df is not result\n assert ser is not result2\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_align.py
test_align.py
Python
17,941
0.95
0.057851
0.064356
vue-tools
301
2023-08-12T23:40:12.107923
GPL-3.0
true
2cc7bc354519f99af7c88a77cf56e289
from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs.offsets import MonthEnd\n\nfrom pandas import (\n DataFrame,\n DatetimeIndex,\n Series,\n date_range,\n period_range,\n to_datetime,\n)\nimport pandas._testing as tm\n\nfrom pandas.tseries import offsets\n\n\nclass TestAsFreq:\n @pytest.fixture(params=["s", "ms", "us", "ns"])\n def unit(self, request):\n return request.param\n\n def test_asfreq2(self, frame_or_series):\n ts = frame_or_series(\n [0.0, 1.0, 2.0],\n index=DatetimeIndex(\n [\n datetime(2009, 10, 30),\n datetime(2009, 11, 30),\n datetime(2009, 12, 31),\n ],\n dtype="M8[ns]",\n freq="BME",\n ),\n )\n\n daily_ts = ts.asfreq("B")\n monthly_ts = daily_ts.asfreq("BME")\n tm.assert_equal(monthly_ts, ts)\n\n daily_ts = ts.asfreq("B", method="pad")\n monthly_ts = daily_ts.asfreq("BME")\n tm.assert_equal(monthly_ts, ts)\n\n daily_ts = ts.asfreq(offsets.BDay())\n monthly_ts = daily_ts.asfreq(offsets.BMonthEnd())\n tm.assert_equal(monthly_ts, ts)\n\n result = ts[:0].asfreq("ME")\n assert len(result) == 0\n assert result is not ts\n\n if frame_or_series is Series:\n daily_ts = ts.asfreq("D", fill_value=-1)\n result = daily_ts.value_counts().sort_index()\n expected = Series(\n [60, 1, 1, 1], index=[-1.0, 2.0, 1.0, 0.0], name="count"\n ).sort_index()\n tm.assert_series_equal(result, expected)\n\n def test_asfreq_datetimeindex_empty(self, frame_or_series):\n # GH#14320\n index = DatetimeIndex(["2016-09-29 11:00"])\n expected = frame_or_series(index=index, dtype=object).asfreq("h")\n result = frame_or_series([3], index=index.copy()).asfreq("h")\n tm.assert_index_equal(expected.index, result.index)\n\n @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"])\n def test_tz_aware_asfreq_smoke(self, tz, frame_or_series):\n dr = date_range("2011-12-01", "2012-07-20", freq="D", tz=tz)\n\n obj = frame_or_series(\n np.random.default_rng(2).standard_normal(len(dr)), index=dr\n )\n\n # it works!\n obj.asfreq("min")\n\n def test_asfreq_normalize(self, frame_or_series):\n rng = date_range("1/1/2000 09:30", periods=20)\n norm = date_range("1/1/2000", periods=20)\n\n vals = np.random.default_rng(2).standard_normal((20, 3))\n\n obj = DataFrame(vals, index=rng)\n expected = DataFrame(vals, index=norm)\n if frame_or_series is Series:\n obj = obj[0]\n expected = expected[0]\n\n result = obj.asfreq("D", normalize=True)\n tm.assert_equal(result, expected)\n\n def test_asfreq_keep_index_name(self, frame_or_series):\n # GH#9854\n index_name = "bar"\n index = date_range("20130101", periods=20, name=index_name)\n obj = DataFrame(list(range(20)), columns=["foo"], index=index)\n obj = tm.get_obj(obj, frame_or_series)\n\n assert index_name == obj.index.name\n assert index_name == obj.asfreq("10D").index.name\n\n def test_asfreq_ts(self, frame_or_series):\n index = period_range(freq="Y", start="1/1/2001", end="12/31/2010")\n obj = DataFrame(\n np.random.default_rng(2).standard_normal((len(index), 3)), index=index\n )\n obj = tm.get_obj(obj, frame_or_series)\n\n result = obj.asfreq("D", how="end")\n exp_index = index.asfreq("D", how="end")\n assert len(result) == len(obj)\n tm.assert_index_equal(result.index, exp_index)\n\n result = obj.asfreq("D", how="start")\n exp_index = index.asfreq("D", how="start")\n assert len(result) == len(obj)\n tm.assert_index_equal(result.index, exp_index)\n\n def test_asfreq_resample_set_correct_freq(self, frame_or_series):\n # GH#5613\n # we test if .asfreq() and .resample() set the correct value for .freq\n dti = to_datetime(["2012-01-01", "2012-01-02", "2012-01-03"])\n obj = DataFrame({"col": [1, 2, 3]}, index=dti)\n obj = tm.get_obj(obj, frame_or_series)\n\n # testing the settings before calling .asfreq() and .resample()\n assert obj.index.freq is None\n assert obj.index.inferred_freq == "D"\n\n # does .asfreq() set .freq correctly?\n assert obj.asfreq("D").index.freq == "D"\n\n # does .resample() set .freq correctly?\n assert obj.resample("D").asfreq().index.freq == "D"\n\n def test_asfreq_empty(self, datetime_frame):\n # test does not blow up on length-0 DataFrame\n zero_length = datetime_frame.reindex([])\n result = zero_length.asfreq("BME")\n assert result is not zero_length\n\n def test_asfreq(self, datetime_frame):\n offset_monthly = datetime_frame.asfreq(offsets.BMonthEnd())\n rule_monthly = datetime_frame.asfreq("BME")\n\n tm.assert_frame_equal(offset_monthly, rule_monthly)\n\n rule_monthly.asfreq("B", method="pad")\n # TODO: actually check that this worked.\n\n # don't forget!\n rule_monthly.asfreq("B", method="pad")\n\n def test_asfreq_datetimeindex(self):\n df = DataFrame(\n {"A": [1, 2, 3]},\n index=[datetime(2011, 11, 1), datetime(2011, 11, 2), datetime(2011, 11, 3)],\n )\n df = df.asfreq("B")\n assert isinstance(df.index, DatetimeIndex)\n\n ts = df["A"].asfreq("B")\n assert isinstance(ts.index, DatetimeIndex)\n\n def test_asfreq_fillvalue(self):\n # test for fill value during upsampling, related to issue 3715\n\n # setup\n rng = date_range("1/1/2016", periods=10, freq="2s")\n # Explicit cast to 'float' to avoid implicit cast when setting None\n ts = Series(np.arange(len(rng)), index=rng, dtype="float")\n df = DataFrame({"one": ts})\n\n # insert pre-existing missing value\n df.loc["2016-01-01 00:00:08", "one"] = None\n\n actual_df = df.asfreq(freq="1s", fill_value=9.0)\n expected_df = df.asfreq(freq="1s").fillna(9.0)\n expected_df.loc["2016-01-01 00:00:08", "one"] = None\n tm.assert_frame_equal(expected_df, actual_df)\n\n expected_series = ts.asfreq(freq="1s").fillna(9.0)\n actual_series = ts.asfreq(freq="1s", fill_value=9.0)\n tm.assert_series_equal(expected_series, actual_series)\n\n def test_asfreq_with_date_object_index(self, frame_or_series):\n rng = date_range("1/1/2000", periods=20)\n ts = frame_or_series(np.random.default_rng(2).standard_normal(20), index=rng)\n\n ts2 = ts.copy()\n ts2.index = [x.date() for x in ts2.index]\n\n result = ts2.asfreq("4h", method="ffill")\n expected = ts.asfreq("4h", method="ffill")\n tm.assert_equal(result, expected)\n\n def test_asfreq_with_unsorted_index(self, frame_or_series):\n # GH#39805\n # Test that rows are not dropped when the datetime index is out of order\n index = to_datetime(["2021-01-04", "2021-01-02", "2021-01-03", "2021-01-01"])\n result = frame_or_series(range(4), index=index)\n\n expected = result.reindex(sorted(index))\n expected.index = expected.index._with_freq("infer")\n\n result = result.asfreq("D")\n tm.assert_equal(result, expected)\n\n def test_asfreq_after_normalize(self, unit):\n # https://github.com/pandas-dev/pandas/issues/50727\n result = DatetimeIndex(\n date_range("2000", periods=2).as_unit(unit).normalize(), freq="D"\n )\n expected = DatetimeIndex(["2000-01-01", "2000-01-02"], freq="D").as_unit(unit)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n "freq, freq_half",\n [\n ("2ME", "ME"),\n (MonthEnd(2), MonthEnd(1)),\n ],\n )\n def test_asfreq_2ME(self, freq, freq_half):\n index = date_range("1/1/2000", periods=6, freq=freq_half)\n df = DataFrame({"s": Series([0.0, 1.0, 2.0, 3.0, 4.0, 5.0], index=index)})\n expected = df.asfreq(freq=freq)\n\n index = date_range("1/1/2000", periods=3, freq=freq)\n result = DataFrame({"s": Series([0.0, 2.0, 4.0], index=index)})\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "freq, freq_depr",\n [\n ("2ME", "2M"),\n ("2QE", "2Q"),\n ("2QE-SEP", "2Q-SEP"),\n ("1BQE", "1BQ"),\n ("2BQE-SEP", "2BQ-SEP"),\n ("1YE", "1Y"),\n ("2YE-MAR", "2Y-MAR"),\n ("1YE", "1A"),\n ("2YE-MAR", "2A-MAR"),\n ("2BYE-MAR", "2BA-MAR"),\n ],\n )\n def test_asfreq_frequency_M_Q_Y_A_deprecated(self, freq, freq_depr):\n # GH#9586, #55978\n depr_msg = f"'{freq_depr[1:]}' is deprecated and will be removed "\n f"in a future version, please use '{freq[1:]}' instead."\n\n index = date_range("1/1/2000", periods=4, freq=f"{freq[1:]}")\n df = DataFrame({"s": Series([0.0, 1.0, 2.0, 3.0], index=index)})\n expected = df.asfreq(freq=freq)\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n result = df.asfreq(freq=freq_depr)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_asfreq.py
test_asfreq.py
Python
9,341
0.95
0.091255
0.090047
python-kit
679
2024-08-08T18:27:43.460269
BSD-3-Clause
true
bc3c87cce1a2ce89406e000bf9e85e30
import numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import IncompatibleFrequency\n\nfrom pandas import (\n DataFrame,\n Period,\n Series,\n Timestamp,\n date_range,\n period_range,\n to_datetime,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture\ndef date_range_frame():\n """\n Fixture for DataFrame of ints with date_range index\n\n Columns are ['A', 'B'].\n """\n N = 50\n rng = date_range("1/1/1990", periods=N, freq="53s")\n return DataFrame({"A": np.arange(N), "B": np.arange(N)}, index=rng)\n\n\nclass TestFrameAsof:\n def test_basic(self, date_range_frame):\n # Explicitly cast to float to avoid implicit cast when setting np.nan\n df = date_range_frame.astype({"A": "float"})\n N = 50\n df.loc[df.index[15:30], "A"] = np.nan\n dates = date_range("1/1/1990", periods=N * 3, freq="25s")\n\n result = df.asof(dates)\n assert result.notna().all(1).all()\n lb = df.index[14]\n ub = df.index[30]\n\n dates = list(dates)\n\n result = df.asof(dates)\n assert result.notna().all(1).all()\n\n mask = (result.index >= lb) & (result.index < ub)\n rs = result[mask]\n assert (rs == 14).all(1).all()\n\n def test_subset(self, date_range_frame):\n N = 10\n # explicitly cast to float to avoid implicit upcast when setting to np.nan\n df = date_range_frame.iloc[:N].copy().astype({"A": "float"})\n df.loc[df.index[4:8], "A"] = np.nan\n dates = date_range("1/1/1990", periods=N * 3, freq="25s")\n\n # with a subset of A should be the same\n result = df.asof(dates, subset="A")\n expected = df.asof(dates)\n tm.assert_frame_equal(result, expected)\n\n # same with A/B\n result = df.asof(dates, subset=["A", "B"])\n expected = df.asof(dates)\n tm.assert_frame_equal(result, expected)\n\n # B gives df.asof\n result = df.asof(dates, subset="B")\n expected = df.resample("25s", closed="right").ffill().reindex(dates)\n expected.iloc[20:] = 9\n # no "missing", so "B" can retain int dtype (df["A"].dtype platform-dependent)\n expected["B"] = expected["B"].astype(df["B"].dtype)\n\n tm.assert_frame_equal(result, expected)\n\n def test_missing(self, date_range_frame):\n # GH 15118\n # no match found - `where` value before earliest date in index\n N = 10\n # Cast to 'float64' to avoid upcast when introducing nan in df.asof\n df = date_range_frame.iloc[:N].copy().astype("float64")\n\n result = df.asof("1989-12-31")\n\n expected = Series(\n index=["A", "B"], name=Timestamp("1989-12-31"), dtype=np.float64\n )\n tm.assert_series_equal(result, expected)\n\n result = df.asof(to_datetime(["1989-12-31"]))\n expected = DataFrame(\n index=to_datetime(["1989-12-31"]), columns=["A", "B"], dtype="float64"\n )\n tm.assert_frame_equal(result, expected)\n\n # Check that we handle PeriodIndex correctly, dont end up with\n # period.ordinal for series name\n df = df.to_period("D")\n result = df.asof("1989-12-31")\n assert isinstance(result.name, Period)\n\n def test_asof_all_nans(self, frame_or_series):\n # GH 15713\n # DataFrame/Series is all nans\n result = frame_or_series([np.nan]).asof([0])\n expected = frame_or_series([np.nan])\n tm.assert_equal(result, expected)\n\n def test_all_nans(self, date_range_frame):\n # GH 15713\n # DataFrame is all nans\n\n # testing non-default indexes, multiple inputs\n N = 150\n rng = date_range_frame.index\n dates = date_range("1/1/1990", periods=N, freq="25s")\n result = DataFrame(np.nan, index=rng, columns=["A"]).asof(dates)\n expected = DataFrame(np.nan, index=dates, columns=["A"])\n tm.assert_frame_equal(result, expected)\n\n # testing multiple columns\n dates = date_range("1/1/1990", periods=N, freq="25s")\n result = DataFrame(np.nan, index=rng, columns=["A", "B", "C"]).asof(dates)\n expected = DataFrame(np.nan, index=dates, columns=["A", "B", "C"])\n tm.assert_frame_equal(result, expected)\n\n # testing scalar input\n result = DataFrame(np.nan, index=[1, 2], columns=["A", "B"]).asof([3])\n expected = DataFrame(np.nan, index=[3], columns=["A", "B"])\n tm.assert_frame_equal(result, expected)\n\n result = DataFrame(np.nan, index=[1, 2], columns=["A", "B"]).asof(3)\n expected = Series(np.nan, index=["A", "B"], name=3)\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n "stamp,expected",\n [\n (\n Timestamp("2018-01-01 23:22:43.325+00:00"),\n Series(2, name=Timestamp("2018-01-01 23:22:43.325+00:00")),\n ),\n (\n Timestamp("2018-01-01 22:33:20.682+01:00"),\n Series(1, name=Timestamp("2018-01-01 22:33:20.682+01:00")),\n ),\n ],\n )\n def test_time_zone_aware_index(self, stamp, expected):\n # GH21194\n # Testing awareness of DataFrame index considering different\n # UTC and timezone\n df = DataFrame(\n data=[1, 2],\n index=[\n Timestamp("2018-01-01 21:00:05.001+00:00"),\n Timestamp("2018-01-01 22:35:10.550+00:00"),\n ],\n )\n\n result = df.asof(stamp)\n tm.assert_series_equal(result, expected)\n\n def test_is_copy(self, date_range_frame):\n # GH-27357, GH-30784: ensure the result of asof is an actual copy and\n # doesn't track the parent dataframe / doesn't give SettingWithCopy warnings\n df = date_range_frame.astype({"A": "float"})\n N = 50\n df.loc[df.index[15:30], "A"] = np.nan\n dates = date_range("1/1/1990", periods=N * 3, freq="25s")\n\n result = df.asof(dates)\n\n with tm.assert_produces_warning(None):\n result["C"] = 1\n\n def test_asof_periodindex_mismatched_freq(self):\n N = 50\n rng = period_range("1/1/1990", periods=N, freq="h")\n df = DataFrame(np.random.default_rng(2).standard_normal(N), index=rng)\n\n # Mismatched freq\n msg = "Input has different freq"\n with pytest.raises(IncompatibleFrequency, match=msg):\n df.asof(rng.asfreq("D"))\n\n def test_asof_preserves_bool_dtype(self):\n # GH#16063 was casting bools to floats\n dti = date_range("2017-01-01", freq="MS", periods=4)\n ser = Series([True, False, True], index=dti[:-1])\n\n ts = dti[-1]\n res = ser.asof([ts])\n\n expected = Series([True], index=[ts])\n tm.assert_series_equal(res, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_asof.py
test_asof.py
Python
6,732
0.95
0.065657
0.15528
react-lib
474
2023-11-13T02:58:10.517293
GPL-3.0
true
99b46ef12a1e7e8fe3721cebdb669e3f
import pytest\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\nclass TestAssign:\n def test_assign(self):\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})\n original = df.copy()\n result = df.assign(C=df.B / df.A)\n expected = df.copy()\n expected["C"] = [4, 2.5, 2]\n tm.assert_frame_equal(result, expected)\n\n # lambda syntax\n result = df.assign(C=lambda x: x.B / x.A)\n tm.assert_frame_equal(result, expected)\n\n # original is unmodified\n tm.assert_frame_equal(df, original)\n\n # Non-Series array-like\n result = df.assign(C=[4, 2.5, 2])\n tm.assert_frame_equal(result, expected)\n # original is unmodified\n tm.assert_frame_equal(df, original)\n\n result = df.assign(B=df.B / df.A)\n expected = expected.drop("B", axis=1).rename(columns={"C": "B"})\n tm.assert_frame_equal(result, expected)\n\n # overwrite\n result = df.assign(A=df.A + df.B)\n expected = df.copy()\n expected["A"] = [5, 7, 9]\n tm.assert_frame_equal(result, expected)\n\n # lambda\n result = df.assign(A=lambda x: x.A + x.B)\n tm.assert_frame_equal(result, expected)\n\n def test_assign_multiple(self):\n df = DataFrame([[1, 4], [2, 5], [3, 6]], columns=["A", "B"])\n result = df.assign(C=[7, 8, 9], D=df.A, E=lambda x: x.B)\n expected = DataFrame(\n [[1, 4, 7, 1, 4], [2, 5, 8, 2, 5], [3, 6, 9, 3, 6]], columns=list("ABCDE")\n )\n tm.assert_frame_equal(result, expected)\n\n def test_assign_order(self):\n # GH 9818\n df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"])\n result = df.assign(D=df.A + df.B, C=df.A - df.B)\n\n expected = DataFrame([[1, 2, 3, -1], [3, 4, 7, -1]], columns=list("ABDC"))\n tm.assert_frame_equal(result, expected)\n result = df.assign(C=df.A - df.B, D=df.A + df.B)\n\n expected = DataFrame([[1, 2, -1, 3], [3, 4, -1, 7]], columns=list("ABCD"))\n\n tm.assert_frame_equal(result, expected)\n\n def test_assign_bad(self):\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})\n\n # non-keyword argument\n msg = r"assign\(\) takes 1 positional argument but 2 were given"\n with pytest.raises(TypeError, match=msg):\n df.assign(lambda x: x.A)\n msg = "'DataFrame' object has no attribute 'C'"\n with pytest.raises(AttributeError, match=msg):\n df.assign(C=df.A, D=df.A + df.C)\n\n def test_assign_dependent(self):\n df = DataFrame({"A": [1, 2], "B": [3, 4]})\n\n result = df.assign(C=df.A, D=lambda x: x["A"] + x["C"])\n expected = DataFrame([[1, 3, 1, 2], [2, 4, 2, 4]], columns=list("ABCD"))\n tm.assert_frame_equal(result, expected)\n\n result = df.assign(C=lambda df: df.A, D=lambda df: df["A"] + df["C"])\n expected = DataFrame([[1, 3, 1, 2], [2, 4, 2, 4]], columns=list("ABCD"))\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_assign.py
test_assign.py
Python
2,982
0.95
0.071429
0.123077
vue-tools
916
2024-02-05T06:01:51.731230
GPL-3.0
true
98283730dc7e453c793a0051fb27e110
import re\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n CategoricalDtype,\n DataFrame,\n DatetimeTZDtype,\n Index,\n Interval,\n IntervalDtype,\n NaT,\n Series,\n Timedelta,\n Timestamp,\n concat,\n date_range,\n option_context,\n)\nimport pandas._testing as tm\n\n\ndef _check_cast(df, v):\n """\n Check if all dtypes of df are equal to v\n """\n assert all(s.dtype.name == v for _, s in df.items())\n\n\nclass TestAstype:\n def test_astype_float(self, float_frame):\n casted = float_frame.astype(int)\n expected = DataFrame(\n float_frame.values.astype(int),\n index=float_frame.index,\n columns=float_frame.columns,\n )\n tm.assert_frame_equal(casted, expected)\n\n casted = float_frame.astype(np.int32)\n expected = DataFrame(\n float_frame.values.astype(np.int32),\n index=float_frame.index,\n columns=float_frame.columns,\n )\n tm.assert_frame_equal(casted, expected)\n\n float_frame["foo"] = "5"\n casted = float_frame.astype(int)\n expected = DataFrame(\n float_frame.values.astype(int),\n index=float_frame.index,\n columns=float_frame.columns,\n )\n tm.assert_frame_equal(casted, expected)\n\n def test_astype_mixed_float(self, mixed_float_frame):\n # mixed casting\n casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float32")\n _check_cast(casted, "float32")\n\n casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float16")\n _check_cast(casted, "float16")\n\n def test_astype_mixed_type(self):\n # mixed casting\n df = DataFrame(\n {\n "a": 1.0,\n "b": 2,\n "c": "foo",\n "float32": np.array([1.0] * 10, dtype="float32"),\n "int32": np.array([1] * 10, dtype="int32"),\n },\n index=np.arange(10),\n )\n mn = df._get_numeric_data().copy()\n mn["little_float"] = np.array(12345.0, dtype="float16")\n mn["big_float"] = np.array(123456789101112.0, dtype="float64")\n\n casted = mn.astype("float64")\n _check_cast(casted, "float64")\n\n casted = mn.astype("int64")\n _check_cast(casted, "int64")\n\n casted = mn.reindex(columns=["little_float"]).astype("float16")\n _check_cast(casted, "float16")\n\n casted = mn.astype("float32")\n _check_cast(casted, "float32")\n\n casted = mn.astype("int32")\n _check_cast(casted, "int32")\n\n # to object\n casted = mn.astype("O")\n _check_cast(casted, "object")\n\n def test_astype_with_exclude_string(self, float_frame):\n df = float_frame.copy()\n expected = float_frame.astype(int)\n df["string"] = "foo"\n casted = df.astype(int, errors="ignore")\n\n expected["string"] = "foo"\n tm.assert_frame_equal(casted, expected)\n\n df = float_frame.copy()\n expected = float_frame.astype(np.int32)\n df["string"] = "foo"\n casted = df.astype(np.int32, errors="ignore")\n\n expected["string"] = "foo"\n tm.assert_frame_equal(casted, expected)\n\n def test_astype_with_view_float(self, float_frame):\n # this is the only real reason to do it this way\n tf = np.round(float_frame).astype(np.int32)\n tf.astype(np.float32, copy=False)\n\n # TODO(wesm): verification?\n tf = float_frame.astype(np.float64)\n tf.astype(np.int64, copy=False)\n\n def test_astype_with_view_mixed_float(self, mixed_float_frame):\n tf = mixed_float_frame.reindex(columns=["A", "B", "C"])\n\n tf.astype(np.int64)\n tf.astype(np.float32)\n\n @pytest.mark.parametrize("dtype", [np.int32, np.int64])\n @pytest.mark.parametrize("val", [np.nan, np.inf])\n def test_astype_cast_nan_inf_int(self, val, dtype):\n # see GH#14265\n #\n # Check NaN and inf --> raise error when converting to int.\n msg = "Cannot convert non-finite values \\(NA or inf\\) to integer"\n df = DataFrame([val])\n\n with pytest.raises(ValueError, match=msg):\n df.astype(dtype)\n\n def test_astype_str(self):\n # see GH#9757\n a = Series(date_range("2010-01-04", periods=5))\n b = Series(date_range("3/6/2012 00:00", periods=5, tz="US/Eastern"))\n c = Series([Timedelta(x, unit="d") for x in range(5)])\n d = Series(range(5))\n e = Series([0.0, 0.2, 0.4, 0.6, 0.8])\n\n df = DataFrame({"a": a, "b": b, "c": c, "d": d, "e": e})\n\n # Datetime-like\n result = df.astype(str)\n\n expected = DataFrame(\n {\n "a": list(map(str, (Timestamp(x)._date_repr for x in a._values))),\n "b": list(map(str, map(Timestamp, b._values))),\n "c": [Timedelta(x)._repr_base() for x in c._values],\n "d": list(map(str, d._values)),\n "e": list(map(str, e._values)),\n },\n dtype="str",\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_astype_str_float(self, using_infer_string):\n # see GH#11302\n result = DataFrame([np.nan]).astype(str)\n expected = DataFrame([np.nan if using_infer_string else "nan"], dtype="str")\n\n tm.assert_frame_equal(result, expected)\n result = DataFrame([1.12345678901234567890]).astype(str)\n\n val = "1.1234567890123457"\n expected = DataFrame([val], dtype="str")\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("dtype_class", [dict, Series])\n def test_astype_dict_like(self, dtype_class):\n # GH7271 & GH16717\n a = Series(date_range("2010-01-04", periods=5))\n b = Series(range(5))\n c = Series([0.0, 0.2, 0.4, 0.6, 0.8])\n d = Series(["1.0", "2", "3.14", "4", "5.4"])\n df = DataFrame({"a": a, "b": b, "c": c, "d": d})\n original = df.copy(deep=True)\n\n # change type of a subset of columns\n dt1 = dtype_class({"b": "str", "d": "float32"})\n result = df.astype(dt1)\n expected = DataFrame(\n {\n "a": a,\n "b": Series(["0", "1", "2", "3", "4"], dtype="str"),\n "c": c,\n "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float32"),\n }\n )\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(df, original)\n\n dt2 = dtype_class({"b": np.float32, "c": "float32", "d": np.float64})\n result = df.astype(dt2)\n expected = DataFrame(\n {\n "a": a,\n "b": Series([0.0, 1.0, 2.0, 3.0, 4.0], dtype="float32"),\n "c": Series([0.0, 0.2, 0.4, 0.6, 0.8], dtype="float32"),\n "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float64"),\n }\n )\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(df, original)\n\n # change all columns\n dt3 = dtype_class({"a": str, "b": str, "c": str, "d": str})\n tm.assert_frame_equal(df.astype(dt3), df.astype(str))\n tm.assert_frame_equal(df, original)\n\n # error should be raised when using something other than column labels\n # in the keys of the dtype dict\n dt4 = dtype_class({"b": str, 2: str})\n dt5 = dtype_class({"e": str})\n msg_frame = (\n "Only a column name can be used for the key in a dtype mappings argument. "\n "'{}' not found in columns."\n )\n with pytest.raises(KeyError, match=msg_frame.format(2)):\n df.astype(dt4)\n with pytest.raises(KeyError, match=msg_frame.format("e")):\n df.astype(dt5)\n tm.assert_frame_equal(df, original)\n\n # if the dtypes provided are the same as the original dtypes, the\n # resulting DataFrame should be the same as the original DataFrame\n dt6 = dtype_class({col: df[col].dtype for col in df.columns})\n equiv = df.astype(dt6)\n tm.assert_frame_equal(df, equiv)\n tm.assert_frame_equal(df, original)\n\n # GH#16717\n # if dtypes provided is empty, the resulting DataFrame\n # should be the same as the original DataFrame\n dt7 = dtype_class({}) if dtype_class is dict else dtype_class({}, dtype=object)\n equiv = df.astype(dt7)\n tm.assert_frame_equal(df, equiv)\n tm.assert_frame_equal(df, original)\n\n def test_astype_duplicate_col(self):\n a1 = Series([1, 2, 3, 4, 5], name="a")\n b = Series([0.1, 0.2, 0.4, 0.6, 0.8], name="b")\n a2 = Series([0, 1, 2, 3, 4], name="a")\n df = concat([a1, b, a2], axis=1)\n\n result = df.astype("str")\n a1_str = Series(["1", "2", "3", "4", "5"], dtype="str", name="a")\n b_str = Series(["0.1", "0.2", "0.4", "0.6", "0.8"], dtype="str", name="b")\n a2_str = Series(["0", "1", "2", "3", "4"], dtype="str", name="a")\n expected = concat([a1_str, b_str, a2_str], axis=1)\n tm.assert_frame_equal(result, expected)\n\n result = df.astype({"a": "str"})\n expected = concat([a1_str, b, a2_str], axis=1)\n tm.assert_frame_equal(result, expected)\n\n def test_astype_duplicate_col_series_arg(self):\n # GH#44417\n vals = np.random.default_rng(2).standard_normal((3, 4))\n df = DataFrame(vals, columns=["A", "B", "C", "A"])\n dtypes = df.dtypes\n dtypes.iloc[0] = str\n dtypes.iloc[2] = "Float64"\n\n result = df.astype(dtypes)\n expected = DataFrame(\n {\n 0: Series(vals[:, 0].astype(str), dtype="str"),\n 1: vals[:, 1],\n 2: pd.array(vals[:, 2], dtype="Float64"),\n 3: vals[:, 3],\n }\n )\n expected.columns = df.columns\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "dtype",\n [\n "category",\n CategoricalDtype(),\n CategoricalDtype(ordered=True),\n CategoricalDtype(ordered=False),\n CategoricalDtype(categories=list("abcdef")),\n CategoricalDtype(categories=list("edba"), ordered=False),\n CategoricalDtype(categories=list("edcb"), ordered=True),\n ],\n ids=repr,\n )\n def test_astype_categorical(self, dtype):\n # GH#18099\n d = {"A": list("abbc"), "B": list("bccd"), "C": list("cdde")}\n df = DataFrame(d)\n result = df.astype(dtype)\n expected = DataFrame({k: Categorical(v, dtype=dtype) for k, v in d.items()})\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("cls", [CategoricalDtype, DatetimeTZDtype, IntervalDtype])\n def test_astype_categoricaldtype_class_raises(self, cls):\n df = DataFrame({"A": ["a", "a", "b", "c"]})\n xpr = f"Expected an instance of {cls.__name__}"\n with pytest.raises(TypeError, match=xpr):\n df.astype({"A": cls})\n\n with pytest.raises(TypeError, match=xpr):\n df["A"].astype(cls)\n\n @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])\n def test_astype_extension_dtypes(self, dtype):\n # GH#22578\n df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"])\n\n expected1 = DataFrame(\n {\n "a": pd.array([1, 3, 5], dtype=dtype),\n "b": pd.array([2, 4, 6], dtype=dtype),\n }\n )\n tm.assert_frame_equal(df.astype(dtype), expected1)\n tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)\n tm.assert_frame_equal(df.astype(dtype).astype("float64"), df)\n\n df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"])\n df["b"] = df["b"].astype(dtype)\n expected2 = DataFrame(\n {"a": [1.0, 3.0, 5.0], "b": pd.array([2, 4, 6], dtype=dtype)}\n )\n tm.assert_frame_equal(df, expected2)\n\n tm.assert_frame_equal(df.astype(dtype), expected1)\n tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)\n\n @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])\n def test_astype_extension_dtypes_1d(self, dtype):\n # GH#22578\n df = DataFrame({"a": [1.0, 2.0, 3.0]})\n\n expected1 = DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)})\n tm.assert_frame_equal(df.astype(dtype), expected1)\n tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)\n\n df = DataFrame({"a": [1.0, 2.0, 3.0]})\n df["a"] = df["a"].astype(dtype)\n expected2 = DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)})\n tm.assert_frame_equal(df, expected2)\n\n tm.assert_frame_equal(df.astype(dtype), expected1)\n tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)\n\n @pytest.mark.parametrize("dtype", ["category", "Int64"])\n def test_astype_extension_dtypes_duplicate_col(self, dtype):\n # GH#24704\n a1 = Series([0, np.nan, 4], name="a")\n a2 = Series([np.nan, 3, 5], name="a")\n df = concat([a1, a2], axis=1)\n\n result = df.astype(dtype)\n expected = concat([a1.astype(dtype), a2.astype(dtype)], axis=1)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "dtype", [{100: "float64", 200: "uint64"}, "category", "float64"]\n )\n def test_astype_column_metadata(self, dtype):\n # GH#19920\n columns = Index([100, 200, 300], dtype=np.uint64, name="foo")\n df = DataFrame(np.arange(15).reshape(5, 3), columns=columns)\n df = df.astype(dtype)\n tm.assert_index_equal(df.columns, columns)\n\n @pytest.mark.parametrize("unit", ["Y", "M", "W", "D", "h", "m"])\n def test_astype_from_object_to_datetime_unit(self, unit):\n vals = [\n ["2015-01-01", "2015-01-02", "2015-01-03"],\n ["2017-01-01", "2017-01-02", "2017-02-03"],\n ]\n df = DataFrame(vals, dtype=object)\n msg = (\n rf"Unexpected value for 'dtype': 'datetime64\[{unit}\]'. "\n r"Must be 'datetime64\[s\]', 'datetime64\[ms\]', 'datetime64\[us\]', "\n r"'datetime64\[ns\]' or DatetimeTZDtype"\n )\n with pytest.raises(ValueError, match=msg):\n df.astype(f"M8[{unit}]")\n\n @pytest.mark.parametrize("unit", ["Y", "M", "W", "D", "h", "m"])\n def test_astype_from_object_to_timedelta_unit(self, unit):\n vals = [\n ["1 Day", "2 Days", "3 Days"],\n ["4 Days", "5 Days", "6 Days"],\n ]\n df = DataFrame(vals, dtype=object)\n msg = (\n r"Cannot convert from timedelta64\[ns\] to timedelta64\[.*\]. "\n "Supported resolutions are 's', 'ms', 'us', 'ns'"\n )\n with pytest.raises(ValueError, match=msg):\n # TODO: this is ValueError while for DatetimeArray it is TypeError;\n # get these consistent\n df.astype(f"m8[{unit}]")\n\n @pytest.mark.parametrize("dtype", ["M8", "m8"])\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])\n def test_astype_from_datetimelike_to_object(self, dtype, unit):\n # tests astype to object dtype\n # GH#19223 / GH#12425\n dtype = f"{dtype}[{unit}]"\n arr = np.array([[1, 2, 3]], dtype=dtype)\n df = DataFrame(arr)\n result = df.astype(object)\n assert (result.dtypes == object).all()\n\n if dtype.startswith("M8"):\n assert result.iloc[0, 0] == Timestamp(1, unit=unit)\n else:\n assert result.iloc[0, 0] == Timedelta(1, unit=unit)\n\n @pytest.mark.parametrize("arr_dtype", [np.int64, np.float64])\n @pytest.mark.parametrize("dtype", ["M8", "m8"])\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])\n def test_astype_to_datetimelike_unit(self, arr_dtype, dtype, unit):\n # tests all units from numeric origination\n # GH#19223 / GH#12425\n dtype = f"{dtype}[{unit}]"\n arr = np.array([[1, 2, 3]], dtype=arr_dtype)\n df = DataFrame(arr)\n result = df.astype(dtype)\n expected = DataFrame(arr.astype(dtype))\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])\n def test_astype_to_datetime_unit(self, unit):\n # tests all units from datetime origination\n # GH#19223\n dtype = f"M8[{unit}]"\n arr = np.array([[1, 2, 3]], dtype=dtype)\n df = DataFrame(arr)\n ser = df.iloc[:, 0]\n idx = Index(ser)\n dta = ser._values\n\n if unit in ["ns", "us", "ms", "s"]:\n # GH#48928\n result = df.astype(dtype)\n else:\n # we use the nearest supported dtype (i.e. M8[s])\n msg = rf"Cannot cast DatetimeArray to dtype datetime64\[{unit}\]"\n with pytest.raises(TypeError, match=msg):\n df.astype(dtype)\n\n with pytest.raises(TypeError, match=msg):\n ser.astype(dtype)\n\n with pytest.raises(TypeError, match=msg.replace("Array", "Index")):\n idx.astype(dtype)\n\n with pytest.raises(TypeError, match=msg):\n dta.astype(dtype)\n\n return\n\n exp_df = DataFrame(arr.astype(dtype))\n assert (exp_df.dtypes == dtype).all()\n tm.assert_frame_equal(result, exp_df)\n\n res_ser = ser.astype(dtype)\n exp_ser = exp_df.iloc[:, 0]\n assert exp_ser.dtype == dtype\n tm.assert_series_equal(res_ser, exp_ser)\n\n exp_dta = exp_ser._values\n\n res_index = idx.astype(dtype)\n exp_index = Index(exp_ser)\n assert exp_index.dtype == dtype\n tm.assert_index_equal(res_index, exp_index)\n\n res_dta = dta.astype(dtype)\n assert exp_dta.dtype == dtype\n tm.assert_extension_array_equal(res_dta, exp_dta)\n\n @pytest.mark.parametrize("unit", ["ns"])\n def test_astype_to_timedelta_unit_ns(self, unit):\n # preserver the timedelta conversion\n # GH#19223\n dtype = f"m8[{unit}]"\n arr = np.array([[1, 2, 3]], dtype=dtype)\n df = DataFrame(arr)\n result = df.astype(dtype)\n expected = DataFrame(arr.astype(dtype))\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("unit", ["us", "ms", "s", "h", "m", "D"])\n def test_astype_to_timedelta_unit(self, unit):\n # coerce to float\n # GH#19223 until 2.0 used to coerce to float\n dtype = f"m8[{unit}]"\n arr = np.array([[1, 2, 3]], dtype=dtype)\n df = DataFrame(arr)\n ser = df.iloc[:, 0]\n tdi = Index(ser)\n tda = tdi._values\n\n if unit in ["us", "ms", "s"]:\n assert (df.dtypes == dtype).all()\n result = df.astype(dtype)\n else:\n # We get the nearest supported unit, i.e. "s"\n assert (df.dtypes == "m8[s]").all()\n\n msg = (\n rf"Cannot convert from timedelta64\[s\] to timedelta64\[{unit}\]. "\n "Supported resolutions are 's', 'ms', 'us', 'ns'"\n )\n with pytest.raises(ValueError, match=msg):\n df.astype(dtype)\n with pytest.raises(ValueError, match=msg):\n ser.astype(dtype)\n with pytest.raises(ValueError, match=msg):\n tdi.astype(dtype)\n with pytest.raises(ValueError, match=msg):\n tda.astype(dtype)\n\n return\n\n result = df.astype(dtype)\n # The conversion is a no-op, so we just get a copy\n expected = df\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])\n def test_astype_to_incorrect_datetimelike(self, unit):\n # trying to astype a m to a M, or vice-versa\n # GH#19224\n dtype = f"M8[{unit}]"\n other = f"m8[{unit}]"\n\n df = DataFrame(np.array([[1, 2, 3]], dtype=dtype))\n msg = "|".join(\n [\n # BlockManager path\n rf"Cannot cast DatetimeArray to dtype timedelta64\[{unit}\]",\n # ArrayManager path\n "cannot astype a datetimelike from "\n rf"\[datetime64\[ns\]\] to \[timedelta64\[{unit}\]\]",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n df.astype(other)\n\n msg = "|".join(\n [\n # BlockManager path\n rf"Cannot cast TimedeltaArray to dtype datetime64\[{unit}\]",\n # ArrayManager path\n "cannot astype a timedelta from "\n rf"\[timedelta64\[ns\]\] to \[datetime64\[{unit}\]\]",\n ]\n )\n df = DataFrame(np.array([[1, 2, 3]], dtype=other))\n with pytest.raises(TypeError, match=msg):\n df.astype(dtype)\n\n def test_astype_arg_for_errors(self):\n # GH#14878\n\n df = DataFrame([1, 2, 3])\n\n msg = (\n "Expected value of kwarg 'errors' to be one of "\n "['raise', 'ignore']. Supplied value is 'True'"\n )\n with pytest.raises(ValueError, match=re.escape(msg)):\n df.astype(np.float64, errors=True)\n\n df.astype(np.int8, errors="ignore")\n\n def test_astype_invalid_conversion(self):\n # GH#47571\n df = DataFrame({"a": [1, 2, "text"], "b": [1, 2, 3]})\n\n msg = (\n "invalid literal for int() with base 10: 'text': "\n "Error while type casting for column 'a'"\n )\n\n with pytest.raises(ValueError, match=re.escape(msg)):\n df.astype({"a": int})\n\n def test_astype_arg_for_errors_dictlist(self):\n # GH#25905\n df = DataFrame(\n [\n {"a": "1", "b": "16.5%", "c": "test"},\n {"a": "2.2", "b": "15.3", "c": "another_test"},\n ]\n )\n expected = DataFrame(\n [\n {"a": 1.0, "b": "16.5%", "c": "test"},\n {"a": 2.2, "b": "15.3", "c": "another_test"},\n ]\n )\n expected["c"] = expected["c"].astype("object")\n type_dict = {"a": "float64", "b": "float64", "c": "object"}\n\n result = df.astype(dtype=type_dict, errors="ignore")\n\n tm.assert_frame_equal(result, expected)\n\n def test_astype_dt64tz(self, timezone_frame):\n # astype\n expected = np.array(\n [\n [\n Timestamp("2013-01-01 00:00:00"),\n Timestamp("2013-01-02 00:00:00"),\n Timestamp("2013-01-03 00:00:00"),\n ],\n [\n Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),\n NaT,\n Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),\n ],\n [\n Timestamp("2013-01-01 00:00:00+0100", tz="CET"),\n NaT,\n Timestamp("2013-01-03 00:00:00+0100", tz="CET"),\n ],\n ],\n dtype=object,\n ).T\n expected = DataFrame(\n expected,\n index=timezone_frame.index,\n columns=timezone_frame.columns,\n dtype=object,\n )\n result = timezone_frame.astype(object)\n tm.assert_frame_equal(result, expected)\n\n msg = "Cannot use .astype to convert from timezone-aware dtype to timezone-"\n with pytest.raises(TypeError, match=msg):\n # dt64tz->dt64 deprecated\n timezone_frame.astype("datetime64[ns]")\n\n def test_astype_dt64tz_to_str(self, timezone_frame, using_infer_string):\n # str formatting\n result = timezone_frame.astype(str)\n na_value = np.nan if using_infer_string else "NaT"\n expected = DataFrame(\n [\n [\n "2013-01-01",\n "2013-01-01 00:00:00-05:00",\n "2013-01-01 00:00:00+01:00",\n ],\n ["2013-01-02", na_value, na_value],\n [\n "2013-01-03",\n "2013-01-03 00:00:00-05:00",\n "2013-01-03 00:00:00+01:00",\n ],\n ],\n columns=timezone_frame.columns,\n dtype="str",\n )\n tm.assert_frame_equal(result, expected)\n\n with option_context("display.max_columns", 20):\n result = str(timezone_frame)\n assert (\n "0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00"\n ) in result\n assert (\n "1 2013-01-02 NaT NaT"\n ) in result\n assert (\n "2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00"\n ) in result\n\n def test_astype_empty_dtype_dict(self):\n # issue mentioned further down in the following issue's thread\n # https://github.com/pandas-dev/pandas/issues/33113\n df = DataFrame()\n result = df.astype({})\n tm.assert_frame_equal(result, df)\n assert result is not df\n\n @pytest.mark.parametrize(\n "data, dtype",\n [\n (["x", "y", "z"], "string[python]"),\n pytest.param(\n ["x", "y", "z"],\n "string[pyarrow]",\n marks=td.skip_if_no("pyarrow"),\n ),\n (["x", "y", "z"], "category"),\n (3 * [Timestamp("2020-01-01", tz="UTC")], None),\n (3 * [Interval(0, 1)], None),\n ],\n )\n @pytest.mark.parametrize("errors", ["raise", "ignore"])\n def test_astype_ignores_errors_for_extension_dtypes(self, data, dtype, errors):\n # https://github.com/pandas-dev/pandas/issues/35471\n df = DataFrame(Series(data, dtype=dtype))\n if errors == "ignore":\n expected = df\n result = df.astype(float, errors=errors)\n tm.assert_frame_equal(result, expected)\n else:\n msg = "(Cannot cast)|(could not convert)"\n with pytest.raises((ValueError, TypeError), match=msg):\n df.astype(float, errors=errors)\n\n def test_astype_tz_conversion(self):\n # GH 35973\n val = {"tz": date_range("2020-08-30", freq="d", periods=2, tz="Europe/London")}\n df = DataFrame(val)\n result = df.astype({"tz": "datetime64[ns, Europe/Berlin]"})\n\n expected = df\n expected["tz"] = expected["tz"].dt.tz_convert("Europe/Berlin")\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("tz", ["UTC", "Europe/Berlin"])\n def test_astype_tz_object_conversion(self, tz):\n # GH 35973\n val = {"tz": date_range("2020-08-30", freq="d", periods=2, tz="Europe/London")}\n expected = DataFrame(val)\n\n # convert expected to object dtype from other tz str (independently tested)\n result = expected.astype({"tz": f"datetime64[ns, {tz}]"})\n result = result.astype({"tz": "object"})\n\n # do real test: object dtype to a specified tz, different from construction tz.\n result = result.astype({"tz": "datetime64[ns, Europe/London]"})\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string) GH#60639")\n def test_astype_dt64_to_string(\n self, frame_or_series, tz_naive_fixture, using_infer_string\n ):\n # GH#41409\n tz = tz_naive_fixture\n\n dti = date_range("2016-01-01", periods=3, tz=tz)\n dta = dti._data\n dta[0] = NaT\n\n obj = frame_or_series(dta)\n result = obj.astype("string")\n\n # Check that Series/DataFrame.astype matches DatetimeArray.astype\n expected = frame_or_series(dta.astype("string"))\n tm.assert_equal(result, expected)\n\n item = result.iloc[0]\n if frame_or_series is DataFrame:\n item = item.iloc[0]\n if using_infer_string:\n assert item is np.nan\n else:\n assert item is pd.NA\n\n # For non-NA values, we should match what we get for non-EA str\n alt = obj.astype(str)\n assert np.all(alt.iloc[1:] == result.iloc[1:])\n\n def test_astype_td64_to_string(self, frame_or_series):\n # GH#41409\n tdi = pd.timedelta_range("1 Day", periods=3)\n obj = frame_or_series(tdi)\n\n expected = frame_or_series(["1 days", "2 days", "3 days"], dtype="string")\n result = obj.astype("string")\n tm.assert_equal(result, expected)\n\n def test_astype_bytes(self):\n # GH#39474\n result = DataFrame(["foo", "bar", "baz"]).astype(bytes)\n assert result.dtypes[0] == np.dtype("S3")\n\n @pytest.mark.parametrize(\n "index_slice",\n [\n np.s_[:2, :2],\n np.s_[:1, :2],\n np.s_[:2, :1],\n np.s_[::2, ::2],\n np.s_[::1, ::2],\n np.s_[::2, ::1],\n ],\n )\n def test_astype_noncontiguous(self, index_slice):\n # GH#42396\n data = np.arange(16).reshape(4, 4)\n df = DataFrame(data)\n\n result = df.iloc[index_slice].astype("int16")\n expected = df.iloc[index_slice]\n tm.assert_frame_equal(result, expected, check_dtype=False)\n\n def test_astype_retain_attrs(self, any_numpy_dtype):\n # GH#44414\n df = DataFrame({"a": [0, 1, 2], "b": [3, 4, 5]})\n df.attrs["Location"] = "Michigan"\n\n result = df.astype({"a": any_numpy_dtype}).attrs\n expected = df.attrs\n\n tm.assert_dict_equal(expected, result)\n\n\nclass TestAstypeCategorical:\n def test_astype_from_categorical3(self):\n df = DataFrame({"cats": [1, 2, 3, 4, 5, 6], "vals": [1, 2, 3, 4, 5, 6]})\n cats = Categorical([1, 2, 3, 4, 5, 6])\n exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]})\n df["cats"] = df["cats"].astype("category")\n tm.assert_frame_equal(exp_df, df)\n\n def test_astype_from_categorical4(self):\n df = DataFrame(\n {"cats": ["a", "b", "b", "a", "a", "d"], "vals": [1, 2, 3, 4, 5, 6]}\n )\n cats = Categorical(["a", "b", "b", "a", "a", "d"])\n exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]})\n df["cats"] = df["cats"].astype("category")\n tm.assert_frame_equal(exp_df, df)\n\n def test_categorical_astype_to_int(self, any_int_dtype):\n # GH#39402\n\n df = DataFrame(data={"col1": pd.array([2.0, 1.0, 3.0])})\n df.col1 = df.col1.astype("category")\n df.col1 = df.col1.astype(any_int_dtype)\n expected = DataFrame({"col1": pd.array([2, 1, 3], dtype=any_int_dtype)})\n tm.assert_frame_equal(df, expected)\n\n def test_astype_categorical_to_string_missing(self):\n # https://github.com/pandas-dev/pandas/issues/41797\n df = DataFrame(["a", "b", np.nan])\n expected = df.astype(str)\n cat = df.astype("category")\n result = cat.astype(str)\n tm.assert_frame_equal(result, expected)\n\n\nclass IntegerArrayNoCopy(pd.core.arrays.IntegerArray):\n # GH 42501\n\n def copy(self):\n assert False\n\n\nclass Int16DtypeNoCopy(pd.Int16Dtype):\n # GH 42501\n\n @classmethod\n def construct_array_type(cls):\n return IntegerArrayNoCopy\n\n\ndef test_frame_astype_no_copy():\n # GH 42501\n df = DataFrame({"a": [1, 4, None, 5], "b": [6, 7, 8, 9]}, dtype=object)\n result = df.astype({"a": Int16DtypeNoCopy()}, copy=False)\n\n assert result.a.dtype == pd.Int16Dtype()\n assert np.shares_memory(df.b.values, result.b.values)\n\n\n@pytest.mark.parametrize("dtype", ["int64", "Int64"])\ndef test_astype_copies(dtype):\n # GH#50984\n pytest.importorskip("pyarrow")\n df = DataFrame({"a": [1, 2, 3]}, dtype=dtype)\n result = df.astype("int64[pyarrow]", copy=True)\n df.iloc[0, 0] = 100\n expected = DataFrame({"a": [1, 2, 3]}, dtype="int64[pyarrow]")\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize("val", [None, 1, 1.5, np.nan, NaT])\ndef test_astype_to_string_not_modifying_input(string_storage, val):\n # GH#51073\n df = DataFrame({"a": ["a", "b", val]})\n expected = df.copy()\n with option_context("mode.string_storage", string_storage):\n df.astype("string", copy=False)\n tm.assert_frame_equal(df, expected)\n\n\n@pytest.mark.parametrize("val", [None, 1, 1.5, np.nan, NaT])\ndef test_astype_to_string_dtype_not_modifying_input(any_string_dtype, val):\n # GH#51073 - variant of the above test with explicit dtype instances\n df = DataFrame({"a": ["a", "b", val]})\n expected = df.copy()\n df.astype(any_string_dtype)\n tm.assert_frame_equal(df, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_astype.py
test_astype.py
Python
32,711
0.95
0.087662
0.098972
react-lib
105
2024-05-29T06:58:55.103374
BSD-3-Clause
true
dc7ac0a365f3c7958f01e29376ff2cc0
from datetime import time\n\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import timezones\n\nfrom pandas import (\n DataFrame,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestAtTime:\n @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])\n def test_localized_at_time(self, tzstr, frame_or_series):\n tz = timezones.maybe_get_tz(tzstr)\n\n rng = date_range("4/16/2012", "5/1/2012", freq="h")\n ts = frame_or_series(\n np.random.default_rng(2).standard_normal(len(rng)), index=rng\n )\n\n ts_local = ts.tz_localize(tzstr)\n\n result = ts_local.at_time(time(10, 0))\n expected = ts.at_time(time(10, 0)).tz_localize(tzstr)\n tm.assert_equal(result, expected)\n assert timezones.tz_compare(result.index.tz, tz)\n\n def test_at_time(self, frame_or_series):\n rng = date_range("1/1/2000", "1/5/2000", freq="5min")\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng\n )\n ts = tm.get_obj(ts, frame_or_series)\n rs = ts.at_time(rng[1])\n assert (rs.index.hour == rng[1].hour).all()\n assert (rs.index.minute == rng[1].minute).all()\n assert (rs.index.second == rng[1].second).all()\n\n result = ts.at_time("9:30")\n expected = ts.at_time(time(9, 30))\n tm.assert_equal(result, expected)\n\n def test_at_time_midnight(self, frame_or_series):\n # midnight, everything\n rng = date_range("1/1/2000", "1/31/2000")\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((len(rng), 3)), index=rng\n )\n ts = tm.get_obj(ts, frame_or_series)\n\n result = ts.at_time(time(0, 0))\n tm.assert_equal(result, ts)\n\n def test_at_time_nonexistent(self, frame_or_series):\n # time doesn't exist\n rng = date_range("1/1/2012", freq="23Min", periods=384)\n ts = DataFrame(np.random.default_rng(2).standard_normal(len(rng)), rng)\n ts = tm.get_obj(ts, frame_or_series)\n rs = ts.at_time("16:00")\n assert len(rs) == 0\n\n @pytest.mark.parametrize(\n "hour", ["1:00", "1:00AM", time(1), time(1, tzinfo=pytz.UTC)]\n )\n def test_at_time_errors(self, hour):\n # GH#24043\n dti = date_range("2018", periods=3, freq="h")\n df = DataFrame(list(range(len(dti))), index=dti)\n if getattr(hour, "tzinfo", None) is None:\n result = df.at_time(hour)\n expected = df.iloc[1:2]\n tm.assert_frame_equal(result, expected)\n else:\n with pytest.raises(ValueError, match="Index must be timezone"):\n df.at_time(hour)\n\n def test_at_time_tz(self):\n # GH#24043\n dti = date_range("2018", periods=3, freq="h", tz="US/Pacific")\n df = DataFrame(list(range(len(dti))), index=dti)\n result = df.at_time(time(4, tzinfo=pytz.timezone("US/Eastern")))\n expected = df.iloc[1:2]\n tm.assert_frame_equal(result, expected)\n\n def test_at_time_raises(self, frame_or_series):\n # GH#20725\n obj = DataFrame([[1, 2, 3], [4, 5, 6]])\n obj = tm.get_obj(obj, frame_or_series)\n msg = "Index must be DatetimeIndex"\n with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex\n obj.at_time("00:00")\n\n @pytest.mark.parametrize("axis", ["index", "columns", 0, 1])\n def test_at_time_axis(self, axis):\n # issue 8839\n rng = date_range("1/1/2000", "1/5/2000", freq="5min")\n ts = DataFrame(np.random.default_rng(2).standard_normal((len(rng), len(rng))))\n ts.index, ts.columns = rng, rng\n\n indices = rng[(rng.hour == 9) & (rng.minute == 30) & (rng.second == 0)]\n\n if axis in ["index", 0]:\n expected = ts.loc[indices, :]\n elif axis in ["columns", 1]:\n expected = ts.loc[:, indices]\n\n result = ts.at_time("9:30", axis=axis)\n\n # Without clearing freq, result has freq 1440T and expected 5T\n result.index = result.index._with_freq(None)\n expected.index = expected.index._with_freq(None)\n tm.assert_frame_equal(result, expected)\n\n def test_at_time_datetimeindex(self):\n index = date_range("2012-01-01", "2012-01-05", freq="30min")\n df = DataFrame(\n np.random.default_rng(2).standard_normal((len(index), 5)), index=index\n )\n akey = time(12, 0, 0)\n ainds = [24, 72, 120, 168]\n\n result = df.at_time(akey)\n expected = df.loc[akey]\n expected2 = df.iloc[ainds]\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(result, expected2)\n assert len(result) == 4\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_at_time.py
test_at_time.py
Python
4,708
0.95
0.090909
0.06422
react-lib
223
2024-05-02T00:22:30.690414
MIT
true
3e462771d2476e54d9e626fb465a7093
from datetime import (\n datetime,\n time,\n)\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import timezones\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n DataFrame,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestBetweenTime:\n @td.skip_if_not_us_locale\n def test_between_time_formats(self, frame_or_series):\n # GH#11818\n rng = date_range("1/1/2000", "1/5/2000", freq="5min")\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng\n )\n ts = tm.get_obj(ts, frame_or_series)\n\n strings = [\n ("2:00", "2:30"),\n ("0200", "0230"),\n ("2:00am", "2:30am"),\n ("0200am", "0230am"),\n ("2:00:00", "2:30:00"),\n ("020000", "023000"),\n ("2:00:00am", "2:30:00am"),\n ("020000am", "023000am"),\n ]\n expected_length = 28\n\n for time_string in strings:\n assert len(ts.between_time(*time_string)) == expected_length\n\n @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])\n def test_localized_between_time(self, tzstr, frame_or_series):\n tz = timezones.maybe_get_tz(tzstr)\n\n rng = date_range("4/16/2012", "5/1/2012", freq="h")\n ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)\n if frame_or_series is DataFrame:\n ts = ts.to_frame()\n\n ts_local = ts.tz_localize(tzstr)\n\n t1, t2 = time(10, 0), time(11, 0)\n result = ts_local.between_time(t1, t2)\n expected = ts.between_time(t1, t2).tz_localize(tzstr)\n tm.assert_equal(result, expected)\n assert timezones.tz_compare(result.index.tz, tz)\n\n def test_between_time_types(self, frame_or_series):\n # GH11818\n rng = date_range("1/1/2000", "1/5/2000", freq="5min")\n obj = DataFrame({"A": 0}, index=rng)\n obj = tm.get_obj(obj, frame_or_series)\n\n msg = r"Cannot convert arg \[datetime\.datetime\(2010, 1, 2, 1, 0\)\] to a time"\n with pytest.raises(ValueError, match=msg):\n obj.between_time(datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5))\n\n def test_between_time(self, inclusive_endpoints_fixture, frame_or_series):\n rng = date_range("1/1/2000", "1/5/2000", freq="5min")\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng\n )\n ts = tm.get_obj(ts, frame_or_series)\n\n stime = time(0, 0)\n etime = time(1, 0)\n inclusive = inclusive_endpoints_fixture\n\n filtered = ts.between_time(stime, etime, inclusive=inclusive)\n exp_len = 13 * 4 + 1\n\n if inclusive in ["right", "neither"]:\n exp_len -= 5\n if inclusive in ["left", "neither"]:\n exp_len -= 4\n\n assert len(filtered) == exp_len\n for rs in filtered.index:\n t = rs.time()\n if inclusive in ["left", "both"]:\n assert t >= stime\n else:\n assert t > stime\n\n if inclusive in ["right", "both"]:\n assert t <= etime\n else:\n assert t < etime\n\n result = ts.between_time("00:00", "01:00")\n expected = ts.between_time(stime, etime)\n tm.assert_equal(result, expected)\n\n # across midnight\n rng = date_range("1/1/2000", "1/5/2000", freq="5min")\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng\n )\n ts = tm.get_obj(ts, frame_or_series)\n stime = time(22, 0)\n etime = time(9, 0)\n\n filtered = ts.between_time(stime, etime, inclusive=inclusive)\n exp_len = (12 * 11 + 1) * 4 + 1\n if inclusive in ["right", "neither"]:\n exp_len -= 4\n if inclusive in ["left", "neither"]:\n exp_len -= 4\n\n assert len(filtered) == exp_len\n for rs in filtered.index:\n t = rs.time()\n if inclusive in ["left", "both"]:\n assert (t >= stime) or (t <= etime)\n else:\n assert (t > stime) or (t <= etime)\n\n if inclusive in ["right", "both"]:\n assert (t <= etime) or (t >= stime)\n else:\n assert (t < etime) or (t >= stime)\n\n def test_between_time_raises(self, frame_or_series):\n # GH#20725\n obj = DataFrame([[1, 2, 3], [4, 5, 6]])\n obj = tm.get_obj(obj, frame_or_series)\n\n msg = "Index must be DatetimeIndex"\n with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex\n obj.between_time(start_time="00:00", end_time="12:00")\n\n def test_between_time_axis(self, frame_or_series):\n # GH#8839\n rng = date_range("1/1/2000", periods=100, freq="10min")\n ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng)\n if frame_or_series is DataFrame:\n ts = ts.to_frame()\n\n stime, etime = ("08:00:00", "09:00:00")\n expected_length = 7\n\n assert len(ts.between_time(stime, etime)) == expected_length\n assert len(ts.between_time(stime, etime, axis=0)) == expected_length\n msg = f"No axis named {ts.ndim} for object type {type(ts).__name__}"\n with pytest.raises(ValueError, match=msg):\n ts.between_time(stime, etime, axis=ts.ndim)\n\n def test_between_time_axis_aliases(self, axis):\n # GH#8839\n rng = date_range("1/1/2000", periods=100, freq="10min")\n ts = DataFrame(np.random.default_rng(2).standard_normal((len(rng), len(rng))))\n stime, etime = ("08:00:00", "09:00:00")\n exp_len = 7\n\n if axis in ["index", 0]:\n ts.index = rng\n assert len(ts.between_time(stime, etime)) == exp_len\n assert len(ts.between_time(stime, etime, axis=0)) == exp_len\n\n if axis in ["columns", 1]:\n ts.columns = rng\n selected = ts.between_time(stime, etime, axis=1).columns\n assert len(selected) == exp_len\n\n def test_between_time_axis_raises(self, axis):\n # issue 8839\n rng = date_range("1/1/2000", periods=100, freq="10min")\n mask = np.arange(0, len(rng))\n rand_data = np.random.default_rng(2).standard_normal((len(rng), len(rng)))\n ts = DataFrame(rand_data, index=rng, columns=rng)\n stime, etime = ("08:00:00", "09:00:00")\n\n msg = "Index must be DatetimeIndex"\n if axis in ["columns", 1]:\n ts.index = mask\n with pytest.raises(TypeError, match=msg):\n ts.between_time(stime, etime)\n with pytest.raises(TypeError, match=msg):\n ts.between_time(stime, etime, axis=0)\n\n if axis in ["index", 0]:\n ts.columns = mask\n with pytest.raises(TypeError, match=msg):\n ts.between_time(stime, etime, axis=1)\n\n def test_between_time_datetimeindex(self):\n index = date_range("2012-01-01", "2012-01-05", freq="30min")\n df = DataFrame(\n np.random.default_rng(2).standard_normal((len(index), 5)), index=index\n )\n bkey = slice(time(13, 0, 0), time(14, 0, 0))\n binds = [26, 27, 28, 74, 75, 76, 122, 123, 124, 170, 171, 172]\n\n result = df.between_time(bkey.start, bkey.stop)\n expected = df.loc[bkey]\n expected2 = df.iloc[binds]\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(result, expected2)\n assert len(result) == 12\n\n def test_between_time_incorrect_arg_inclusive(self):\n # GH40245\n rng = date_range("1/1/2000", "1/5/2000", freq="5min")\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((len(rng), 2)), index=rng\n )\n\n stime = time(0, 0)\n etime = time(1, 0)\n inclusive = "bad_string"\n msg = "Inclusive has to be either 'both', 'neither', 'left' or 'right'"\n with pytest.raises(ValueError, match=msg):\n ts.between_time(stime, etime, inclusive=inclusive)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_between_time.py
test_between_time.py
Python
8,083
0.95
0.127753
0.042553
react-lib
928
2025-04-13T15:59:00.742165
GPL-3.0
true
a1ac363f1c6ed0d703109ec4fec12d71
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameClip:\n def test_clip(self, float_frame):\n median = float_frame.median().median()\n original = float_frame.copy()\n\n double = float_frame.clip(upper=median, lower=median)\n assert not (double.values != median).any()\n\n # Verify that float_frame was not changed inplace\n assert (float_frame.values == original.values).all()\n\n def test_inplace_clip(self, float_frame):\n # GH#15388\n median = float_frame.median().median()\n frame_copy = float_frame.copy()\n\n return_value = frame_copy.clip(upper=median, lower=median, inplace=True)\n assert return_value is None\n assert not (frame_copy.values != median).any()\n\n def test_dataframe_clip(self):\n # GH#2747\n df = DataFrame(np.random.default_rng(2).standard_normal((1000, 2)))\n\n for lb, ub in [(-1, 1), (1, -1)]:\n clipped_df = df.clip(lb, ub)\n\n lb, ub = min(lb, ub), max(ub, lb)\n lb_mask = df.values <= lb\n ub_mask = df.values >= ub\n mask = ~lb_mask & ~ub_mask\n assert (clipped_df.values[lb_mask] == lb).all()\n assert (clipped_df.values[ub_mask] == ub).all()\n assert (clipped_df.values[mask] == df.values[mask]).all()\n\n def test_clip_mixed_numeric(self):\n # clip on mixed integer or floats\n # GH#24162, clipping now preserves numeric types per column\n df = DataFrame({"A": [1, 2, 3], "B": [1.0, np.nan, 3.0]})\n result = df.clip(1, 2)\n expected = DataFrame({"A": [1, 2, 2], "B": [1.0, np.nan, 2.0]})\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame([[1, 2, 3.4], [3, 4, 5.6]], columns=["foo", "bar", "baz"])\n expected = df.dtypes\n result = df.clip(upper=3).dtypes\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize("inplace", [True, False])\n def test_clip_against_series(self, inplace):\n # GH#6966\n\n df = DataFrame(np.random.default_rng(2).standard_normal((1000, 2)))\n lb = Series(np.random.default_rng(2).standard_normal(1000))\n ub = lb + 1\n\n original = df.copy()\n clipped_df = df.clip(lb, ub, axis=0, inplace=inplace)\n\n if inplace:\n clipped_df = df\n\n for i in range(2):\n lb_mask = original.iloc[:, i] <= lb\n ub_mask = original.iloc[:, i] >= ub\n mask = ~lb_mask & ~ub_mask\n\n result = clipped_df.loc[lb_mask, i]\n tm.assert_series_equal(result, lb[lb_mask], check_names=False)\n assert result.name == i\n\n result = clipped_df.loc[ub_mask, i]\n tm.assert_series_equal(result, ub[ub_mask], check_names=False)\n assert result.name == i\n\n tm.assert_series_equal(clipped_df.loc[mask, i], df.loc[mask, i])\n\n @pytest.mark.parametrize("inplace", [True, False])\n @pytest.mark.parametrize("lower", [[2, 3, 4], np.asarray([2, 3, 4])])\n @pytest.mark.parametrize(\n "axis,res",\n [\n (0, [[2.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 7.0, 7.0]]),\n (1, [[2.0, 3.0, 4.0], [4.0, 5.0, 6.0], [5.0, 6.0, 7.0]]),\n ],\n )\n def test_clip_against_list_like(self, inplace, lower, axis, res):\n # GH#15390\n arr = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])\n\n original = DataFrame(\n arr, columns=["one", "two", "three"], index=["a", "b", "c"]\n )\n\n result = original.clip(lower=lower, upper=[5, 6, 7], axis=axis, inplace=inplace)\n\n expected = DataFrame(res, columns=original.columns, index=original.index)\n if inplace:\n result = original\n tm.assert_frame_equal(result, expected, check_exact=True)\n\n @pytest.mark.parametrize("axis", [0, 1, None])\n def test_clip_against_frame(self, axis):\n df = DataFrame(np.random.default_rng(2).standard_normal((1000, 2)))\n lb = DataFrame(np.random.default_rng(2).standard_normal((1000, 2)))\n ub = lb + 1\n\n clipped_df = df.clip(lb, ub, axis=axis)\n\n lb_mask = df <= lb\n ub_mask = df >= ub\n mask = ~lb_mask & ~ub_mask\n\n tm.assert_frame_equal(clipped_df[lb_mask], lb[lb_mask])\n tm.assert_frame_equal(clipped_df[ub_mask], ub[ub_mask])\n tm.assert_frame_equal(clipped_df[mask], df[mask])\n\n def test_clip_against_unordered_columns(self):\n # GH#20911\n df1 = DataFrame(\n np.random.default_rng(2).standard_normal((1000, 4)),\n columns=["A", "B", "C", "D"],\n )\n df2 = DataFrame(\n np.random.default_rng(2).standard_normal((1000, 4)),\n columns=["D", "A", "B", "C"],\n )\n df3 = DataFrame(df2.values - 1, columns=["B", "D", "C", "A"])\n result_upper = df1.clip(lower=0, upper=df2)\n expected_upper = df1.clip(lower=0, upper=df2[df1.columns])\n result_lower = df1.clip(lower=df3, upper=3)\n expected_lower = df1.clip(lower=df3[df1.columns], upper=3)\n result_lower_upper = df1.clip(lower=df3, upper=df2)\n expected_lower_upper = df1.clip(lower=df3[df1.columns], upper=df2[df1.columns])\n tm.assert_frame_equal(result_upper, expected_upper)\n tm.assert_frame_equal(result_lower, expected_lower)\n tm.assert_frame_equal(result_lower_upper, expected_lower_upper)\n\n def test_clip_with_na_args(self, float_frame):\n """Should process np.nan argument as None"""\n # GH#17276\n tm.assert_frame_equal(float_frame.clip(np.nan), float_frame)\n tm.assert_frame_equal(float_frame.clip(upper=np.nan, lower=np.nan), float_frame)\n\n # GH#19992 and adjusted in GH#40420\n df = DataFrame({"col_0": [1, 2, 3], "col_1": [4, 5, 6], "col_2": [7, 8, 9]})\n\n msg = "Downcasting behavior in Series and DataFrame methods 'where'"\n # TODO: avoid this warning here? seems like we should never be upcasting\n # in the first place?\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.clip(lower=[4, 5, np.nan], axis=0)\n expected = DataFrame(\n {"col_0": [4, 5, 3], "col_1": [4, 5, 6], "col_2": [7, 8, 9]}\n )\n tm.assert_frame_equal(result, expected)\n\n result = df.clip(lower=[4, 5, np.nan], axis=1)\n expected = DataFrame(\n {"col_0": [4, 4, 4], "col_1": [5, 5, 6], "col_2": [7, 8, 9]}\n )\n tm.assert_frame_equal(result, expected)\n\n # GH#40420\n data = {"col_0": [9, -3, 0, -1, 5], "col_1": [-2, -7, 6, 8, -5]}\n df = DataFrame(data)\n t = Series([2, -4, np.nan, 6, 3])\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.clip(lower=t, axis=0)\n expected = DataFrame({"col_0": [9, -3, 0, 6, 5], "col_1": [2, -4, 6, 8, 3]})\n tm.assert_frame_equal(result, expected)\n\n def test_clip_int_data_with_float_bound(self):\n # GH51472\n df = DataFrame({"a": [1, 2, 3]})\n result = df.clip(lower=1.5)\n expected = DataFrame({"a": [1.5, 2.0, 3.0]})\n tm.assert_frame_equal(result, expected)\n\n def test_clip_with_list_bound(self):\n # GH#54817\n df = DataFrame([1, 5])\n expected = DataFrame([3, 5])\n result = df.clip([3])\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame([1, 3])\n result = df.clip(upper=[3])\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_clip.py
test_clip.py
Python
7,554
0.95
0.080402
0.092593
python-kit
766
2024-06-09T08:29:36.871533
MIT
true
7913807e7b8d4ae1f7d8c5a477a05d81
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\nclass TestCombine:\n @pytest.mark.parametrize(\n "data",\n [\n pd.date_range("2000", periods=4),\n pd.date_range("2000", periods=4, tz="US/Central"),\n pd.period_range("2000", periods=4),\n pd.timedelta_range(0, periods=4),\n ],\n )\n def test_combine_datetlike_udf(self, data):\n # GH#23079\n df = pd.DataFrame({"A": data})\n other = df.copy()\n df.iloc[1, 0] = None\n\n def combiner(a, b):\n return b\n\n result = df.combine(other, combiner)\n tm.assert_frame_equal(result, other)\n\n def test_combine_generic(self, float_frame):\n df1 = float_frame\n df2 = float_frame.loc[float_frame.index[:-5], ["A", "B", "C"]]\n\n combined = df1.combine(df2, np.add)\n combined2 = df2.combine(df1, np.add)\n assert combined["D"].isna().all()\n assert combined2["D"].isna().all()\n\n chunk = combined.loc[combined.index[:-5], ["A", "B", "C"]]\n chunk2 = combined2.loc[combined2.index[:-5], ["A", "B", "C"]]\n\n exp = (\n float_frame.loc[float_frame.index[:-5], ["A", "B", "C"]].reindex_like(chunk)\n * 2\n )\n tm.assert_frame_equal(chunk, exp)\n tm.assert_frame_equal(chunk2, exp)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_combine.py
test_combine.py
Python
1,359
0.95
0.085106
0.052632
awesome-app
261
2024-12-21T21:54:17.103912
Apache-2.0
true
4c660227700a44585328de2fa192a7d7
from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.cast import find_common_type\nfrom pandas.core.dtypes.common import is_dtype_equal\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameCombineFirst:\n def test_combine_first_mixed(self):\n a = Series(["a", "b"], index=range(2))\n b = Series(range(2), index=range(2))\n f = DataFrame({"A": a, "B": b})\n\n a = Series(["a", "b"], index=range(5, 7))\n b = Series(range(2), index=range(5, 7))\n g = DataFrame({"A": a, "B": b})\n\n exp = DataFrame({"A": list("abab"), "B": [0, 1, 0, 1]}, index=[0, 1, 5, 6])\n combined = f.combine_first(g)\n tm.assert_frame_equal(combined, exp)\n\n def test_combine_first(self, float_frame, using_infer_string):\n # disjoint\n head, tail = float_frame[:5], float_frame[5:]\n\n combined = head.combine_first(tail)\n reordered_frame = float_frame.reindex(combined.index)\n tm.assert_frame_equal(combined, reordered_frame)\n tm.assert_index_equal(combined.columns, float_frame.columns)\n tm.assert_series_equal(combined["A"], reordered_frame["A"])\n\n # same index\n fcopy = float_frame.copy()\n fcopy["A"] = 1\n del fcopy["C"]\n\n fcopy2 = float_frame.copy()\n fcopy2["B"] = 0\n del fcopy2["D"]\n\n combined = fcopy.combine_first(fcopy2)\n\n assert (combined["A"] == 1).all()\n tm.assert_series_equal(combined["B"], fcopy["B"])\n tm.assert_series_equal(combined["C"], fcopy2["C"])\n tm.assert_series_equal(combined["D"], fcopy["D"])\n\n # overlap\n head, tail = reordered_frame[:10].copy(), reordered_frame\n head["A"] = 1\n\n combined = head.combine_first(tail)\n assert (combined["A"][:10] == 1).all()\n\n # reverse overlap\n tail.iloc[:10, tail.columns.get_loc("A")] = 0\n combined = tail.combine_first(head)\n assert (combined["A"][:10] == 0).all()\n\n # no overlap\n f = float_frame[:10]\n g = float_frame[10:]\n combined = f.combine_first(g)\n tm.assert_series_equal(combined["A"].reindex(f.index), f["A"])\n tm.assert_series_equal(combined["A"].reindex(g.index), g["A"])\n\n # corner cases\n warning = FutureWarning if using_infer_string else None\n with tm.assert_produces_warning(warning, match="empty entries"):\n comb = float_frame.combine_first(DataFrame())\n tm.assert_frame_equal(comb, float_frame)\n\n comb = DataFrame().combine_first(float_frame)\n tm.assert_frame_equal(comb, float_frame.sort_index())\n\n comb = float_frame.combine_first(DataFrame(index=["faz", "boo"]))\n assert "faz" in comb.index\n\n # #2525\n df = DataFrame({"a": [1]}, index=[datetime(2012, 1, 1)])\n df2 = DataFrame(columns=["b"])\n result = df.combine_first(df2)\n assert "b" in result\n\n def test_combine_first_mixed_bug(self):\n idx = Index(["a", "b", "c", "e"])\n ser1 = Series([5.0, -9.0, 4.0, 100.0], index=idx)\n ser2 = Series(["a", "b", "c", "e"], index=idx)\n ser3 = Series([12, 4, 5, 97], index=idx)\n\n frame1 = DataFrame({"col0": ser1, "col2": ser2, "col3": ser3})\n\n idx = Index(["a", "b", "c", "f"])\n ser1 = Series([5.0, -9.0, 4.0, 100.0], index=idx)\n ser2 = Series(["a", "b", "c", "f"], index=idx)\n ser3 = Series([12, 4, 5, 97], index=idx)\n\n frame2 = DataFrame({"col1": ser1, "col2": ser2, "col5": ser3})\n\n combined = frame1.combine_first(frame2)\n assert len(combined.columns) == 5\n\n def test_combine_first_same_as_in_update(self):\n # gh 3016 (same as in update)\n df = DataFrame(\n [[1.0, 2.0, False, True], [4.0, 5.0, True, False]],\n columns=["A", "B", "bool1", "bool2"],\n )\n\n other = DataFrame([[45, 45]], index=[0], columns=["A", "B"])\n result = df.combine_first(other)\n tm.assert_frame_equal(result, df)\n\n df.loc[0, "A"] = np.nan\n result = df.combine_first(other)\n df.loc[0, "A"] = 45\n tm.assert_frame_equal(result, df)\n\n def test_combine_first_doc_example(self):\n # doc example\n df1 = DataFrame(\n {"A": [1.0, np.nan, 3.0, 5.0, np.nan], "B": [np.nan, 2.0, 3.0, np.nan, 6.0]}\n )\n\n df2 = DataFrame(\n {\n "A": [5.0, 2.0, 4.0, np.nan, 3.0, 7.0],\n "B": [np.nan, np.nan, 3.0, 4.0, 6.0, 8.0],\n }\n )\n\n result = df1.combine_first(df2)\n expected = DataFrame({"A": [1, 2, 3, 5, 3, 7.0], "B": [np.nan, 2, 3, 4, 6, 8]})\n tm.assert_frame_equal(result, expected)\n\n def test_combine_first_return_obj_type_with_bools(self):\n # GH3552\n\n df1 = DataFrame(\n [[np.nan, 3.0, True], [-4.6, np.nan, True], [np.nan, 7.0, False]]\n )\n df2 = DataFrame([[-42.6, np.nan, True], [-5.0, 1.6, False]], index=[1, 2])\n\n expected = Series([True, True, False], name=2, dtype=bool)\n\n result_12 = df1.combine_first(df2)[2]\n tm.assert_series_equal(result_12, expected)\n\n result_21 = df2.combine_first(df1)[2]\n tm.assert_series_equal(result_21, expected)\n\n @pytest.mark.parametrize(\n "data1, data2, data_expected",\n (\n (\n [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n [pd.NaT, pd.NaT, pd.NaT],\n [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n ),\n (\n [pd.NaT, pd.NaT, pd.NaT],\n [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n ),\n (\n [datetime(2000, 1, 2), pd.NaT, pd.NaT],\n [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n [datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n ),\n (\n [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n [datetime(2000, 1, 2), pd.NaT, pd.NaT],\n [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n ),\n ),\n )\n def test_combine_first_convert_datatime_correctly(\n self, data1, data2, data_expected\n ):\n # GH 3593\n\n df1, df2 = DataFrame({"a": data1}), DataFrame({"a": data2})\n result = df1.combine_first(df2)\n expected = DataFrame({"a": data_expected})\n tm.assert_frame_equal(result, expected)\n\n def test_combine_first_align_nan(self):\n # GH 7509 (not fixed)\n dfa = DataFrame([[pd.Timestamp("2011-01-01"), 2]], columns=["a", "b"])\n dfb = DataFrame([[4], [5]], columns=["b"])\n assert dfa["a"].dtype == "datetime64[ns]"\n assert dfa["b"].dtype == "int64"\n\n res = dfa.combine_first(dfb)\n exp = DataFrame(\n {"a": [pd.Timestamp("2011-01-01"), pd.NaT], "b": [2, 5]},\n columns=["a", "b"],\n )\n tm.assert_frame_equal(res, exp)\n assert res["a"].dtype == "datetime64[ns]"\n # TODO: this must be int64\n assert res["b"].dtype == "int64"\n\n res = dfa.iloc[:0].combine_first(dfb)\n exp = DataFrame({"a": [np.nan, np.nan], "b": [4, 5]}, columns=["a", "b"])\n tm.assert_frame_equal(res, exp)\n # TODO: this must be datetime64\n assert res["a"].dtype == "float64"\n # TODO: this must be int64\n assert res["b"].dtype == "int64"\n\n def test_combine_first_timezone(self, unit):\n # see gh-7630\n data1 = pd.to_datetime("20100101 01:01").tz_localize("UTC").as_unit(unit)\n df1 = DataFrame(\n columns=["UTCdatetime", "abc"],\n data=data1,\n index=pd.date_range("20140627", periods=1),\n )\n data2 = pd.to_datetime("20121212 12:12").tz_localize("UTC").as_unit(unit)\n df2 = DataFrame(\n columns=["UTCdatetime", "xyz"],\n data=data2,\n index=pd.date_range("20140628", periods=1),\n )\n res = df2[["UTCdatetime"]].combine_first(df1)\n exp = DataFrame(\n {\n "UTCdatetime": [\n pd.Timestamp("2010-01-01 01:01", tz="UTC"),\n pd.Timestamp("2012-12-12 12:12", tz="UTC"),\n ],\n "abc": [pd.Timestamp("2010-01-01 01:01:00", tz="UTC"), pd.NaT],\n },\n columns=["UTCdatetime", "abc"],\n index=pd.date_range("20140627", periods=2, freq="D"),\n dtype=f"datetime64[{unit}, UTC]",\n )\n assert res["UTCdatetime"].dtype == f"datetime64[{unit}, UTC]"\n assert res["abc"].dtype == f"datetime64[{unit}, UTC]"\n\n tm.assert_frame_equal(res, exp)\n\n def test_combine_first_timezone2(self, unit):\n # see gh-10567\n dts1 = pd.date_range("2015-01-01", "2015-01-05", tz="UTC", unit=unit)\n df1 = DataFrame({"DATE": dts1})\n dts2 = pd.date_range("2015-01-03", "2015-01-05", tz="UTC", unit=unit)\n df2 = DataFrame({"DATE": dts2})\n\n res = df1.combine_first(df2)\n tm.assert_frame_equal(res, df1)\n assert res["DATE"].dtype == f"datetime64[{unit}, UTC]"\n\n def test_combine_first_timezone3(self, unit):\n dts1 = pd.DatetimeIndex(\n ["2011-01-01", "NaT", "2011-01-03", "2011-01-04"], tz="US/Eastern"\n ).as_unit(unit)\n df1 = DataFrame({"DATE": dts1}, index=[1, 3, 5, 7])\n dts2 = pd.DatetimeIndex(\n ["2012-01-01", "2012-01-02", "2012-01-03"], tz="US/Eastern"\n ).as_unit(unit)\n df2 = DataFrame({"DATE": dts2}, index=[2, 4, 5])\n\n res = df1.combine_first(df2)\n exp_dts = pd.DatetimeIndex(\n [\n "2011-01-01",\n "2012-01-01",\n "NaT",\n "2012-01-02",\n "2011-01-03",\n "2011-01-04",\n ],\n tz="US/Eastern",\n ).as_unit(unit)\n exp = DataFrame({"DATE": exp_dts}, index=[1, 2, 3, 4, 5, 7])\n tm.assert_frame_equal(res, exp)\n\n # FIXME: parametrizing over unit breaks on non-nano\n def test_combine_first_timezone4(self):\n # different tz\n dts1 = pd.date_range("2015-01-01", "2015-01-05", tz="US/Eastern")\n df1 = DataFrame({"DATE": dts1})\n dts2 = pd.date_range("2015-01-03", "2015-01-05")\n df2 = DataFrame({"DATE": dts2})\n\n # if df1 doesn't have NaN, keep its dtype\n res = df1.combine_first(df2)\n tm.assert_frame_equal(res, df1)\n assert res["DATE"].dtype == "datetime64[ns, US/Eastern]"\n\n def test_combine_first_timezone5(self, unit):\n dts1 = pd.date_range("2015-01-01", "2015-01-02", tz="US/Eastern", unit=unit)\n df1 = DataFrame({"DATE": dts1})\n dts2 = pd.date_range("2015-01-01", "2015-01-03", unit=unit)\n df2 = DataFrame({"DATE": dts2})\n\n res = df1.combine_first(df2)\n exp_dts = [\n pd.Timestamp("2015-01-01", tz="US/Eastern"),\n pd.Timestamp("2015-01-02", tz="US/Eastern"),\n pd.Timestamp("2015-01-03"),\n ]\n exp = DataFrame({"DATE": exp_dts})\n tm.assert_frame_equal(res, exp)\n assert res["DATE"].dtype == "object"\n\n def test_combine_first_timedelta(self):\n data1 = pd.TimedeltaIndex(["1 day", "NaT", "3 day", "4day"])\n df1 = DataFrame({"TD": data1}, index=[1, 3, 5, 7])\n data2 = pd.TimedeltaIndex(["10 day", "11 day", "12 day"])\n df2 = DataFrame({"TD": data2}, index=[2, 4, 5])\n\n res = df1.combine_first(df2)\n exp_dts = pd.TimedeltaIndex(\n ["1 day", "10 day", "NaT", "11 day", "3 day", "4 day"]\n )\n exp = DataFrame({"TD": exp_dts}, index=[1, 2, 3, 4, 5, 7])\n tm.assert_frame_equal(res, exp)\n assert res["TD"].dtype == "timedelta64[ns]"\n\n def test_combine_first_period(self):\n data1 = pd.PeriodIndex(["2011-01", "NaT", "2011-03", "2011-04"], freq="M")\n df1 = DataFrame({"P": data1}, index=[1, 3, 5, 7])\n data2 = pd.PeriodIndex(["2012-01-01", "2012-02", "2012-03"], freq="M")\n df2 = DataFrame({"P": data2}, index=[2, 4, 5])\n\n res = df1.combine_first(df2)\n exp_dts = pd.PeriodIndex(\n ["2011-01", "2012-01", "NaT", "2012-02", "2011-03", "2011-04"], freq="M"\n )\n exp = DataFrame({"P": exp_dts}, index=[1, 2, 3, 4, 5, 7])\n tm.assert_frame_equal(res, exp)\n assert res["P"].dtype == data1.dtype\n\n # different freq\n dts2 = pd.PeriodIndex(["2012-01-01", "2012-01-02", "2012-01-03"], freq="D")\n df2 = DataFrame({"P": dts2}, index=[2, 4, 5])\n\n res = df1.combine_first(df2)\n exp_dts = [\n pd.Period("2011-01", freq="M"),\n pd.Period("2012-01-01", freq="D"),\n pd.NaT,\n pd.Period("2012-01-02", freq="D"),\n pd.Period("2011-03", freq="M"),\n pd.Period("2011-04", freq="M"),\n ]\n exp = DataFrame({"P": exp_dts}, index=[1, 2, 3, 4, 5, 7])\n tm.assert_frame_equal(res, exp)\n assert res["P"].dtype == "object"\n\n def test_combine_first_int(self):\n # GH14687 - integer series that do no align exactly\n\n df1 = DataFrame({"a": [0, 1, 3, 5]}, dtype="int64")\n df2 = DataFrame({"a": [1, 4]}, dtype="int64")\n\n result_12 = df1.combine_first(df2)\n expected_12 = DataFrame({"a": [0, 1, 3, 5]})\n tm.assert_frame_equal(result_12, expected_12)\n\n result_21 = df2.combine_first(df1)\n expected_21 = DataFrame({"a": [1, 4, 3, 5]})\n tm.assert_frame_equal(result_21, expected_21)\n\n @pytest.mark.parametrize("val", [1, 1.0])\n def test_combine_first_with_asymmetric_other(self, val):\n # see gh-20699\n df1 = DataFrame({"isNum": [val]})\n df2 = DataFrame({"isBool": [True]})\n\n res = df1.combine_first(df2)\n exp = DataFrame({"isBool": [True], "isNum": [val]})\n\n tm.assert_frame_equal(res, exp)\n\n def test_combine_first_string_dtype_only_na(self, nullable_string_dtype):\n # GH: 37519\n df = DataFrame(\n {"a": ["962", "85"], "b": [pd.NA] * 2}, dtype=nullable_string_dtype\n )\n df2 = DataFrame({"a": ["85"], "b": [pd.NA]}, dtype=nullable_string_dtype)\n df.set_index(["a", "b"], inplace=True)\n df2.set_index(["a", "b"], inplace=True)\n result = df.combine_first(df2)\n expected = DataFrame(\n {"a": ["962", "85"], "b": [pd.NA] * 2}, dtype=nullable_string_dtype\n ).set_index(["a", "b"])\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "scalar1, scalar2",\n [\n (datetime(2020, 1, 1), datetime(2020, 1, 2)),\n (pd.Period("2020-01-01", "D"), pd.Period("2020-01-02", "D")),\n (pd.Timedelta("89 days"), pd.Timedelta("60 min")),\n (pd.Interval(left=0, right=1), pd.Interval(left=2, right=3, closed="left")),\n ],\n)\ndef test_combine_first_timestamp_bug(scalar1, scalar2, nulls_fixture):\n # GH28481\n na_value = nulls_fixture\n\n frame = DataFrame([[na_value, na_value]], columns=["a", "b"])\n other = DataFrame([[scalar1, scalar2]], columns=["b", "c"])\n\n common_dtype = find_common_type([frame.dtypes["b"], other.dtypes["b"]])\n\n if is_dtype_equal(common_dtype, "object") or frame.dtypes["b"] == other.dtypes["b"]:\n val = scalar1\n else:\n val = na_value\n\n result = frame.combine_first(other)\n\n expected = DataFrame([[na_value, val, scalar2]], columns=["a", "b", "c"])\n\n expected["b"] = expected["b"].astype(common_dtype)\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_combine_first_timestamp_bug_NaT():\n # GH28481\n frame = DataFrame([[pd.NaT, pd.NaT]], columns=["a", "b"])\n other = DataFrame(\n [[datetime(2020, 1, 1), datetime(2020, 1, 2)]], columns=["b", "c"]\n )\n\n result = frame.combine_first(other)\n expected = DataFrame(\n [[pd.NaT, datetime(2020, 1, 1), datetime(2020, 1, 2)]], columns=["a", "b", "c"]\n )\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_combine_first_with_nan_multiindex():\n # gh-36562\n\n mi1 = MultiIndex.from_arrays(\n [["b", "b", "c", "a", "b", np.nan], [1, 2, 3, 4, 5, 6]], names=["a", "b"]\n )\n df = DataFrame({"c": [1, 1, 1, 1, 1, 1]}, index=mi1)\n mi2 = MultiIndex.from_arrays(\n [["a", "b", "c", "a", "b", "d"], [1, 1, 1, 1, 1, 1]], names=["a", "b"]\n )\n s = Series([1, 2, 3, 4, 5, 6], index=mi2)\n res = df.combine_first(DataFrame({"d": s}))\n mi_expected = MultiIndex.from_arrays(\n [\n ["a", "a", "a", "b", "b", "b", "b", "c", "c", "d", np.nan],\n [1, 1, 4, 1, 1, 2, 5, 1, 3, 1, 6],\n ],\n names=["a", "b"],\n )\n expected = DataFrame(\n {\n "c": [np.nan, np.nan, 1, 1, 1, 1, 1, np.nan, 1, np.nan, 1],\n "d": [1.0, 4.0, np.nan, 2.0, 5.0, np.nan, np.nan, 3.0, np.nan, 6.0, np.nan],\n },\n index=mi_expected,\n )\n tm.assert_frame_equal(res, expected)\n\n\ndef test_combine_preserve_dtypes():\n # GH7509\n a_column = Series(["a", "b"], index=range(2))\n b_column = Series(range(2), index=range(2))\n df1 = DataFrame({"A": a_column, "B": b_column})\n\n c_column = Series(["a", "b"], index=range(5, 7))\n b_column = Series(range(-1, 1), index=range(5, 7))\n df2 = DataFrame({"B": b_column, "C": c_column})\n\n expected = DataFrame(\n {\n "A": ["a", "b", np.nan, np.nan],\n "B": [0, 1, -1, 0],\n "C": [np.nan, np.nan, "a", "b"],\n },\n index=[0, 1, 5, 6],\n )\n combined = df1.combine_first(df2)\n tm.assert_frame_equal(combined, expected)\n\n\ndef test_combine_first_duplicates_rows_for_nan_index_values():\n # GH39881\n df1 = DataFrame(\n {"x": [9, 10, 11]},\n index=MultiIndex.from_arrays([[1, 2, 3], [np.nan, 5, 6]], names=["a", "b"]),\n )\n\n df2 = DataFrame(\n {"y": [12, 13, 14]},\n index=MultiIndex.from_arrays([[1, 2, 4], [np.nan, 5, 7]], names=["a", "b"]),\n )\n\n expected = DataFrame(\n {\n "x": [9.0, 10.0, 11.0, np.nan],\n "y": [12.0, 13.0, np.nan, 14.0],\n },\n index=MultiIndex.from_arrays(\n [[1, 2, 3, 4], [np.nan, 5, 6, 7]], names=["a", "b"]\n ),\n )\n combined = df1.combine_first(df2)\n tm.assert_frame_equal(combined, expected)\n\n\ndef test_combine_first_int64_not_cast_to_float64():\n # GH 28613\n df_1 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})\n df_2 = DataFrame({"A": [1, 20, 30], "B": [40, 50, 60], "C": [12, 34, 65]})\n result = df_1.combine_first(df_2)\n expected = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [12, 34, 65]})\n tm.assert_frame_equal(result, expected)\n\n\ndef test_midx_losing_dtype():\n # GH#49830\n midx = MultiIndex.from_arrays([[0, 0], [np.nan, np.nan]])\n midx2 = MultiIndex.from_arrays([[1, 1], [np.nan, np.nan]])\n df1 = DataFrame({"a": [None, 4]}, index=midx)\n df2 = DataFrame({"a": [3, 3]}, index=midx2)\n result = df1.combine_first(df2)\n expected_midx = MultiIndex.from_arrays(\n [[0, 0, 1, 1], [np.nan, np.nan, np.nan, np.nan]]\n )\n expected = DataFrame({"a": [np.nan, 4, 3, 3]}, index=expected_midx)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_combine_first_empty_columns():\n left = DataFrame(columns=["a", "b"])\n right = DataFrame(columns=["a", "c"])\n result = left.combine_first(right)\n expected = DataFrame(columns=["a", "b", "c"])\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_combine_first.py
test_combine_first.py
Python
19,726
0.95
0.053957
0.067391
python-kit
704
2025-04-07T09:08:37.447680
GPL-3.0
true
1afd1f1d73c2beda912ce1298a646a92
import numpy as np\nimport pytest\n\nfrom pandas.compat.numpy import np_version_gte1p25\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize("align_axis", [0, 1, "index", "columns"])\ndef test_compare_axis(align_axis):\n # GH#30429\n df = pd.DataFrame(\n {"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},\n columns=["col1", "col2", "col3"],\n )\n df2 = df.copy()\n df2.loc[0, "col1"] = "c"\n df2.loc[2, "col3"] = 4.0\n\n result = df.compare(df2, align_axis=align_axis)\n\n if align_axis in (1, "columns"):\n indices = pd.Index([0, 2])\n columns = pd.MultiIndex.from_product([["col1", "col3"], ["self", "other"]])\n expected = pd.DataFrame(\n [["a", "c", np.nan, np.nan], [np.nan, np.nan, 3.0, 4.0]],\n index=indices,\n columns=columns,\n )\n else:\n indices = pd.MultiIndex.from_product([[0, 2], ["self", "other"]])\n columns = pd.Index(["col1", "col3"])\n expected = pd.DataFrame(\n [["a", np.nan], ["c", np.nan], [np.nan, 3.0], [np.nan, 4.0]],\n index=indices,\n columns=columns,\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "keep_shape, keep_equal",\n [\n (True, False),\n (False, True),\n (True, True),\n # False, False case is already covered in test_compare_axis\n ],\n)\ndef test_compare_various_formats(keep_shape, keep_equal):\n df = pd.DataFrame(\n {"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},\n columns=["col1", "col2", "col3"],\n )\n df2 = df.copy()\n df2.loc[0, "col1"] = "c"\n df2.loc[2, "col3"] = 4.0\n\n result = df.compare(df2, keep_shape=keep_shape, keep_equal=keep_equal)\n\n if keep_shape:\n indices = pd.Index([0, 1, 2])\n columns = pd.MultiIndex.from_product(\n [["col1", "col2", "col3"], ["self", "other"]]\n )\n if keep_equal:\n expected = pd.DataFrame(\n [\n ["a", "c", 1.0, 1.0, 1.0, 1.0],\n ["b", "b", 2.0, 2.0, 2.0, 2.0],\n ["c", "c", np.nan, np.nan, 3.0, 4.0],\n ],\n index=indices,\n columns=columns,\n )\n else:\n expected = pd.DataFrame(\n [\n ["a", "c", np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan, 3.0, 4.0],\n ],\n index=indices,\n columns=columns,\n )\n else:\n indices = pd.Index([0, 2])\n columns = pd.MultiIndex.from_product([["col1", "col3"], ["self", "other"]])\n expected = pd.DataFrame(\n [["a", "c", 1.0, 1.0], ["c", "c", 3.0, 4.0]], index=indices, columns=columns\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_compare_with_equal_nulls():\n # We want to make sure two NaNs are considered the same\n # and dropped where applicable\n df = pd.DataFrame(\n {"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},\n columns=["col1", "col2", "col3"],\n )\n df2 = df.copy()\n df2.loc[0, "col1"] = "c"\n\n result = df.compare(df2)\n indices = pd.Index([0])\n columns = pd.MultiIndex.from_product([["col1"], ["self", "other"]])\n expected = pd.DataFrame([["a", "c"]], index=indices, columns=columns)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_compare_with_non_equal_nulls():\n # We want to make sure the relevant NaNs do not get dropped\n # even if the entire row or column are NaNs\n df = pd.DataFrame(\n {"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},\n columns=["col1", "col2", "col3"],\n )\n df2 = df.copy()\n df2.loc[0, "col1"] = "c"\n df2.loc[2, "col3"] = np.nan\n\n result = df.compare(df2)\n\n indices = pd.Index([0, 2])\n columns = pd.MultiIndex.from_product([["col1", "col3"], ["self", "other"]])\n expected = pd.DataFrame(\n [["a", "c", np.nan, np.nan], [np.nan, np.nan, 3.0, np.nan]],\n index=indices,\n columns=columns,\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize("align_axis", [0, 1])\ndef test_compare_multi_index(align_axis):\n df = pd.DataFrame(\n {"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]}\n )\n df.columns = pd.MultiIndex.from_arrays([["a", "a", "b"], ["col1", "col2", "col3"]])\n df.index = pd.MultiIndex.from_arrays([["x", "x", "y"], [0, 1, 2]])\n\n df2 = df.copy()\n df2.iloc[0, 0] = "c"\n df2.iloc[2, 2] = 4.0\n\n result = df.compare(df2, align_axis=align_axis)\n\n if align_axis == 0:\n indices = pd.MultiIndex.from_arrays(\n [["x", "x", "y", "y"], [0, 0, 2, 2], ["self", "other", "self", "other"]]\n )\n columns = pd.MultiIndex.from_arrays([["a", "b"], ["col1", "col3"]])\n data = [["a", np.nan], ["c", np.nan], [np.nan, 3.0], [np.nan, 4.0]]\n else:\n indices = pd.MultiIndex.from_arrays([["x", "y"], [0, 2]])\n columns = pd.MultiIndex.from_arrays(\n [\n ["a", "a", "b", "b"],\n ["col1", "col1", "col3", "col3"],\n ["self", "other", "self", "other"],\n ]\n )\n data = [["a", "c", np.nan, np.nan], [np.nan, np.nan, 3.0, 4.0]]\n\n expected = pd.DataFrame(data=data, index=indices, columns=columns)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_compare_unaligned_objects():\n # test DataFrames with different indices\n msg = (\n r"Can only compare identically-labeled \(both index and columns\) DataFrame "\n "objects"\n )\n with pytest.raises(ValueError, match=msg):\n df1 = pd.DataFrame([1, 2, 3], index=["a", "b", "c"])\n df2 = pd.DataFrame([1, 2, 3], index=["a", "b", "d"])\n df1.compare(df2)\n\n # test DataFrames with different shapes\n msg = (\n r"Can only compare identically-labeled \(both index and columns\) DataFrame "\n "objects"\n )\n with pytest.raises(ValueError, match=msg):\n df1 = pd.DataFrame(np.ones((3, 3)))\n df2 = pd.DataFrame(np.zeros((2, 1)))\n df1.compare(df2)\n\n\ndef test_compare_result_names():\n # GH 44354\n df1 = pd.DataFrame(\n {"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},\n )\n df2 = pd.DataFrame(\n {\n "col1": ["c", "b", "c"],\n "col2": [1.0, 2.0, np.nan],\n "col3": [1.0, 2.0, np.nan],\n },\n )\n result = df1.compare(df2, result_names=("left", "right"))\n expected = pd.DataFrame(\n {\n ("col1", "left"): {0: "a", 2: np.nan},\n ("col1", "right"): {0: "c", 2: np.nan},\n ("col3", "left"): {0: np.nan, 2: 3.0},\n ("col3", "right"): {0: np.nan, 2: np.nan},\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "result_names",\n [\n [1, 2],\n "HK",\n {"2": 2, "3": 3},\n 3,\n 3.0,\n ],\n)\ndef test_invalid_input_result_names(result_names):\n # GH 44354\n df1 = pd.DataFrame(\n {"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]},\n )\n df2 = pd.DataFrame(\n {\n "col1": ["c", "b", "c"],\n "col2": [1.0, 2.0, np.nan],\n "col3": [1.0, 2.0, np.nan],\n },\n )\n with pytest.raises(\n TypeError,\n match=(\n f"Passing 'result_names' as a {type(result_names)} is not "\n "supported. Provide 'result_names' as a tuple instead."\n ),\n ):\n df1.compare(df2, result_names=result_names)\n\n\n@pytest.mark.parametrize(\n "val1,val2",\n [(4, pd.NA), (pd.NA, pd.NA), (pd.NA, 4)],\n)\ndef test_compare_ea_and_np_dtype(val1, val2):\n # GH 48966\n arr = [4.0, val1]\n ser = pd.Series([1, val2], dtype="Int64")\n\n df1 = pd.DataFrame({"a": arr, "b": [1.0, 2]})\n df2 = pd.DataFrame({"a": ser, "b": [1.0, 2]})\n expected = pd.DataFrame(\n {\n ("a", "self"): arr,\n ("a", "other"): ser,\n ("b", "self"): np.nan,\n ("b", "other"): np.nan,\n }\n )\n if val1 is pd.NA and val2 is pd.NA:\n # GH#18463 TODO: is this really the desired behavior?\n expected.loc[1, ("a", "self")] = np.nan\n\n if val1 is pd.NA and np_version_gte1p25:\n # can't compare with numpy array if it contains pd.NA\n with pytest.raises(TypeError, match="boolean value of NA is ambiguous"):\n result = df1.compare(df2, keep_shape=True)\n else:\n result = df1.compare(df2, keep_shape=True)\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "df1_val,df2_val,diff_self,diff_other",\n [\n (4, 3, 4, 3),\n (4, 4, pd.NA, pd.NA),\n (4, pd.NA, 4, pd.NA),\n (pd.NA, pd.NA, pd.NA, pd.NA),\n ],\n)\ndef test_compare_nullable_int64_dtype(df1_val, df2_val, diff_self, diff_other):\n # GH 48966\n df1 = pd.DataFrame({"a": pd.Series([df1_val, pd.NA], dtype="Int64"), "b": [1.0, 2]})\n df2 = df1.copy()\n df2.loc[0, "a"] = df2_val\n\n expected = pd.DataFrame(\n {\n ("a", "self"): pd.Series([diff_self, pd.NA], dtype="Int64"),\n ("a", "other"): pd.Series([diff_other, pd.NA], dtype="Int64"),\n ("b", "self"): np.nan,\n ("b", "other"): np.nan,\n }\n )\n result = df1.compare(df2, keep_shape=True)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_compare.py
test_compare.py
Python
9,615
0.95
0.059016
0.052239
python-kit
499
2024-03-05T13:05:00.362127
MIT
true
12c865e833ef496f4eddbb79a8807214
import datetime\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\nclass TestConvertDtypes:\n @pytest.mark.parametrize(\n "convert_integer, expected", [(False, np.dtype("int32")), (True, "Int32")]\n )\n def test_convert_dtypes(self, convert_integer, expected, string_storage):\n # Specific types are tested in tests/series/test_dtypes.py\n # Just check that it works for DataFrame here\n df = pd.DataFrame(\n {\n "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),\n "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),\n }\n )\n with pd.option_context("string_storage", string_storage):\n result = df.convert_dtypes(True, True, convert_integer, False)\n expected = pd.DataFrame(\n {\n "a": pd.Series([1, 2, 3], dtype=expected),\n "b": pd.Series(["x", "y", "z"], dtype=f"string[{string_storage}]"),\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_convert_empty(self):\n # Empty DataFrame can pass convert_dtypes, see GH#40393\n empty_df = pd.DataFrame()\n tm.assert_frame_equal(empty_df, empty_df.convert_dtypes())\n\n def test_convert_dtypes_retain_column_names(self):\n # GH#41435\n df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})\n df.columns.name = "cols"\n\n result = df.convert_dtypes()\n tm.assert_index_equal(result.columns, df.columns)\n assert result.columns.name == "cols"\n\n def test_pyarrow_dtype_backend(self):\n pa = pytest.importorskip("pyarrow")\n df = pd.DataFrame(\n {\n "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),\n "b": pd.Series(["x", "y", None], dtype=np.dtype("O")),\n "c": pd.Series([True, False, None], dtype=np.dtype("O")),\n "d": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),\n "e": pd.Series(pd.date_range("2022", periods=3)),\n "f": pd.Series(pd.date_range("2022", periods=3, tz="UTC").as_unit("s")),\n "g": pd.Series(pd.timedelta_range("1D", periods=3)),\n }\n )\n result = df.convert_dtypes(dtype_backend="pyarrow")\n expected = pd.DataFrame(\n {\n "a": pd.arrays.ArrowExtensionArray(\n pa.array([1, 2, 3], type=pa.int32())\n ),\n "b": pd.arrays.ArrowExtensionArray(pa.array(["x", "y", None])),\n "c": pd.arrays.ArrowExtensionArray(pa.array([True, False, None])),\n "d": pd.arrays.ArrowExtensionArray(pa.array([None, 100.5, 200.0])),\n "e": pd.arrays.ArrowExtensionArray(\n pa.array(\n [\n datetime.datetime(2022, 1, 1),\n datetime.datetime(2022, 1, 2),\n datetime.datetime(2022, 1, 3),\n ],\n type=pa.timestamp(unit="ns"),\n )\n ),\n "f": pd.arrays.ArrowExtensionArray(\n pa.array(\n [\n datetime.datetime(2022, 1, 1),\n datetime.datetime(2022, 1, 2),\n datetime.datetime(2022, 1, 3),\n ],\n type=pa.timestamp(unit="s", tz="UTC"),\n )\n ),\n "g": pd.arrays.ArrowExtensionArray(\n pa.array(\n [\n datetime.timedelta(1),\n datetime.timedelta(2),\n datetime.timedelta(3),\n ],\n type=pa.duration("ns"),\n )\n ),\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_pyarrow_dtype_backend_already_pyarrow(self):\n pytest.importorskip("pyarrow")\n expected = pd.DataFrame([1, 2, 3], dtype="int64[pyarrow]")\n result = expected.convert_dtypes(dtype_backend="pyarrow")\n tm.assert_frame_equal(result, expected)\n\n def test_pyarrow_dtype_backend_from_pandas_nullable(self):\n pa = pytest.importorskip("pyarrow")\n df = pd.DataFrame(\n {\n "a": pd.Series([1, 2, None], dtype="Int32"),\n "b": pd.Series(["x", "y", None], dtype="string[python]"),\n "c": pd.Series([True, False, None], dtype="boolean"),\n "d": pd.Series([None, 100.5, 200], dtype="Float64"),\n }\n )\n result = df.convert_dtypes(dtype_backend="pyarrow")\n expected = pd.DataFrame(\n {\n "a": pd.arrays.ArrowExtensionArray(\n pa.array([1, 2, None], type=pa.int32())\n ),\n "b": pd.arrays.ArrowExtensionArray(pa.array(["x", "y", None])),\n "c": pd.arrays.ArrowExtensionArray(pa.array([True, False, None])),\n "d": pd.arrays.ArrowExtensionArray(pa.array([None, 100.5, 200.0])),\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_pyarrow_dtype_empty_object(self):\n # GH 50970\n pytest.importorskip("pyarrow")\n expected = pd.DataFrame(columns=[0])\n result = expected.convert_dtypes(dtype_backend="pyarrow")\n tm.assert_frame_equal(result, expected)\n\n def test_pyarrow_engine_lines_false(self):\n # GH 48893\n df = pd.DataFrame({"a": [1, 2, 3]})\n msg = (\n "dtype_backend numpy is invalid, only 'numpy_nullable' and "\n "'pyarrow' are allowed."\n )\n with pytest.raises(ValueError, match=msg):\n df.convert_dtypes(dtype_backend="numpy")\n\n def test_pyarrow_backend_no_conversion(self):\n # GH#52872\n pytest.importorskip("pyarrow")\n df = pd.DataFrame({"a": [1, 2], "b": 1.5, "c": True, "d": "x"})\n expected = df.copy()\n result = df.convert_dtypes(\n convert_floating=False,\n convert_integer=False,\n convert_boolean=False,\n convert_string=False,\n dtype_backend="pyarrow",\n )\n tm.assert_frame_equal(result, expected)\n\n def test_convert_dtypes_pyarrow_to_np_nullable(self):\n # GH 53648\n pytest.importorskip("pyarrow")\n ser = pd.DataFrame(range(2), dtype="int32[pyarrow]")\n result = ser.convert_dtypes(dtype_backend="numpy_nullable")\n expected = pd.DataFrame(range(2), dtype="Int32")\n tm.assert_frame_equal(result, expected)\n\n def test_convert_dtypes_pyarrow_timestamp(self):\n # GH 54191\n pytest.importorskip("pyarrow")\n ser = pd.Series(pd.date_range("2020-01-01", "2020-01-02", freq="1min"))\n expected = ser.astype("timestamp[ms][pyarrow]")\n result = expected.convert_dtypes(dtype_backend="pyarrow")\n tm.assert_series_equal(result, expected)\n\n def test_convert_dtypes_avoid_block_splitting(self):\n # GH#55341\n df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": "a"})\n result = df.convert_dtypes(convert_integer=False)\n expected = pd.DataFrame(\n {\n "a": [1, 2, 3],\n "b": [4, 5, 6],\n "c": pd.Series(["a"] * 3, dtype="string[python]"),\n }\n )\n tm.assert_frame_equal(result, expected)\n assert result._mgr.nblocks == 2\n\n def test_convert_dtypes_from_arrow(self):\n # GH#56581\n df = pd.DataFrame([["a", datetime.time(18, 12)]], columns=["a", "b"])\n result = df.convert_dtypes()\n expected = df.astype({"a": "string[python]"})\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_convert_dtypes.py
test_convert_dtypes.py
Python
7,848
0.95
0.075758
0.060773
node-utils
399
2025-03-18T06:31:21.552176
MIT
true
68008bc9ee37f683b680854ad7f3e131
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\nclass TestCopy:\n @pytest.mark.parametrize("attr", ["index", "columns"])\n def test_copy_index_name_checking(self, float_frame, attr):\n # don't want to be able to modify the index stored elsewhere after\n # making a copy\n ind = getattr(float_frame, attr)\n ind.name = None\n cp = float_frame.copy()\n getattr(cp, attr).name = "foo"\n assert getattr(float_frame, attr).name is None\n\n @td.skip_copy_on_write_invalid_test\n def test_copy_cache(self):\n # GH#31784 _item_cache not cleared on copy causes incorrect reads after updates\n df = DataFrame({"a": [1]})\n\n df["x"] = [0]\n df["a"]\n\n df.copy()\n\n df["a"].values[0] = -1\n\n tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0]}))\n\n df["y"] = [0]\n\n assert df["a"].values[0] == -1\n tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0], "y": [0]}))\n\n def test_copy(self, float_frame, float_string_frame):\n cop = float_frame.copy()\n cop["E"] = cop["A"]\n assert "E" not in float_frame\n\n # copy objects\n copy = float_string_frame.copy()\n assert copy._mgr is not float_string_frame._mgr\n\n @td.skip_array_manager_invalid_test\n def test_copy_consolidates(self):\n # GH#42477\n df = DataFrame(\n {\n "a": np.random.default_rng(2).integers(0, 100, size=55),\n "b": np.random.default_rng(2).integers(0, 100, size=55),\n }\n )\n\n for i in range(10):\n df.loc[:, f"n_{i}"] = np.random.default_rng(2).integers(0, 100, size=55)\n\n assert len(df._mgr.blocks) == 11\n result = df.copy()\n assert len(result._mgr.blocks) == 1\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_copy.py
test_copy.py
Python
1,873
0.95
0.09375
0.104167
react-lib
592
2025-04-08T09:04:49.598859
Apache-2.0
true
96fbfda99ddaf4cbee5ba2901cc2c40d
from pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameCount:\n def test_count(self):\n # corner case\n frame = DataFrame()\n ct1 = frame.count(1)\n assert isinstance(ct1, Series)\n\n ct2 = frame.count(0)\n assert isinstance(ct2, Series)\n\n # GH#423\n df = DataFrame(index=range(10))\n result = df.count(1)\n expected = Series(0, index=df.index)\n tm.assert_series_equal(result, expected)\n\n df = DataFrame(columns=range(10))\n result = df.count(0)\n expected = Series(0, index=df.columns)\n tm.assert_series_equal(result, expected)\n\n df = DataFrame()\n result = df.count()\n expected = Series(dtype="int64")\n tm.assert_series_equal(result, expected)\n\n def test_count_objects(self, float_string_frame):\n dm = DataFrame(float_string_frame._series)\n df = DataFrame(float_string_frame._series)\n\n tm.assert_series_equal(dm.count(), df.count())\n tm.assert_series_equal(dm.count(1), df.count(1))\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_count.py
test_count.py
Python
1,083
0.95
0.076923
0.064516
node-utils
265
2024-04-17T00:01:55.304747
GPL-3.0
true
05cc3863ca0a8fdc861571644c22f376
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n date_range,\n isna,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameCov:\n def test_cov(self, float_frame, float_string_frame):\n # min_periods no NAs (corner case)\n expected = float_frame.cov()\n result = float_frame.cov(min_periods=len(float_frame))\n\n tm.assert_frame_equal(expected, result)\n\n result = float_frame.cov(min_periods=len(float_frame) + 1)\n assert isna(result.values).all()\n\n # with NAs\n frame = float_frame.copy()\n frame.iloc[:5, frame.columns.get_loc("A")] = np.nan\n frame.iloc[5:10, frame.columns.get_loc("B")] = np.nan\n result = frame.cov(min_periods=len(frame) - 8)\n expected = frame.cov()\n expected.loc["A", "B"] = np.nan\n expected.loc["B", "A"] = np.nan\n tm.assert_frame_equal(result, expected)\n\n # regular\n result = frame.cov()\n expected = frame["A"].cov(frame["C"])\n tm.assert_almost_equal(result["A"]["C"], expected)\n\n # fails on non-numeric types\n with pytest.raises(ValueError, match="could not convert string to float"):\n float_string_frame.cov()\n result = float_string_frame.cov(numeric_only=True)\n expected = float_string_frame.loc[:, ["A", "B", "C", "D"]].cov()\n tm.assert_frame_equal(result, expected)\n\n # Single column frame\n df = DataFrame(np.linspace(0.0, 1.0, 10))\n result = df.cov()\n expected = DataFrame(\n np.cov(df.values.T).reshape((1, 1)), index=df.columns, columns=df.columns\n )\n tm.assert_frame_equal(result, expected)\n df.loc[0] = np.nan\n result = df.cov()\n expected = DataFrame(\n np.cov(df.values[1:].T).reshape((1, 1)),\n index=df.columns,\n columns=df.columns,\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("test_ddof", [None, 0, 1, 2, 3])\n def test_cov_ddof(self, test_ddof):\n # GH#34611\n np_array1 = np.random.default_rng(2).random(10)\n np_array2 = np.random.default_rng(2).random(10)\n df = DataFrame({0: np_array1, 1: np_array2})\n result = df.cov(ddof=test_ddof)\n expected_np = np.cov(np_array1, np_array2, ddof=test_ddof)\n expected = DataFrame(expected_np)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "other_column", [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])]\n )\n def test_cov_nullable_integer(self, other_column):\n # https://github.com/pandas-dev/pandas/issues/33803\n data = DataFrame({"a": pd.array([1, 2, None]), "b": other_column})\n result = data.cov()\n arr = np.array([[0.5, 0.5], [0.5, 1.0]])\n expected = DataFrame(arr, columns=["a", "b"], index=["a", "b"])\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("numeric_only", [True, False])\n def test_cov_numeric_only(self, numeric_only):\n # when dtypes of pandas series are different\n # then ndarray will have dtype=object,\n # so it need to be properly handled\n df = DataFrame({"a": [1, 0], "c": ["x", "y"]})\n expected = DataFrame(0.5, index=["a"], columns=["a"])\n if numeric_only:\n result = df.cov(numeric_only=numeric_only)\n tm.assert_frame_equal(result, expected)\n else:\n with pytest.raises(ValueError, match="could not convert string to float"):\n df.cov(numeric_only=numeric_only)\n\n\nclass TestDataFrameCorr:\n # DataFrame.corr(), as opposed to DataFrame.corrwith\n\n @pytest.mark.parametrize("method", ["pearson", "kendall", "spearman"])\n def test_corr_scipy_method(self, float_frame, method):\n pytest.importorskip("scipy")\n float_frame.loc[float_frame.index[:5], "A"] = np.nan\n float_frame.loc[float_frame.index[5:10], "B"] = np.nan\n float_frame.loc[float_frame.index[:10], "A"] = float_frame["A"][10:20].copy()\n\n correls = float_frame.corr(method=method)\n expected = float_frame["A"].corr(float_frame["C"], method=method)\n tm.assert_almost_equal(correls["A"]["C"], expected)\n\n # ---------------------------------------------------------------------\n\n def test_corr_non_numeric(self, float_string_frame):\n with pytest.raises(ValueError, match="could not convert string to float"):\n float_string_frame.corr()\n result = float_string_frame.corr(numeric_only=True)\n expected = float_string_frame.loc[:, ["A", "B", "C", "D"]].corr()\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"])\n def test_corr_nooverlap(self, meth):\n # nothing in common\n pytest.importorskip("scipy")\n df = DataFrame(\n {\n "A": [1, 1.5, 1, np.nan, np.nan, np.nan],\n "B": [np.nan, np.nan, np.nan, 1, 1.5, 1],\n "C": [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n }\n )\n rs = df.corr(meth)\n assert isna(rs.loc["A", "B"])\n assert isna(rs.loc["B", "A"])\n assert rs.loc["A", "A"] == 1\n assert rs.loc["B", "B"] == 1\n assert isna(rs.loc["C", "C"])\n\n @pytest.mark.parametrize("meth", ["pearson", "spearman"])\n def test_corr_constant(self, meth):\n # constant --> all NA\n df = DataFrame(\n {\n "A": [1, 1, 1, np.nan, np.nan, np.nan],\n "B": [np.nan, np.nan, np.nan, 1, 1, 1],\n }\n )\n rs = df.corr(meth)\n assert isna(rs.values).all()\n\n @pytest.mark.filterwarnings("ignore::RuntimeWarning")\n @pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"])\n def test_corr_int_and_boolean(self, meth):\n # when dtypes of pandas series are different\n # then ndarray will have dtype=object,\n # so it need to be properly handled\n pytest.importorskip("scipy")\n df = DataFrame({"a": [True, False], "b": [1, 0]})\n\n expected = DataFrame(np.ones((2, 2)), index=["a", "b"], columns=["a", "b"])\n result = df.corr(meth)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("method", ["cov", "corr"])\n def test_corr_cov_independent_index_column(self, method):\n # GH#14617\n df = DataFrame(\n np.random.default_rng(2).standard_normal(4 * 10).reshape(10, 4),\n columns=list("abcd"),\n )\n result = getattr(df, method)()\n assert result.index is not result.columns\n assert result.index.equals(result.columns)\n\n def test_corr_invalid_method(self):\n # GH#22298\n df = DataFrame(np.random.default_rng(2).normal(size=(10, 2)))\n msg = "method must be either 'pearson', 'spearman', 'kendall', or a callable, "\n with pytest.raises(ValueError, match=msg):\n df.corr(method="____")\n\n def test_corr_int(self):\n # dtypes other than float64 GH#1761\n df = DataFrame({"a": [1, 2, 3, 4], "b": [1, 2, 3, 4]})\n\n df.cov()\n df.corr()\n\n @pytest.mark.parametrize(\n "nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])]\n )\n @pytest.mark.parametrize(\n "other_column",\n [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]), np.array([1.0, 2.0, np.nan])],\n )\n @pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"])\n def test_corr_nullable_integer(self, nullable_column, other_column, method):\n # https://github.com/pandas-dev/pandas/issues/33803\n pytest.importorskip("scipy")\n data = DataFrame({"a": nullable_column, "b": other_column})\n result = data.corr(method=method)\n expected = DataFrame(np.ones((2, 2)), columns=["a", "b"], index=["a", "b"])\n tm.assert_frame_equal(result, expected)\n\n def test_corr_item_cache(self, using_copy_on_write, warn_copy_on_write):\n # Check that corr does not lead to incorrect entries in item_cache\n\n df = DataFrame({"A": range(10)})\n df["B"] = range(10)[::-1]\n\n ser = df["A"] # populate item_cache\n assert len(df._mgr.arrays) == 2 # i.e. 2 blocks\n\n _ = df.corr(numeric_only=True)\n\n if using_copy_on_write:\n ser.iloc[0] = 99\n assert df.loc[0, "A"] == 0\n else:\n # Check that the corr didn't break link between ser and df\n ser.values[0] = 99\n assert df.loc[0, "A"] == 99\n if not warn_copy_on_write:\n assert df["A"] is ser\n assert df.values[0, 0] == 99\n\n @pytest.mark.parametrize("length", [2, 20, 200, 2000])\n def test_corr_for_constant_columns(self, length):\n # GH: 37448\n df = DataFrame(length * [[0.4, 0.1]], columns=["A", "B"])\n result = df.corr()\n expected = DataFrame(\n {"A": [np.nan, np.nan], "B": [np.nan, np.nan]}, index=["A", "B"]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_calc_corr_small_numbers(self):\n # GH: 37452\n df = DataFrame(\n {"A": [1.0e-20, 2.0e-20, 3.0e-20], "B": [1.0e-20, 2.0e-20, 3.0e-20]}\n )\n result = df.corr()\n expected = DataFrame({"A": [1.0, 1.0], "B": [1.0, 1.0]}, index=["A", "B"])\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"])\n def test_corr_min_periods_greater_than_length(self, method):\n pytest.importorskip("scipy")\n df = DataFrame({"A": [1, 2], "B": [1, 2]})\n result = df.corr(method=method, min_periods=3)\n expected = DataFrame(\n {"A": [np.nan, np.nan], "B": [np.nan, np.nan]}, index=["A", "B"]\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"])\n @pytest.mark.parametrize("numeric_only", [True, False])\n def test_corr_numeric_only(self, meth, numeric_only):\n # when dtypes of pandas series are different\n # then ndarray will have dtype=object,\n # so it need to be properly handled\n pytest.importorskip("scipy")\n df = DataFrame({"a": [1, 0], "b": [1, 0], "c": ["x", "y"]})\n expected = DataFrame(np.ones((2, 2)), index=["a", "b"], columns=["a", "b"])\n if numeric_only:\n result = df.corr(meth, numeric_only=numeric_only)\n tm.assert_frame_equal(result, expected)\n else:\n with pytest.raises(ValueError, match="could not convert string to float"):\n df.corr(meth, numeric_only=numeric_only)\n\n\nclass TestDataFrameCorrWith:\n @pytest.mark.parametrize(\n "dtype",\n [\n "float64",\n "Float64",\n pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow")),\n ],\n )\n def test_corrwith(self, datetime_frame, dtype):\n datetime_frame = datetime_frame.astype(dtype)\n\n a = datetime_frame\n noise = Series(np.random.default_rng(2).standard_normal(len(a)), index=a.index)\n\n b = datetime_frame.add(noise, axis=0)\n\n # make sure order does not matter\n b = b.reindex(columns=b.columns[::-1], index=b.index[::-1][10:])\n del b["B"]\n\n colcorr = a.corrwith(b, axis=0)\n tm.assert_almost_equal(colcorr["A"], a["A"].corr(b["A"]))\n\n rowcorr = a.corrwith(b, axis=1)\n tm.assert_series_equal(rowcorr, a.T.corrwith(b.T, axis=0))\n\n dropped = a.corrwith(b, axis=0, drop=True)\n tm.assert_almost_equal(dropped["A"], a["A"].corr(b["A"]))\n assert "B" not in dropped\n\n dropped = a.corrwith(b, axis=1, drop=True)\n assert a.index[-1] not in dropped.index\n\n # non time-series data\n index = ["a", "b", "c", "d", "e"]\n columns = ["one", "two", "three", "four"]\n df1 = DataFrame(\n np.random.default_rng(2).standard_normal((5, 4)),\n index=index,\n columns=columns,\n )\n df2 = DataFrame(\n np.random.default_rng(2).standard_normal((4, 4)),\n index=index[:4],\n columns=columns,\n )\n correls = df1.corrwith(df2, axis=1)\n for row in index[:4]:\n tm.assert_almost_equal(correls[row], df1.loc[row].corr(df2.loc[row]))\n\n def test_corrwith_with_objects(self, using_infer_string):\n df1 = DataFrame(\n np.random.default_rng(2).standard_normal((10, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=date_range("2000-01-01", periods=10, freq="B"),\n )\n df2 = df1.copy()\n cols = ["A", "B", "C", "D"]\n\n df1["obj"] = "foo"\n df2["obj"] = "bar"\n\n if using_infer_string:\n msg = "Cannot perform reduction 'mean' with string dtype"\n with pytest.raises(TypeError, match=msg):\n df1.corrwith(df2)\n else:\n with pytest.raises(TypeError, match="Could not convert"):\n df1.corrwith(df2)\n result = df1.corrwith(df2, numeric_only=True)\n expected = df1.loc[:, cols].corrwith(df2.loc[:, cols])\n tm.assert_series_equal(result, expected)\n\n with pytest.raises(TypeError, match="unsupported operand type"):\n df1.corrwith(df2, axis=1)\n result = df1.corrwith(df2, axis=1, numeric_only=True)\n expected = df1.loc[:, cols].corrwith(df2.loc[:, cols], axis=1)\n tm.assert_series_equal(result, expected)\n\n def test_corrwith_series(self, datetime_frame):\n result = datetime_frame.corrwith(datetime_frame["A"])\n expected = datetime_frame.apply(datetime_frame["A"].corr)\n\n tm.assert_series_equal(result, expected)\n\n def test_corrwith_matches_corrcoef(self):\n df1 = DataFrame(np.arange(10000), columns=["a"])\n df2 = DataFrame(np.arange(10000) ** 2, columns=["a"])\n c1 = df1.corrwith(df2)["a"]\n c2 = np.corrcoef(df1["a"], df2["a"])[0][1]\n\n tm.assert_almost_equal(c1, c2)\n assert c1 < 1\n\n @pytest.mark.parametrize("numeric_only", [True, False])\n def test_corrwith_mixed_dtypes(self, numeric_only):\n # GH#18570\n df = DataFrame(\n {"a": [1, 4, 3, 2], "b": [4, 6, 7, 3], "c": ["a", "b", "c", "d"]}\n )\n s = Series([0, 6, 7, 3])\n if numeric_only:\n result = df.corrwith(s, numeric_only=numeric_only)\n corrs = [df["a"].corr(s), df["b"].corr(s)]\n expected = Series(data=corrs, index=["a", "b"])\n tm.assert_series_equal(result, expected)\n else:\n with pytest.raises(\n ValueError,\n match="could not convert string to float",\n ):\n df.corrwith(s, numeric_only=numeric_only)\n\n def test_corrwith_index_intersection(self):\n df1 = DataFrame(\n np.random.default_rng(2).random(size=(10, 2)), columns=["a", "b"]\n )\n df2 = DataFrame(\n np.random.default_rng(2).random(size=(10, 3)), columns=["a", "b", "c"]\n )\n\n result = df1.corrwith(df2, drop=True).index.sort_values()\n expected = df1.columns.intersection(df2.columns).sort_values()\n tm.assert_index_equal(result, expected)\n\n def test_corrwith_index_union(self):\n df1 = DataFrame(\n np.random.default_rng(2).random(size=(10, 2)), columns=["a", "b"]\n )\n df2 = DataFrame(\n np.random.default_rng(2).random(size=(10, 3)), columns=["a", "b", "c"]\n )\n\n result = df1.corrwith(df2, drop=False).index.sort_values()\n expected = df1.columns.union(df2.columns).sort_values()\n tm.assert_index_equal(result, expected)\n\n def test_corrwith_dup_cols(self):\n # GH#21925\n df1 = DataFrame(np.vstack([np.arange(10)] * 3).T)\n df2 = df1.copy()\n df2 = pd.concat((df2, df2[0]), axis=1)\n\n result = df1.corrwith(df2)\n expected = Series(np.ones(4), index=[0, 0, 1, 2])\n tm.assert_series_equal(result, expected)\n\n def test_corr_numerical_instabilities(self):\n # GH#45640\n df = DataFrame([[0.2, 0.4], [0.4, 0.2]])\n result = df.corr()\n expected = DataFrame({0: [1.0, -1.0], 1: [-1.0, 1.0]})\n tm.assert_frame_equal(result - 1, expected - 1, atol=1e-17)\n\n def test_corrwith_spearman(self):\n # GH#21925\n pytest.importorskip("scipy")\n df = DataFrame(np.random.default_rng(2).random(size=(100, 3)))\n result = df.corrwith(df**2, method="spearman")\n expected = Series(np.ones(len(result)))\n tm.assert_series_equal(result, expected)\n\n def test_corrwith_kendall(self):\n # GH#21925\n pytest.importorskip("scipy")\n df = DataFrame(np.random.default_rng(2).random(size=(100, 3)))\n result = df.corrwith(df**2, method="kendall")\n expected = Series(np.ones(len(result)))\n tm.assert_series_equal(result, expected)\n\n def test_corrwith_spearman_with_tied_data(self):\n # GH#48826\n pytest.importorskip("scipy")\n df1 = DataFrame(\n {\n "A": [1, np.nan, 7, 8],\n "B": [False, True, True, False],\n "C": [10, 4, 9, 3],\n }\n )\n df2 = df1[["B", "C"]]\n result = (df1 + 1).corrwith(df2.B, method="spearman")\n expected = Series([0.0, 1.0, 0.0], index=["A", "B", "C"])\n tm.assert_series_equal(result, expected)\n\n df_bool = DataFrame(\n {"A": [True, True, False, False], "B": [True, False, False, True]}\n )\n ser_bool = Series([True, True, False, True])\n result = df_bool.corrwith(ser_bool)\n expected = Series([0.57735, 0.57735], index=["A", "B"])\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_cov_corr.py
test_cov_corr.py
Python
17,875
0.95
0.085106
0.08933
react-lib
475
2024-12-12T02:07:00.465113
MIT
true
9b868070928a234a13462146689aa0a9
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n Series,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameDescribe:\n def test_describe_bool_in_mixed_frame(self):\n df = DataFrame(\n {\n "string_data": ["a", "b", "c", "d", "e"],\n "bool_data": [True, True, False, False, False],\n "int_data": [10, 20, 30, 40, 50],\n }\n )\n\n # Integer data are included in .describe() output,\n # Boolean and string data are not.\n result = df.describe()\n expected = DataFrame(\n {"int_data": [5, 30, df.int_data.std(), 10, 20, 30, 40, 50]},\n index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],\n )\n tm.assert_frame_equal(result, expected)\n\n # Top value is a boolean value that is False\n result = df.describe(include=["bool"])\n\n expected = DataFrame(\n {"bool_data": [5, 2, False, 3]}, index=["count", "unique", "top", "freq"]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_describe_empty_object(self):\n # GH#27183\n df = DataFrame({"A": [None, None]}, dtype=object)\n result = df.describe()\n expected = DataFrame(\n {"A": [0, 0, np.nan, np.nan]},\n dtype=object,\n index=["count", "unique", "top", "freq"],\n )\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:0].describe()\n tm.assert_frame_equal(result, expected)\n\n def test_describe_bool_frame(self):\n # GH#13891\n df = DataFrame(\n {\n "bool_data_1": [False, False, True, True],\n "bool_data_2": [False, True, True, True],\n }\n )\n result = df.describe()\n expected = DataFrame(\n {"bool_data_1": [4, 2, False, 2], "bool_data_2": [4, 2, True, 3]},\n index=["count", "unique", "top", "freq"],\n )\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame(\n {\n "bool_data": [False, False, True, True, False],\n "int_data": [0, 1, 2, 3, 4],\n }\n )\n result = df.describe()\n expected = DataFrame(\n {"int_data": [5, 2, df.int_data.std(), 0, 1, 2, 3, 4]},\n index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],\n )\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame(\n {"bool_data": [False, False, True, True], "str_data": ["a", "b", "c", "a"]}\n )\n result = df.describe()\n expected = DataFrame(\n {"bool_data": [4, 2, False, 2], "str_data": [4, 3, "a", 2]},\n index=["count", "unique", "top", "freq"],\n )\n tm.assert_frame_equal(result, expected)\n\n def test_describe_categorical(self):\n df = DataFrame({"value": np.random.default_rng(2).integers(0, 10000, 100)})\n labels = [f"{i} - {i + 499}" for i in range(0, 10000, 500)]\n cat_labels = Categorical(labels, labels)\n\n df = df.sort_values(by=["value"], ascending=True)\n df["value_group"] = pd.cut(\n df.value, range(0, 10500, 500), right=False, labels=cat_labels\n )\n cat = df\n\n # Categoricals should not show up together with numerical columns\n result = cat.describe()\n assert len(result.columns) == 1\n\n # In a frame, describe() for the cat should be the same as for string\n # arrays (count, unique, top, freq)\n\n cat = Categorical(\n ["a", "b", "b", "b"], categories=["a", "b", "c"], ordered=True\n )\n s = Series(cat)\n result = s.describe()\n expected = Series([4, 2, "b", 3], index=["count", "unique", "top", "freq"])\n tm.assert_series_equal(result, expected)\n\n cat = Series(Categorical(["a", "b", "c", "c"]))\n df3 = DataFrame({"cat": cat, "s": ["a", "b", "c", "c"]})\n result = df3.describe()\n tm.assert_numpy_array_equal(result["cat"].values, result["s"].values)\n\n def test_describe_empty_categorical_column(self):\n # GH#26397\n # Ensure the index of an empty categorical DataFrame column\n # also contains (count, unique, top, freq)\n df = DataFrame({"empty_col": Categorical([])})\n result = df.describe()\n expected = DataFrame(\n {"empty_col": [0, 0, np.nan, np.nan]},\n index=["count", "unique", "top", "freq"],\n dtype="object",\n )\n tm.assert_frame_equal(result, expected)\n # ensure NaN, not None\n assert np.isnan(result.iloc[2, 0])\n assert np.isnan(result.iloc[3, 0])\n\n def test_describe_categorical_columns(self):\n # GH#11558\n columns = pd.CategoricalIndex(["int1", "int2", "obj"], ordered=True, name="XXX")\n df = DataFrame(\n {\n "int1": [10, 20, 30, 40, 50],\n "int2": [10, 20, 30, 40, 50],\n "obj": ["A", 0, None, "X", 1],\n },\n columns=columns,\n )\n result = df.describe()\n\n exp_columns = pd.CategoricalIndex(\n ["int1", "int2"],\n categories=["int1", "int2", "obj"],\n ordered=True,\n name="XXX",\n )\n expected = DataFrame(\n {\n "int1": [5, 30, df.int1.std(), 10, 20, 30, 40, 50],\n "int2": [5, 30, df.int2.std(), 10, 20, 30, 40, 50],\n },\n index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],\n columns=exp_columns,\n )\n\n tm.assert_frame_equal(result, expected)\n tm.assert_categorical_equal(result.columns.values, expected.columns.values)\n\n def test_describe_datetime_columns(self):\n columns = pd.DatetimeIndex(\n ["2011-01-01", "2011-02-01", "2011-03-01"],\n freq="MS",\n tz="US/Eastern",\n name="XXX",\n )\n df = DataFrame(\n {\n 0: [10, 20, 30, 40, 50],\n 1: [10, 20, 30, 40, 50],\n 2: ["A", 0, None, "X", 1],\n }\n )\n df.columns = columns\n result = df.describe()\n\n exp_columns = pd.DatetimeIndex(\n ["2011-01-01", "2011-02-01"], freq="MS", tz="US/Eastern", name="XXX"\n )\n expected = DataFrame(\n {\n 0: [5, 30, df.iloc[:, 0].std(), 10, 20, 30, 40, 50],\n 1: [5, 30, df.iloc[:, 1].std(), 10, 20, 30, 40, 50],\n },\n index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],\n )\n expected.columns = exp_columns\n tm.assert_frame_equal(result, expected)\n assert result.columns.freq == "MS"\n assert result.columns.tz == expected.columns.tz\n\n def test_describe_timedelta_values(self):\n # GH#6145\n t1 = pd.timedelta_range("1 days", freq="D", periods=5)\n t2 = pd.timedelta_range("1 hours", freq="h", periods=5)\n df = DataFrame({"t1": t1, "t2": t2})\n\n expected = DataFrame(\n {\n "t1": [\n 5,\n pd.Timedelta("3 days"),\n df.iloc[:, 0].std(),\n pd.Timedelta("1 days"),\n pd.Timedelta("2 days"),\n pd.Timedelta("3 days"),\n pd.Timedelta("4 days"),\n pd.Timedelta("5 days"),\n ],\n "t2": [\n 5,\n pd.Timedelta("3 hours"),\n df.iloc[:, 1].std(),\n pd.Timedelta("1 hours"),\n pd.Timedelta("2 hours"),\n pd.Timedelta("3 hours"),\n pd.Timedelta("4 hours"),\n pd.Timedelta("5 hours"),\n ],\n },\n index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],\n )\n\n result = df.describe()\n tm.assert_frame_equal(result, expected)\n\n exp_repr = (\n " t1 t2\n"\n "count 5 5\n"\n "mean 3 days 00:00:00 0 days 03:00:00\n"\n "std 1 days 13:56:50.394919273 0 days 01:34:52.099788303\n"\n "min 1 days 00:00:00 0 days 01:00:00\n"\n "25% 2 days 00:00:00 0 days 02:00:00\n"\n "50% 3 days 00:00:00 0 days 03:00:00\n"\n "75% 4 days 00:00:00 0 days 04:00:00\n"\n "max 5 days 00:00:00 0 days 05:00:00"\n )\n assert repr(result) == exp_repr\n\n def test_describe_tz_values(self, tz_naive_fixture):\n # GH#21332\n tz = tz_naive_fixture\n s1 = Series(range(5))\n start = Timestamp(2018, 1, 1)\n end = Timestamp(2018, 1, 5)\n s2 = Series(date_range(start, end, tz=tz))\n df = DataFrame({"s1": s1, "s2": s2})\n\n expected = DataFrame(\n {\n "s1": [5, 2, 0, 1, 2, 3, 4, 1.581139],\n "s2": [\n 5,\n Timestamp(2018, 1, 3).tz_localize(tz),\n start.tz_localize(tz),\n s2[1],\n s2[2],\n s2[3],\n end.tz_localize(tz),\n np.nan,\n ],\n },\n index=["count", "mean", "min", "25%", "50%", "75%", "max", "std"],\n )\n result = df.describe(include="all")\n tm.assert_frame_equal(result, expected)\n\n def test_datetime_is_numeric_includes_datetime(self):\n df = DataFrame({"a": date_range("2012", periods=3), "b": [1, 2, 3]})\n result = df.describe()\n expected = DataFrame(\n {\n "a": [\n 3,\n Timestamp("2012-01-02"),\n Timestamp("2012-01-01"),\n Timestamp("2012-01-01T12:00:00"),\n Timestamp("2012-01-02"),\n Timestamp("2012-01-02T12:00:00"),\n Timestamp("2012-01-03"),\n np.nan,\n ],\n "b": [3, 2, 1, 1.5, 2, 2.5, 3, 1],\n },\n index=["count", "mean", "min", "25%", "50%", "75%", "max", "std"],\n )\n tm.assert_frame_equal(result, expected)\n\n def test_describe_tz_values2(self):\n tz = "CET"\n s1 = Series(range(5))\n start = Timestamp(2018, 1, 1)\n end = Timestamp(2018, 1, 5)\n s2 = Series(date_range(start, end, tz=tz))\n df = DataFrame({"s1": s1, "s2": s2})\n\n s1_ = s1.describe()\n s2_ = s2.describe()\n idx = [\n "count",\n "mean",\n "min",\n "25%",\n "50%",\n "75%",\n "max",\n "std",\n ]\n expected = pd.concat([s1_, s2_], axis=1, keys=["s1", "s2"]).reindex(\n idx, copy=False\n )\n\n result = df.describe(include="all")\n tm.assert_frame_equal(result, expected)\n\n def test_describe_percentiles_integer_idx(self):\n # GH#26660\n df = DataFrame({"x": [1]})\n pct = np.linspace(0, 1, 10 + 1)\n result = df.describe(percentiles=pct)\n\n expected = DataFrame(\n {"x": [1.0, 1.0, np.nan, 1.0, *(1.0 for _ in pct), 1.0]},\n index=[\n "count",\n "mean",\n "std",\n "min",\n "0%",\n "10%",\n "20%",\n "30%",\n "40%",\n "50%",\n "60%",\n "70%",\n "80%",\n "90%",\n "100%",\n "max",\n ],\n )\n tm.assert_frame_equal(result, expected)\n\n def test_describe_does_not_raise_error_for_dictlike_elements(self):\n # GH#32409\n df = DataFrame([{"test": {"a": "1"}}, {"test": {"a": "2"}}])\n expected = DataFrame(\n {"test": [2, 2, {"a": "1"}, 1]}, index=["count", "unique", "top", "freq"]\n )\n result = df.describe()\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("exclude", ["x", "y", ["x", "y"], ["x", "z"]])\n def test_describe_when_include_all_exclude_not_allowed(self, exclude):\n """\n When include is 'all', then setting exclude != None is not allowed.\n """\n df = DataFrame({"x": [1], "y": [2], "z": [3]})\n msg = "exclude must be None when include is 'all'"\n with pytest.raises(ValueError, match=msg):\n df.describe(include="all", exclude=exclude)\n\n def test_describe_with_duplicate_columns(self):\n df = DataFrame(\n [[1, 1, 1], [2, 2, 2], [3, 3, 3]],\n columns=["bar", "a", "a"],\n dtype="float64",\n )\n result = df.describe()\n ser = df.iloc[:, 0].describe()\n expected = pd.concat([ser, ser, ser], keys=df.columns, axis=1)\n tm.assert_frame_equal(result, expected)\n\n def test_ea_with_na(self, any_numeric_ea_dtype):\n # GH#48778\n\n df = DataFrame({"a": [1, pd.NA, pd.NA], "b": pd.NA}, dtype=any_numeric_ea_dtype)\n result = df.describe()\n expected = DataFrame(\n {"a": [1.0, 1.0, pd.NA] + [1.0] * 5, "b": [0.0] + [pd.NA] * 7},\n index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],\n dtype="Float64",\n )\n tm.assert_frame_equal(result, expected)\n\n def test_describe_exclude_pa_dtype(self):\n # GH#52570\n pa = pytest.importorskip("pyarrow")\n df = DataFrame(\n {\n "a": Series([1, 2, 3], dtype=pd.ArrowDtype(pa.int8())),\n "b": Series([1, 2, 3], dtype=pd.ArrowDtype(pa.int16())),\n "c": Series([1, 2, 3], dtype=pd.ArrowDtype(pa.int32())),\n }\n )\n result = df.describe(\n include=pd.ArrowDtype(pa.int8()), exclude=pd.ArrowDtype(pa.int32())\n )\n expected = DataFrame(\n {"a": [3, 2, 1, 1, 1.5, 2, 2.5, 3]},\n index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],\n dtype=pd.ArrowDtype(pa.float64()),\n )\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_describe.py
test_describe.py
Python
14,500
0.95
0.052758
0.050532
vue-tools
870
2024-04-15T08:36:08.767030
BSD-3-Clause
true
d59e1b38132a960251f37221f7d917dc
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Series,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameDiff:\n def test_diff_requires_integer(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((2, 2)))\n with pytest.raises(ValueError, match="periods must be an integer"):\n df.diff(1.5)\n\n # GH#44572 np.int64 is accepted\n @pytest.mark.parametrize("num", [1, np.int64(1)])\n def test_diff(self, datetime_frame, num):\n df = datetime_frame\n the_diff = df.diff(num)\n\n expected = df["A"] - df["A"].shift(num)\n tm.assert_series_equal(the_diff["A"], expected)\n\n def test_diff_int_dtype(self):\n # int dtype\n a = 10_000_000_000_000_000\n b = a + 1\n ser = Series([a, b])\n\n rs = DataFrame({"s": ser}).diff()\n assert rs.s[1] == 1\n\n def test_diff_mixed_numeric(self, datetime_frame):\n # mixed numeric\n tf = datetime_frame.astype("float32")\n the_diff = tf.diff(1)\n tm.assert_series_equal(the_diff["A"], tf["A"] - tf["A"].shift(1))\n\n def test_diff_axis1_nonconsolidated(self):\n # GH#10907\n df = DataFrame({"y": Series([2]), "z": Series([3])})\n df.insert(0, "x", 1)\n result = df.diff(axis=1)\n expected = DataFrame({"x": np.nan, "y": Series(1), "z": Series(1)})\n tm.assert_frame_equal(result, expected)\n\n def test_diff_timedelta64_with_nat(self):\n # GH#32441\n arr = np.arange(6).reshape(3, 2).astype("timedelta64[ns]")\n arr[:, 0] = np.timedelta64("NaT", "ns")\n\n df = DataFrame(arr)\n result = df.diff(1, axis=0)\n\n expected = DataFrame({0: df[0], 1: [pd.NaT, pd.Timedelta(2), pd.Timedelta(2)]})\n tm.assert_equal(result, expected)\n\n result = df.diff(0)\n expected = df - df\n assert expected[0].isna().all()\n tm.assert_equal(result, expected)\n\n result = df.diff(-1, axis=1)\n expected = df * np.nan\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize("tz", [None, "UTC"])\n def test_diff_datetime_axis0_with_nat(self, tz, unit):\n # GH#32441\n dti = pd.DatetimeIndex(["NaT", "2019-01-01", "2019-01-02"], tz=tz).as_unit(unit)\n ser = Series(dti)\n\n df = ser.to_frame()\n\n result = df.diff()\n ex_index = pd.TimedeltaIndex([pd.NaT, pd.NaT, pd.Timedelta(days=1)]).as_unit(\n unit\n )\n expected = Series(ex_index).to_frame()\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("tz", [None, "UTC"])\n def test_diff_datetime_with_nat_zero_periods(self, tz):\n # diff on NaT values should give NaT, not timedelta64(0)\n dti = date_range("2016-01-01", periods=4, tz=tz)\n ser = Series(dti)\n df = ser.to_frame().copy()\n\n df[1] = ser.copy()\n\n df.iloc[:, 0] = pd.NaT\n\n expected = df - df\n assert expected[0].isna().all()\n\n result = df.diff(0, axis=0)\n tm.assert_frame_equal(result, expected)\n\n result = df.diff(0, axis=1)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("tz", [None, "UTC"])\n def test_diff_datetime_axis0(self, tz):\n # GH#18578\n df = DataFrame(\n {\n 0: date_range("2010", freq="D", periods=2, tz=tz),\n 1: date_range("2010", freq="D", periods=2, tz=tz),\n }\n )\n\n result = df.diff(axis=0)\n expected = DataFrame(\n {\n 0: pd.TimedeltaIndex(["NaT", "1 days"]),\n 1: pd.TimedeltaIndex(["NaT", "1 days"]),\n }\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("tz", [None, "UTC"])\n def test_diff_datetime_axis1(self, tz):\n # GH#18578\n df = DataFrame(\n {\n 0: date_range("2010", freq="D", periods=2, tz=tz),\n 1: date_range("2010", freq="D", periods=2, tz=tz),\n }\n )\n\n result = df.diff(axis=1)\n expected = DataFrame(\n {\n 0: pd.TimedeltaIndex(["NaT", "NaT"]),\n 1: pd.TimedeltaIndex(["0 days", "0 days"]),\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_diff_timedelta(self, unit):\n # GH#4533\n df = DataFrame(\n {\n "time": [Timestamp("20130101 9:01"), Timestamp("20130101 9:02")],\n "value": [1.0, 2.0],\n }\n )\n df["time"] = df["time"].dt.as_unit(unit)\n\n res = df.diff()\n exp = DataFrame(\n [[pd.NaT, np.nan], [pd.Timedelta("00:01:00"), 1]], columns=["time", "value"]\n )\n exp["time"] = exp["time"].dt.as_unit(unit)\n tm.assert_frame_equal(res, exp)\n\n def test_diff_mixed_dtype(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))\n df["A"] = np.array([1, 2, 3, 4, 5], dtype=object)\n\n result = df.diff()\n assert result[0].dtype == np.float64\n\n def test_diff_neg_n(self, datetime_frame):\n rs = datetime_frame.diff(-1)\n xp = datetime_frame - datetime_frame.shift(-1)\n tm.assert_frame_equal(rs, xp)\n\n def test_diff_float_n(self, datetime_frame):\n rs = datetime_frame.diff(1.0)\n xp = datetime_frame.diff(1)\n tm.assert_frame_equal(rs, xp)\n\n def test_diff_axis(self):\n # GH#9727\n df = DataFrame([[1.0, 2.0], [3.0, 4.0]])\n tm.assert_frame_equal(\n df.diff(axis=1), DataFrame([[np.nan, 1.0], [np.nan, 1.0]])\n )\n tm.assert_frame_equal(\n df.diff(axis=0), DataFrame([[np.nan, np.nan], [2.0, 2.0]])\n )\n\n def test_diff_period(self):\n # GH#32995 Don't pass an incorrect axis\n pi = date_range("2016-01-01", periods=3).to_period("D")\n df = DataFrame({"A": pi})\n\n result = df.diff(1, axis=1)\n\n expected = (df - pd.NaT).astype(object)\n tm.assert_frame_equal(result, expected)\n\n def test_diff_axis1_mixed_dtypes(self):\n # GH#32995 operate column-wise when we have mixed dtypes and axis=1\n df = DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})\n\n expected = DataFrame({"A": [np.nan, np.nan, np.nan], "B": df["B"] / 2})\n\n result = df.diff(axis=1)\n tm.assert_frame_equal(result, expected)\n\n # GH#21437 mixed-float-dtypes\n df = DataFrame(\n {"a": np.arange(3, dtype="float32"), "b": np.arange(3, dtype="float64")}\n )\n result = df.diff(axis=1)\n expected = DataFrame({"a": df["a"] * np.nan, "b": df["b"] * 0})\n tm.assert_frame_equal(result, expected)\n\n def test_diff_axis1_mixed_dtypes_large_periods(self):\n # GH#32995 operate column-wise when we have mixed dtypes and axis=1\n df = DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})\n\n expected = df * np.nan\n\n result = df.diff(axis=1, periods=3)\n tm.assert_frame_equal(result, expected)\n\n def test_diff_axis1_mixed_dtypes_negative_periods(self):\n # GH#32995 operate column-wise when we have mixed dtypes and axis=1\n df = DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})\n\n expected = DataFrame({"A": -1.0 * df["A"], "B": df["B"] * np.nan})\n\n result = df.diff(axis=1, periods=-1)\n tm.assert_frame_equal(result, expected)\n\n def test_diff_sparse(self):\n # GH#28813 .diff() should work for sparse dataframes as well\n sparse_df = DataFrame([[0, 1], [1, 0]], dtype="Sparse[int]")\n\n result = sparse_df.diff()\n expected = DataFrame(\n [[np.nan, np.nan], [1.0, -1.0]], dtype=pd.SparseDtype("float", 0.0)\n )\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "axis,expected",\n [\n (\n 0,\n DataFrame(\n {\n "a": [np.nan, 0, 1, 0, np.nan, np.nan, np.nan, 0],\n "b": [np.nan, 1, np.nan, np.nan, -2, 1, np.nan, np.nan],\n "c": np.repeat(np.nan, 8),\n "d": [np.nan, 3, 5, 7, 9, 11, 13, 15],\n },\n dtype="Int64",\n ),\n ),\n (\n 1,\n DataFrame(\n {\n "a": np.repeat(np.nan, 8),\n "b": [0, 1, np.nan, 1, np.nan, np.nan, np.nan, 0],\n "c": np.repeat(np.nan, 8),\n "d": np.repeat(np.nan, 8),\n },\n dtype="Int64",\n ),\n ),\n ],\n )\n def test_diff_integer_na(self, axis, expected):\n # GH#24171 IntegerNA Support for DataFrame.diff()\n df = DataFrame(\n {\n "a": np.repeat([0, 1, np.nan, 2], 2),\n "b": np.tile([0, 1, np.nan, 2], 2),\n "c": np.repeat(np.nan, 8),\n "d": np.arange(1, 9) ** 2,\n },\n dtype="Int64",\n )\n\n # Test case for default behaviour of diff\n result = df.diff(axis=axis)\n tm.assert_frame_equal(result, expected)\n\n def test_diff_readonly(self):\n # https://github.com/pandas-dev/pandas/issues/35559\n arr = np.random.default_rng(2).standard_normal((5, 2))\n arr.flags.writeable = False\n df = DataFrame(arr)\n result = df.diff()\n expected = DataFrame(np.array(df)).diff()\n tm.assert_frame_equal(result, expected)\n\n def test_diff_all_int_dtype(self, any_int_numpy_dtype):\n # GH 14773\n df = DataFrame(range(5))\n df = df.astype(any_int_numpy_dtype)\n result = df.diff()\n expected_dtype = (\n "float32" if any_int_numpy_dtype in ("int8", "int16") else "float64"\n )\n expected = DataFrame([np.nan, 1.0, 1.0, 1.0, 1.0], dtype=expected_dtype)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_diff.py
test_diff.py
Python
10,099
0.95
0.090909
0.082677
awesome-app
490
2025-06-16T04:25:42.153445
GPL-3.0
true
9b58f92e508634014d9d6b95f3865758
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass DotSharedTests:\n @pytest.fixture\n def obj(self):\n raise NotImplementedError\n\n @pytest.fixture\n def other(self) -> DataFrame:\n """\n other is a DataFrame that is indexed so that obj.dot(other) is valid\n """\n raise NotImplementedError\n\n @pytest.fixture\n def expected(self, obj, other) -> DataFrame:\n """\n The expected result of obj.dot(other)\n """\n raise NotImplementedError\n\n @classmethod\n def reduced_dim_assert(cls, result, expected):\n """\n Assertion about results with 1 fewer dimension that self.obj\n """\n raise NotImplementedError\n\n def test_dot_equiv_values_dot(self, obj, other, expected):\n # `expected` is constructed from obj.values.dot(other.values)\n result = obj.dot(other)\n tm.assert_equal(result, expected)\n\n def test_dot_2d_ndarray(self, obj, other, expected):\n # Check ndarray argument; in this case we get matching values,\n # but index/columns may not match\n result = obj.dot(other.values)\n assert np.all(result == expected.values)\n\n def test_dot_1d_ndarray(self, obj, expected):\n # can pass correct-length array\n row = obj.iloc[0] if obj.ndim == 2 else obj\n\n result = obj.dot(row.values)\n expected = obj.dot(row)\n self.reduced_dim_assert(result, expected)\n\n def test_dot_series(self, obj, other, expected):\n # Check series argument\n result = obj.dot(other["1"])\n self.reduced_dim_assert(result, expected["1"])\n\n def test_dot_series_alignment(self, obj, other, expected):\n result = obj.dot(other.iloc[::-1]["1"])\n self.reduced_dim_assert(result, expected["1"])\n\n def test_dot_aligns(self, obj, other, expected):\n # Check index alignment\n other2 = other.iloc[::-1]\n result = obj.dot(other2)\n tm.assert_equal(result, expected)\n\n def test_dot_shape_mismatch(self, obj):\n msg = "Dot product shape mismatch"\n # exception raised is of type Exception\n with pytest.raises(Exception, match=msg):\n obj.dot(obj.values[:3])\n\n def test_dot_misaligned(self, obj, other):\n msg = "matrices are not aligned"\n with pytest.raises(ValueError, match=msg):\n obj.dot(other.T)\n\n\nclass TestSeriesDot(DotSharedTests):\n @pytest.fixture\n def obj(self):\n return Series(\n np.random.default_rng(2).standard_normal(4), index=["p", "q", "r", "s"]\n )\n\n @pytest.fixture\n def other(self):\n return DataFrame(\n np.random.default_rng(2).standard_normal((3, 4)),\n index=["1", "2", "3"],\n columns=["p", "q", "r", "s"],\n ).T\n\n @pytest.fixture\n def expected(self, obj, other):\n return Series(np.dot(obj.values, other.values), index=other.columns)\n\n @classmethod\n def reduced_dim_assert(cls, result, expected):\n """\n Assertion about results with 1 fewer dimension that self.obj\n """\n tm.assert_almost_equal(result, expected)\n\n\nclass TestDataFrameDot(DotSharedTests):\n @pytest.fixture\n def obj(self):\n return DataFrame(\n np.random.default_rng(2).standard_normal((3, 4)),\n index=["a", "b", "c"],\n columns=["p", "q", "r", "s"],\n )\n\n @pytest.fixture\n def other(self):\n return DataFrame(\n np.random.default_rng(2).standard_normal((4, 2)),\n index=["p", "q", "r", "s"],\n columns=["1", "2"],\n )\n\n @pytest.fixture\n def expected(self, obj, other):\n return DataFrame(\n np.dot(obj.values, other.values), index=obj.index, columns=other.columns\n )\n\n @classmethod\n def reduced_dim_assert(cls, result, expected):\n """\n Assertion about results with 1 fewer dimension that self.obj\n """\n tm.assert_series_equal(result, expected, check_names=False)\n assert result.name is None\n\n\n@pytest.mark.parametrize(\n "dtype,exp_dtype",\n [("Float32", "Float64"), ("Int16", "Int32"), ("float[pyarrow]", "double[pyarrow]")],\n)\ndef test_arrow_dtype(dtype, exp_dtype):\n pytest.importorskip("pyarrow")\n\n cols = ["a", "b"]\n df_a = DataFrame([[1, 2], [3, 4], [5, 6]], columns=cols, dtype="int32")\n df_b = DataFrame([[1, 0], [0, 1]], index=cols, dtype=dtype)\n result = df_a.dot(df_b)\n expected = DataFrame([[1, 2], [3, 4], [5, 6]], dtype=exp_dtype)\n\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_dot.py
test_dot.py
Python
4,623
0.95
0.16129
0.055556
awesome-app
717
2023-12-24T04:31:28.769354
BSD-3-Clause
true
f31252db2afc973921cf850dc1a9e586
import re\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import PerformanceWarning\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n DatetimeIndex,\n Index,\n MultiIndex,\n Series,\n Timestamp,\n)\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize(\n "msg,labels,level",\n [\n (r"labels \[4\] not found in level", 4, "a"),\n (r"labels \[7\] not found in level", 7, "b"),\n ],\n)\ndef test_drop_raise_exception_if_labels_not_in_level(msg, labels, level):\n # GH 8594\n mi = MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"])\n s = Series([10, 20, 30], index=mi)\n df = DataFrame([10, 20, 30], index=mi)\n\n with pytest.raises(KeyError, match=msg):\n s.drop(labels, level=level)\n with pytest.raises(KeyError, match=msg):\n df.drop(labels, level=level)\n\n\n@pytest.mark.parametrize("labels,level", [(4, "a"), (7, "b")])\ndef test_drop_errors_ignore(labels, level):\n # GH 8594\n mi = MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"])\n s = Series([10, 20, 30], index=mi)\n df = DataFrame([10, 20, 30], index=mi)\n\n expected_s = s.drop(labels, level=level, errors="ignore")\n tm.assert_series_equal(s, expected_s)\n\n expected_df = df.drop(labels, level=level, errors="ignore")\n tm.assert_frame_equal(df, expected_df)\n\n\ndef test_drop_with_non_unique_datetime_index_and_invalid_keys():\n # GH 30399\n\n # define dataframe with unique datetime index\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)),\n columns=["a", "b", "c"],\n index=pd.date_range("2012", freq="h", periods=5),\n )\n # create dataframe with non-unique datetime index\n df = df.iloc[[0, 2, 2, 3]].copy()\n\n with pytest.raises(KeyError, match="not found in axis"):\n df.drop(["a", "b"]) # Dropping with labels not exist in the index\n\n\nclass TestDataFrameDrop:\n def test_drop_names(self):\n df = DataFrame(\n [[1, 2, 3], [3, 4, 5], [5, 6, 7]],\n index=["a", "b", "c"],\n columns=["d", "e", "f"],\n )\n df.index.name, df.columns.name = "first", "second"\n df_dropped_b = df.drop("b")\n df_dropped_e = df.drop("e", axis=1)\n df_inplace_b, df_inplace_e = df.copy(), df.copy()\n return_value = df_inplace_b.drop("b", inplace=True)\n assert return_value is None\n return_value = df_inplace_e.drop("e", axis=1, inplace=True)\n assert return_value is None\n for obj in (df_dropped_b, df_dropped_e, df_inplace_b, df_inplace_e):\n assert obj.index.name == "first"\n assert obj.columns.name == "second"\n assert list(df.columns) == ["d", "e", "f"]\n\n msg = r"\['g'\] not found in axis"\n with pytest.raises(KeyError, match=msg):\n df.drop(["g"])\n with pytest.raises(KeyError, match=msg):\n df.drop(["g"], axis=1)\n\n # errors = 'ignore'\n dropped = df.drop(["g"], errors="ignore")\n expected = Index(["a", "b", "c"], name="first")\n tm.assert_index_equal(dropped.index, expected)\n\n dropped = df.drop(["b", "g"], errors="ignore")\n expected = Index(["a", "c"], name="first")\n tm.assert_index_equal(dropped.index, expected)\n\n dropped = df.drop(["g"], axis=1, errors="ignore")\n expected = Index(["d", "e", "f"], name="second")\n tm.assert_index_equal(dropped.columns, expected)\n\n dropped = df.drop(["d", "g"], axis=1, errors="ignore")\n expected = Index(["e", "f"], name="second")\n tm.assert_index_equal(dropped.columns, expected)\n\n # GH 16398\n dropped = df.drop([], errors="ignore")\n expected = Index(["a", "b", "c"], name="first")\n tm.assert_index_equal(dropped.index, expected)\n\n def test_drop(self):\n simple = DataFrame({"A": [1, 2, 3, 4], "B": [0, 1, 2, 3]})\n tm.assert_frame_equal(simple.drop("A", axis=1), simple[["B"]])\n tm.assert_frame_equal(simple.drop(["A", "B"], axis="columns"), simple[[]])\n tm.assert_frame_equal(simple.drop([0, 1, 3], axis=0), simple.loc[[2], :])\n tm.assert_frame_equal(simple.drop([0, 3], axis="index"), simple.loc[[1, 2], :])\n\n with pytest.raises(KeyError, match=r"\[5\] not found in axis"):\n simple.drop(5)\n with pytest.raises(KeyError, match=r"\['C'\] not found in axis"):\n simple.drop("C", axis=1)\n with pytest.raises(KeyError, match=r"\[5\] not found in axis"):\n simple.drop([1, 5])\n with pytest.raises(KeyError, match=r"\['C'\] not found in axis"):\n simple.drop(["A", "C"], axis=1)\n\n # GH 42881\n with pytest.raises(KeyError, match=r"\['C', 'D', 'F'\] not found in axis"):\n simple.drop(["C", "D", "F"], axis=1)\n\n # errors = 'ignore'\n tm.assert_frame_equal(simple.drop(5, errors="ignore"), simple)\n tm.assert_frame_equal(\n simple.drop([0, 5], errors="ignore"), simple.loc[[1, 2, 3], :]\n )\n tm.assert_frame_equal(simple.drop("C", axis=1, errors="ignore"), simple)\n tm.assert_frame_equal(\n simple.drop(["A", "C"], axis=1, errors="ignore"), simple[["B"]]\n )\n\n # non-unique - wheee!\n nu_df = DataFrame(\n list(zip(range(3), range(-3, 1), list("abc"))), columns=["a", "a", "b"]\n )\n tm.assert_frame_equal(nu_df.drop("a", axis=1), nu_df[["b"]])\n tm.assert_frame_equal(nu_df.drop("b", axis="columns"), nu_df["a"])\n tm.assert_frame_equal(nu_df.drop([]), nu_df) # GH 16398\n\n nu_df = nu_df.set_index(Index(["X", "Y", "X"]))\n nu_df.columns = list("abc")\n tm.assert_frame_equal(nu_df.drop("X", axis="rows"), nu_df.loc[["Y"], :])\n tm.assert_frame_equal(nu_df.drop(["X", "Y"], axis=0), nu_df.loc[[], :])\n\n # inplace cache issue\n # GH#5628\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 3)), columns=list("abc")\n )\n expected = df[~(df.b > 0)]\n return_value = df.drop(labels=df[df.b > 0].index, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(df, expected)\n\n def test_drop_multiindex_not_lexsorted(self):\n # GH#11640\n\n # define the lexsorted version\n lexsorted_mi = MultiIndex.from_tuples(\n [("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"]\n )\n lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi)\n assert lexsorted_df.columns._is_lexsorted()\n\n # define the non-lexsorted version\n not_lexsorted_df = DataFrame(\n columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]]\n )\n not_lexsorted_df = not_lexsorted_df.pivot_table(\n index="a", columns=["b", "c"], values="d"\n )\n not_lexsorted_df = not_lexsorted_df.reset_index()\n assert not not_lexsorted_df.columns._is_lexsorted()\n\n expected = lexsorted_df.drop("a", axis=1).astype(float)\n with tm.assert_produces_warning(PerformanceWarning):\n result = not_lexsorted_df.drop("a", axis=1)\n\n tm.assert_frame_equal(result, expected)\n\n def test_drop_api_equivalence(self):\n # equivalence of the labels/axis and index/columns API's (GH#12392)\n df = DataFrame(\n [[1, 2, 3], [3, 4, 5], [5, 6, 7]],\n index=["a", "b", "c"],\n columns=["d", "e", "f"],\n )\n\n res1 = df.drop("a")\n res2 = df.drop(index="a")\n tm.assert_frame_equal(res1, res2)\n\n res1 = df.drop("d", axis=1)\n res2 = df.drop(columns="d")\n tm.assert_frame_equal(res1, res2)\n\n res1 = df.drop(labels="e", axis=1)\n res2 = df.drop(columns="e")\n tm.assert_frame_equal(res1, res2)\n\n res1 = df.drop(["a"], axis=0)\n res2 = df.drop(index=["a"])\n tm.assert_frame_equal(res1, res2)\n\n res1 = df.drop(["a"], axis=0).drop(["d"], axis=1)\n res2 = df.drop(index=["a"], columns=["d"])\n tm.assert_frame_equal(res1, res2)\n\n msg = "Cannot specify both 'labels' and 'index'/'columns'"\n with pytest.raises(ValueError, match=msg):\n df.drop(labels="a", index="b")\n\n with pytest.raises(ValueError, match=msg):\n df.drop(labels="a", columns="b")\n\n msg = "Need to specify at least one of 'labels', 'index' or 'columns'"\n with pytest.raises(ValueError, match=msg):\n df.drop(axis=1)\n\n data = [[1, 2, 3], [1, 2, 3]]\n\n @pytest.mark.parametrize(\n "actual",\n [\n DataFrame(data=data, index=["a", "a"]),\n DataFrame(data=data, index=["a", "b"]),\n DataFrame(data=data, index=["a", "b"]).set_index([0, 1]),\n DataFrame(data=data, index=["a", "a"]).set_index([0, 1]),\n ],\n )\n def test_raise_on_drop_duplicate_index(self, actual):\n # GH#19186\n level = 0 if isinstance(actual.index, MultiIndex) else None\n msg = re.escape("\"['c'] not found in axis\"")\n with pytest.raises(KeyError, match=msg):\n actual.drop("c", level=level, axis=0)\n with pytest.raises(KeyError, match=msg):\n actual.T.drop("c", level=level, axis=1)\n expected_no_err = actual.drop("c", axis=0, level=level, errors="ignore")\n tm.assert_frame_equal(expected_no_err, actual)\n expected_no_err = actual.T.drop("c", axis=1, level=level, errors="ignore")\n tm.assert_frame_equal(expected_no_err.T, actual)\n\n @pytest.mark.parametrize("index", [[1, 2, 3], [1, 1, 2]])\n @pytest.mark.parametrize("drop_labels", [[], [1], [2]])\n def test_drop_empty_list(self, index, drop_labels):\n # GH#21494\n expected_index = [i for i in index if i not in drop_labels]\n frame = DataFrame(index=index).drop(drop_labels)\n tm.assert_frame_equal(frame, DataFrame(index=expected_index))\n\n @pytest.mark.parametrize("index", [[1, 2, 3], [1, 2, 2]])\n @pytest.mark.parametrize("drop_labels", [[1, 4], [4, 5]])\n def test_drop_non_empty_list(self, index, drop_labels):\n # GH# 21494\n with pytest.raises(KeyError, match="not found in axis"):\n DataFrame(index=index).drop(drop_labels)\n\n @pytest.mark.parametrize(\n "empty_listlike",\n [\n [],\n {},\n np.array([]),\n Series([], dtype="datetime64[ns]"),\n Index([]),\n DatetimeIndex([]),\n ],\n )\n def test_drop_empty_listlike_non_unique_datetime_index(self, empty_listlike):\n # GH#27994\n data = {"column_a": [5, 10], "column_b": ["one", "two"]}\n index = [Timestamp("2021-01-01"), Timestamp("2021-01-01")]\n df = DataFrame(data, index=index)\n\n # Passing empty list-like should return the same DataFrame.\n expected = df.copy()\n result = df.drop(empty_listlike)\n tm.assert_frame_equal(result, expected)\n\n def test_mixed_depth_drop(self):\n arrays = [\n ["a", "top", "top", "routine1", "routine1", "routine2"],\n ["", "OD", "OD", "result1", "result2", "result1"],\n ["", "wx", "wy", "", "", ""],\n ]\n\n tuples = sorted(zip(*arrays))\n index = MultiIndex.from_tuples(tuples)\n df = DataFrame(np.random.default_rng(2).standard_normal((4, 6)), columns=index)\n\n result = df.drop("a", axis=1)\n expected = df.drop([("a", "", "")], axis=1)\n tm.assert_frame_equal(expected, result)\n\n result = df.drop(["top"], axis=1)\n expected = df.drop([("top", "OD", "wx")], axis=1)\n expected = expected.drop([("top", "OD", "wy")], axis=1)\n tm.assert_frame_equal(expected, result)\n\n result = df.drop(("top", "OD", "wx"), axis=1)\n expected = df.drop([("top", "OD", "wx")], axis=1)\n tm.assert_frame_equal(expected, result)\n\n expected = df.drop([("top", "OD", "wy")], axis=1)\n expected = df.drop("top", axis=1)\n\n result = df.drop("result1", level=1, axis=1)\n expected = df.drop(\n [("routine1", "result1", ""), ("routine2", "result1", "")], axis=1\n )\n tm.assert_frame_equal(expected, result)\n\n def test_drop_multiindex_other_level_nan(self):\n # GH#12754\n df = (\n DataFrame(\n {\n "A": ["one", "one", "two", "two"],\n "B": [np.nan, 0.0, 1.0, 2.0],\n "C": ["a", "b", "c", "c"],\n "D": [1, 2, 3, 4],\n }\n )\n .set_index(["A", "B", "C"])\n .sort_index()\n )\n result = df.drop("c", level="C")\n expected = DataFrame(\n [2, 1],\n columns=["D"],\n index=MultiIndex.from_tuples(\n [("one", 0.0, "b"), ("one", np.nan, "a")], names=["A", "B", "C"]\n ),\n )\n tm.assert_frame_equal(result, expected)\n\n def test_drop_nonunique(self):\n df = DataFrame(\n [\n ["x-a", "x", "a", 1.5],\n ["x-a", "x", "a", 1.2],\n ["z-c", "z", "c", 3.1],\n ["x-a", "x", "a", 4.1],\n ["x-b", "x", "b", 5.1],\n ["x-b", "x", "b", 4.1],\n ["x-b", "x", "b", 2.2],\n ["y-a", "y", "a", 1.2],\n ["z-b", "z", "b", 2.1],\n ],\n columns=["var1", "var2", "var3", "var4"],\n )\n\n grp_size = df.groupby("var1").size()\n drop_idx = grp_size.loc[grp_size == 1]\n\n idf = df.set_index(["var1", "var2", "var3"])\n\n # it works! GH#2101\n result = idf.drop(drop_idx.index, level=0).reset_index()\n expected = df[-df.var1.isin(drop_idx.index)]\n\n result.index = expected.index\n\n tm.assert_frame_equal(result, expected)\n\n def test_drop_level(self, multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n\n result = frame.drop(["bar", "qux"], level="first")\n expected = frame.iloc[[0, 1, 2, 5, 6]]\n tm.assert_frame_equal(result, expected)\n\n result = frame.drop(["two"], level="second")\n expected = frame.iloc[[0, 2, 3, 6, 7, 9]]\n tm.assert_frame_equal(result, expected)\n\n result = frame.T.drop(["bar", "qux"], axis=1, level="first")\n expected = frame.iloc[[0, 1, 2, 5, 6]].T\n tm.assert_frame_equal(result, expected)\n\n result = frame.T.drop(["two"], axis=1, level="second")\n expected = frame.iloc[[0, 2, 3, 6, 7, 9]].T\n tm.assert_frame_equal(result, expected)\n\n def test_drop_level_nonunique_datetime(self):\n # GH#12701\n idx = Index([2, 3, 4, 4, 5], name="id")\n idxdt = pd.to_datetime(\n [\n "2016-03-23 14:00",\n "2016-03-23 15:00",\n "2016-03-23 16:00",\n "2016-03-23 16:00",\n "2016-03-23 17:00",\n ]\n )\n df = DataFrame(np.arange(10).reshape(5, 2), columns=list("ab"), index=idx)\n df["tstamp"] = idxdt\n df = df.set_index("tstamp", append=True)\n ts = Timestamp("201603231600")\n assert df.index.is_unique is False\n\n result = df.drop(ts, level="tstamp")\n expected = df.loc[idx != 4]\n tm.assert_frame_equal(result, expected)\n\n def test_drop_tz_aware_timestamp_across_dst(self, frame_or_series):\n # GH#21761\n start = Timestamp("2017-10-29", tz="Europe/Berlin")\n end = Timestamp("2017-10-29 04:00:00", tz="Europe/Berlin")\n index = pd.date_range(start, end, freq="15min")\n data = frame_or_series(data=[1] * len(index), index=index)\n result = data.drop(start)\n expected_start = Timestamp("2017-10-29 00:15:00", tz="Europe/Berlin")\n expected_idx = pd.date_range(expected_start, end, freq="15min")\n expected = frame_or_series(data=[1] * len(expected_idx), index=expected_idx)\n tm.assert_equal(result, expected)\n\n def test_drop_preserve_names(self):\n index = MultiIndex.from_arrays(\n [[0, 0, 0, 1, 1, 1], [1, 2, 3, 1, 2, 3]], names=["one", "two"]\n )\n\n df = DataFrame(np.random.default_rng(2).standard_normal((6, 3)), index=index)\n\n result = df.drop([(0, 2)])\n assert result.index.names == ("one", "two")\n\n @pytest.mark.parametrize(\n "operation", ["__iadd__", "__isub__", "__imul__", "__ipow__"]\n )\n @pytest.mark.parametrize("inplace", [False, True])\n def test_inplace_drop_and_operation(self, operation, inplace):\n # GH#30484\n df = DataFrame({"x": range(5)})\n expected = df.copy()\n df["y"] = range(5)\n y = df["y"]\n\n with tm.assert_produces_warning(None):\n if inplace:\n df.drop("y", axis=1, inplace=inplace)\n else:\n df = df.drop("y", axis=1, inplace=inplace)\n\n # Perform operation and check result\n getattr(y, operation)(1)\n tm.assert_frame_equal(df, expected)\n\n def test_drop_with_non_unique_multiindex(self):\n # GH#36293\n mi = MultiIndex.from_arrays([["x", "y", "x"], ["i", "j", "i"]])\n df = DataFrame([1, 2, 3], index=mi)\n result = df.drop(index="x")\n expected = DataFrame([2], index=MultiIndex.from_arrays([["y"], ["j"]]))\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("indexer", [("a", "a"), [("a", "a")]])\n def test_drop_tuple_with_non_unique_multiindex(self, indexer):\n # GH#42771\n idx = MultiIndex.from_product([["a", "b"], ["a", "a"]])\n df = DataFrame({"x": range(len(idx))}, index=idx)\n result = df.drop(index=[("a", "a")])\n expected = DataFrame(\n {"x": [2, 3]}, index=MultiIndex.from_tuples([("b", "a"), ("b", "a")])\n )\n tm.assert_frame_equal(result, expected)\n\n def test_drop_with_duplicate_columns(self):\n df = DataFrame(\n [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"]\n )\n result = df.drop(["a"], axis=1)\n expected = DataFrame([[1], [1], [1]], columns=["bar"])\n tm.assert_frame_equal(result, expected)\n result = df.drop("a", axis=1)\n tm.assert_frame_equal(result, expected)\n\n def test_drop_with_duplicate_columns2(self):\n # drop buggy GH#6240\n df = DataFrame(\n {\n "A": np.random.default_rng(2).standard_normal(5),\n "B": np.random.default_rng(2).standard_normal(5),\n "C": np.random.default_rng(2).standard_normal(5),\n "D": ["a", "b", "c", "d", "e"],\n }\n )\n\n expected = df.take([0, 1, 1], axis=1)\n df2 = df.take([2, 0, 1, 2, 1], axis=1)\n result = df2.drop("C", axis=1)\n tm.assert_frame_equal(result, expected)\n\n def test_drop_inplace_no_leftover_column_reference(self):\n # GH 13934\n df = DataFrame({"a": [1, 2, 3]}, columns=Index(["a"], dtype="object"))\n a = df.a\n df.drop(["a"], axis=1, inplace=True)\n tm.assert_index_equal(df.columns, Index([], dtype="object"))\n a -= a.mean()\n tm.assert_index_equal(df.columns, Index([], dtype="object"))\n\n def test_drop_level_missing_label_multiindex(self):\n # GH 18561\n df = DataFrame(index=MultiIndex.from_product([range(3), range(3)]))\n with pytest.raises(KeyError, match="labels \\[5\\] not found in level"):\n df.drop(5, level=0)\n\n @pytest.mark.parametrize("idx, level", [(["a", "b"], 0), (["a"], None)])\n def test_drop_index_ea_dtype(self, any_numeric_ea_dtype, idx, level):\n # GH#45860\n df = DataFrame(\n {"a": [1, 2, 2, pd.NA], "b": 100}, dtype=any_numeric_ea_dtype\n ).set_index(idx)\n result = df.drop(Index([2, pd.NA]), level=level)\n expected = DataFrame(\n {"a": [1], "b": 100}, dtype=any_numeric_ea_dtype\n ).set_index(idx)\n tm.assert_frame_equal(result, expected)\n\n def test_drop_parse_strings_datetime_index(self):\n # GH #5355\n df = DataFrame(\n {"a": [1, 2], "b": [1, 2]},\n index=[Timestamp("2000-01-03"), Timestamp("2000-01-04")],\n )\n result = df.drop("2000-01-03", axis=0)\n expected = DataFrame({"a": [2], "b": [2]}, index=[Timestamp("2000-01-04")])\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_drop.py
test_drop.py
Python
20,362
0.95
0.06044
0.073913
python-kit
758
2025-02-22T03:52:46.106351
GPL-3.0
true
6b9cd6f641a4975a2fbb3e46a6a4f769
import pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n)\nimport pandas._testing as tm\n\n\nclass TestDropLevel:\n def test_droplevel(self, frame_or_series):\n # GH#20342\n cols = MultiIndex.from_tuples(\n [("c", "e"), ("d", "f")], names=["level_1", "level_2"]\n )\n mi = MultiIndex.from_tuples([(1, 2), (5, 6), (9, 10)], names=["a", "b"])\n df = DataFrame([[3, 4], [7, 8], [11, 12]], index=mi, columns=cols)\n if frame_or_series is not DataFrame:\n df = df.iloc[:, 0]\n\n # test that dropping of a level in index works\n expected = df.reset_index("a", drop=True)\n result = df.droplevel("a", axis="index")\n tm.assert_equal(result, expected)\n\n if frame_or_series is DataFrame:\n # test that dropping of a level in columns works\n expected = df.copy()\n expected.columns = Index(["c", "d"], name="level_1")\n result = df.droplevel("level_2", axis="columns")\n tm.assert_equal(result, expected)\n else:\n # test that droplevel raises ValueError on axis != 0\n with pytest.raises(ValueError, match="No axis named columns"):\n df.droplevel(1, axis="columns")\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_droplevel.py
test_droplevel.py
Python
1,253
0.95
0.111111
0.129032
awesome-app
607
2024-02-10T08:22:14.126678
MIT
true
a6ae9891d5b8c146b33ade53d51b1961
import datetime\n\nimport dateutil\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameMissingData:\n def test_dropEmptyRows(self, float_frame):\n N = len(float_frame.index)\n mat = np.random.default_rng(2).standard_normal(N)\n mat[:5] = np.nan\n\n frame = DataFrame({"foo": mat}, index=float_frame.index)\n original = Series(mat, index=float_frame.index, name="foo")\n expected = original.dropna()\n inplace_frame1, inplace_frame2 = frame.copy(), frame.copy()\n\n smaller_frame = frame.dropna(how="all")\n # check that original was preserved\n tm.assert_series_equal(frame["foo"], original)\n return_value = inplace_frame1.dropna(how="all", inplace=True)\n tm.assert_series_equal(smaller_frame["foo"], expected)\n tm.assert_series_equal(inplace_frame1["foo"], expected)\n assert return_value is None\n\n smaller_frame = frame.dropna(how="all", subset=["foo"])\n return_value = inplace_frame2.dropna(how="all", subset=["foo"], inplace=True)\n tm.assert_series_equal(smaller_frame["foo"], expected)\n tm.assert_series_equal(inplace_frame2["foo"], expected)\n assert return_value is None\n\n def test_dropIncompleteRows(self, float_frame):\n N = len(float_frame.index)\n mat = np.random.default_rng(2).standard_normal(N)\n mat[:5] = np.nan\n\n frame = DataFrame({"foo": mat}, index=float_frame.index)\n frame["bar"] = 5\n original = Series(mat, index=float_frame.index, name="foo")\n inp_frame1, inp_frame2 = frame.copy(), frame.copy()\n\n smaller_frame = frame.dropna()\n tm.assert_series_equal(frame["foo"], original)\n return_value = inp_frame1.dropna(inplace=True)\n\n exp = Series(mat[5:], index=float_frame.index[5:], name="foo")\n tm.assert_series_equal(smaller_frame["foo"], exp)\n tm.assert_series_equal(inp_frame1["foo"], exp)\n assert return_value is None\n\n samesize_frame = frame.dropna(subset=["bar"])\n tm.assert_series_equal(frame["foo"], original)\n assert (frame["bar"] == 5).all()\n return_value = inp_frame2.dropna(subset=["bar"], inplace=True)\n tm.assert_index_equal(samesize_frame.index, float_frame.index)\n tm.assert_index_equal(inp_frame2.index, float_frame.index)\n assert return_value is None\n\n def test_dropna(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((6, 4)))\n df.iloc[:2, 2] = np.nan\n\n dropped = df.dropna(axis=1)\n expected = df.loc[:, [0, 1, 3]]\n inp = df.copy()\n return_value = inp.dropna(axis=1, inplace=True)\n tm.assert_frame_equal(dropped, expected)\n tm.assert_frame_equal(inp, expected)\n assert return_value is None\n\n dropped = df.dropna(axis=0)\n expected = df.loc[list(range(2, 6))]\n inp = df.copy()\n return_value = inp.dropna(axis=0, inplace=True)\n tm.assert_frame_equal(dropped, expected)\n tm.assert_frame_equal(inp, expected)\n assert return_value is None\n\n # threshold\n dropped = df.dropna(axis=1, thresh=5)\n expected = df.loc[:, [0, 1, 3]]\n inp = df.copy()\n return_value = inp.dropna(axis=1, thresh=5, inplace=True)\n tm.assert_frame_equal(dropped, expected)\n tm.assert_frame_equal(inp, expected)\n assert return_value is None\n\n dropped = df.dropna(axis=0, thresh=4)\n expected = df.loc[range(2, 6)]\n inp = df.copy()\n return_value = inp.dropna(axis=0, thresh=4, inplace=True)\n tm.assert_frame_equal(dropped, expected)\n tm.assert_frame_equal(inp, expected)\n assert return_value is None\n\n dropped = df.dropna(axis=1, thresh=4)\n tm.assert_frame_equal(dropped, df)\n\n dropped = df.dropna(axis=1, thresh=3)\n tm.assert_frame_equal(dropped, df)\n\n # subset\n dropped = df.dropna(axis=0, subset=[0, 1, 3])\n inp = df.copy()\n return_value = inp.dropna(axis=0, subset=[0, 1, 3], inplace=True)\n tm.assert_frame_equal(dropped, df)\n tm.assert_frame_equal(inp, df)\n assert return_value is None\n\n # all\n dropped = df.dropna(axis=1, how="all")\n tm.assert_frame_equal(dropped, df)\n\n df[2] = np.nan\n dropped = df.dropna(axis=1, how="all")\n expected = df.loc[:, [0, 1, 3]]\n tm.assert_frame_equal(dropped, expected)\n\n # bad input\n msg = "No axis named 3 for object type DataFrame"\n with pytest.raises(ValueError, match=msg):\n df.dropna(axis=3)\n\n def test_drop_and_dropna_caching(self):\n # tst that cacher updates\n original = Series([1, 2, np.nan], name="A")\n expected = Series([1, 2], dtype=original.dtype, name="A")\n df = DataFrame({"A": original.values.copy()})\n df2 = df.copy()\n df["A"].dropna()\n tm.assert_series_equal(df["A"], original)\n\n ser = df["A"]\n return_value = ser.dropna(inplace=True)\n tm.assert_series_equal(ser, expected)\n tm.assert_series_equal(df["A"], original)\n assert return_value is None\n\n df2["A"].drop([1])\n tm.assert_series_equal(df2["A"], original)\n\n ser = df2["A"]\n return_value = ser.drop([1], inplace=True)\n tm.assert_series_equal(ser, original.drop([1]))\n tm.assert_series_equal(df2["A"], original)\n assert return_value is None\n\n def test_dropna_corner(self, float_frame):\n # bad input\n msg = "invalid how option: foo"\n with pytest.raises(ValueError, match=msg):\n float_frame.dropna(how="foo")\n # non-existent column - 8303\n with pytest.raises(KeyError, match=r"^\['X'\]$"):\n float_frame.dropna(subset=["A", "X"])\n\n def test_dropna_multiple_axes(self):\n df = DataFrame(\n [\n [1, np.nan, 2, 3],\n [4, np.nan, 5, 6],\n [np.nan, np.nan, np.nan, np.nan],\n [7, np.nan, 8, 9],\n ]\n )\n\n # GH20987\n with pytest.raises(TypeError, match="supplying multiple axes"):\n df.dropna(how="all", axis=[0, 1])\n with pytest.raises(TypeError, match="supplying multiple axes"):\n df.dropna(how="all", axis=(0, 1))\n\n inp = df.copy()\n with pytest.raises(TypeError, match="supplying multiple axes"):\n inp.dropna(how="all", axis=(0, 1), inplace=True)\n\n def test_dropna_tz_aware_datetime(self, using_infer_string):\n # GH13407\n\n df = DataFrame()\n if using_infer_string:\n df.columns = df.columns.astype("str")\n dt1 = datetime.datetime(2015, 1, 1, tzinfo=dateutil.tz.tzutc())\n dt2 = datetime.datetime(2015, 2, 2, tzinfo=dateutil.tz.tzutc())\n df["Time"] = [dt1]\n result = df.dropna(axis=0)\n expected = DataFrame({"Time": [dt1]})\n tm.assert_frame_equal(result, expected)\n\n # Ex2\n df = DataFrame({"Time": [dt1, None, np.nan, dt2]})\n result = df.dropna(axis=0)\n expected = DataFrame([dt1, dt2], columns=["Time"], index=[0, 3])\n tm.assert_frame_equal(result, expected)\n\n def test_dropna_categorical_interval_index(self):\n # GH 25087\n ii = pd.IntervalIndex.from_breaks([0, 2.78, 3.14, 6.28])\n ci = pd.CategoricalIndex(ii)\n df = DataFrame({"A": list("abc")}, index=ci)\n\n expected = df\n result = df.dropna()\n tm.assert_frame_equal(result, expected)\n\n def test_dropna_with_duplicate_columns(self):\n df = DataFrame(\n {\n "A": np.random.default_rng(2).standard_normal(5),\n "B": np.random.default_rng(2).standard_normal(5),\n "C": np.random.default_rng(2).standard_normal(5),\n "D": ["a", "b", "c", "d", "e"],\n }\n )\n df.iloc[2, [0, 1, 2]] = np.nan\n df.iloc[0, 0] = np.nan\n df.iloc[1, 1] = np.nan\n df.iloc[:, 3] = np.nan\n expected = df.dropna(subset=["A", "B", "C"], how="all")\n expected.columns = ["A", "A", "B", "C"]\n\n df.columns = ["A", "A", "B", "C"]\n\n result = df.dropna(subset=["A", "C"], how="all")\n tm.assert_frame_equal(result, expected)\n\n def test_set_single_column_subset(self):\n # GH 41021\n df = DataFrame({"A": [1, 2, 3], "B": list("abc"), "C": [4, np.nan, 5]})\n expected = DataFrame(\n {"A": [1, 3], "B": list("ac"), "C": [4.0, 5.0]}, index=[0, 2]\n )\n result = df.dropna(subset="C")\n tm.assert_frame_equal(result, expected)\n\n def test_single_column_not_present_in_axis(self):\n # GH 41021\n df = DataFrame({"A": [1, 2, 3]})\n\n # Column not present\n with pytest.raises(KeyError, match="['D']"):\n df.dropna(subset="D", axis=0)\n\n def test_subset_is_nparray(self):\n # GH 41021\n df = DataFrame({"A": [1, 2, np.nan], "B": list("abc"), "C": [4, np.nan, 5]})\n expected = DataFrame({"A": [1.0], "B": ["a"], "C": [4.0]})\n result = df.dropna(subset=np.array(["A", "C"]))\n tm.assert_frame_equal(result, expected)\n\n def test_no_nans_in_frame(self, axis):\n # GH#41965\n df = DataFrame([[1, 2], [3, 4]], columns=pd.RangeIndex(0, 2))\n expected = df.copy()\n result = df.dropna(axis=axis)\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n def test_how_thresh_param_incompatible(self):\n # GH46575\n df = DataFrame([1, 2, pd.NA])\n msg = "You cannot set both the how and thresh arguments at the same time"\n with pytest.raises(TypeError, match=msg):\n df.dropna(how="all", thresh=2)\n\n with pytest.raises(TypeError, match=msg):\n df.dropna(how="any", thresh=2)\n\n with pytest.raises(TypeError, match=msg):\n df.dropna(how=None, thresh=None)\n\n @pytest.mark.parametrize("val", [1, 1.5])\n def test_dropna_ignore_index(self, val):\n # GH#31725\n df = DataFrame({"a": [1, 2, val]}, index=[3, 2, 1])\n result = df.dropna(ignore_index=True)\n expected = DataFrame({"a": [1, 2, val]})\n tm.assert_frame_equal(result, expected)\n\n df.dropna(ignore_index=True, inplace=True)\n tm.assert_frame_equal(df, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_dropna.py
test_dropna.py
Python
10,417
0.95
0.0625
0.079498
python-kit
499
2024-02-18T12:12:48.646762
GPL-3.0
true
d5bcafd2e51b2f3fb48673800ace8326
from datetime import datetime\nimport re\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n NaT,\n concat,\n)\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize("subset", ["a", ["a"], ["a", "B"]])\ndef test_drop_duplicates_with_misspelled_column_name(subset):\n # GH 19730\n df = DataFrame({"A": [0, 0, 1], "B": [0, 0, 1], "C": [0, 0, 1]})\n msg = re.escape("Index(['a'], dtype=")\n\n with pytest.raises(KeyError, match=msg):\n df.drop_duplicates(subset)\n\n\ndef test_drop_duplicates():\n df = DataFrame(\n {\n "AAA": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"],\n "B": ["one", "one", "two", "two", "two", "two", "one", "two"],\n "C": [1, 1, 2, 2, 2, 2, 1, 2],\n "D": range(8),\n }\n )\n # single column\n result = df.drop_duplicates("AAA")\n expected = df[:2]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("AAA", keep="last")\n expected = df.loc[[6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("AAA", keep=False)\n expected = df.loc[[]]\n tm.assert_frame_equal(result, expected)\n assert len(result) == 0\n\n # multi column\n expected = df.loc[[0, 1, 2, 3]]\n result = df.drop_duplicates(np.array(["AAA", "B"]))\n tm.assert_frame_equal(result, expected)\n result = df.drop_duplicates(["AAA", "B"])\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(("AAA", "B"), keep="last")\n expected = df.loc[[0, 5, 6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(("AAA", "B"), keep=False)\n expected = df.loc[[0]]\n tm.assert_frame_equal(result, expected)\n\n # consider everything\n df2 = df.loc[:, ["AAA", "B", "C"]]\n\n result = df2.drop_duplicates()\n # in this case only\n expected = df2.drop_duplicates(["AAA", "B"])\n tm.assert_frame_equal(result, expected)\n\n result = df2.drop_duplicates(keep="last")\n expected = df2.drop_duplicates(["AAA", "B"], keep="last")\n tm.assert_frame_equal(result, expected)\n\n result = df2.drop_duplicates(keep=False)\n expected = df2.drop_duplicates(["AAA", "B"], keep=False)\n tm.assert_frame_equal(result, expected)\n\n # integers\n result = df.drop_duplicates("C")\n expected = df.iloc[[0, 2]]\n tm.assert_frame_equal(result, expected)\n result = df.drop_duplicates("C", keep="last")\n expected = df.iloc[[-2, -1]]\n tm.assert_frame_equal(result, expected)\n\n df["E"] = df["C"].astype("int8")\n result = df.drop_duplicates("E")\n expected = df.iloc[[0, 2]]\n tm.assert_frame_equal(result, expected)\n result = df.drop_duplicates("E", keep="last")\n expected = df.iloc[[-2, -1]]\n tm.assert_frame_equal(result, expected)\n\n # GH 11376\n df = DataFrame({"x": [7, 6, 3, 3, 4, 8, 0], "y": [0, 6, 5, 5, 9, 1, 2]})\n expected = df.loc[df.index != 3]\n tm.assert_frame_equal(df.drop_duplicates(), expected)\n\n df = DataFrame([[1, 0], [0, 2]])\n tm.assert_frame_equal(df.drop_duplicates(), df)\n\n df = DataFrame([[-2, 0], [0, -4]])\n tm.assert_frame_equal(df.drop_duplicates(), df)\n\n x = np.iinfo(np.int64).max / 3 * 2\n df = DataFrame([[-x, x], [0, x + 4]])\n tm.assert_frame_equal(df.drop_duplicates(), df)\n\n df = DataFrame([[-x, x], [x, x + 4]])\n tm.assert_frame_equal(df.drop_duplicates(), df)\n\n # GH 11864\n df = DataFrame([i] * 9 for i in range(16))\n df = concat([df, DataFrame([[1] + [0] * 8])], ignore_index=True)\n\n for keep in ["first", "last", False]:\n assert df.duplicated(keep=keep).sum() == 0\n\n\ndef test_drop_duplicates_with_duplicate_column_names():\n # GH17836\n df = DataFrame([[1, 2, 5], [3, 4, 6], [3, 4, 7]], columns=["a", "a", "b"])\n\n result0 = df.drop_duplicates()\n tm.assert_frame_equal(result0, df)\n\n result1 = df.drop_duplicates("a")\n expected1 = df[:2]\n tm.assert_frame_equal(result1, expected1)\n\n\ndef test_drop_duplicates_for_take_all():\n df = DataFrame(\n {\n "AAA": ["foo", "bar", "baz", "bar", "foo", "bar", "qux", "foo"],\n "B": ["one", "one", "two", "two", "two", "two", "one", "two"],\n "C": [1, 1, 2, 2, 2, 2, 1, 2],\n "D": range(8),\n }\n )\n # single column\n result = df.drop_duplicates("AAA")\n expected = df.iloc[[0, 1, 2, 6]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("AAA", keep="last")\n expected = df.iloc[[2, 5, 6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("AAA", keep=False)\n expected = df.iloc[[2, 6]]\n tm.assert_frame_equal(result, expected)\n\n # multiple columns\n result = df.drop_duplicates(["AAA", "B"])\n expected = df.iloc[[0, 1, 2, 3, 4, 6]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(["AAA", "B"], keep="last")\n expected = df.iloc[[0, 1, 2, 5, 6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(["AAA", "B"], keep=False)\n expected = df.iloc[[0, 1, 2, 6]]\n tm.assert_frame_equal(result, expected)\n\n\ndef test_drop_duplicates_tuple():\n df = DataFrame(\n {\n ("AA", "AB"): ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"],\n "B": ["one", "one", "two", "two", "two", "two", "one", "two"],\n "C": [1, 1, 2, 2, 2, 2, 1, 2],\n "D": range(8),\n }\n )\n # single column\n result = df.drop_duplicates(("AA", "AB"))\n expected = df[:2]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(("AA", "AB"), keep="last")\n expected = df.loc[[6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(("AA", "AB"), keep=False)\n expected = df.loc[[]] # empty df\n assert len(result) == 0\n tm.assert_frame_equal(result, expected)\n\n # multi column\n expected = df.loc[[0, 1, 2, 3]]\n result = df.drop_duplicates((("AA", "AB"), "B"))\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "df",\n [\n DataFrame(),\n DataFrame(columns=[]),\n DataFrame(columns=["A", "B", "C"]),\n DataFrame(index=[]),\n DataFrame(index=["A", "B", "C"]),\n ],\n)\ndef test_drop_duplicates_empty(df):\n # GH 20516\n result = df.drop_duplicates()\n tm.assert_frame_equal(result, df)\n\n result = df.copy()\n result.drop_duplicates(inplace=True)\n tm.assert_frame_equal(result, df)\n\n\ndef test_drop_duplicates_NA():\n # none\n df = DataFrame(\n {\n "A": [None, None, "foo", "bar", "foo", "bar", "bar", "foo"],\n "B": ["one", "one", "two", "two", "two", "two", "one", "two"],\n "C": [1.0, np.nan, np.nan, np.nan, 1.0, 1.0, 1, 1.0],\n "D": range(8),\n }\n )\n # single column\n result = df.drop_duplicates("A")\n expected = df.loc[[0, 2, 3]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("A", keep="last")\n expected = df.loc[[1, 6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("A", keep=False)\n expected = df.loc[[]] # empty df\n tm.assert_frame_equal(result, expected)\n assert len(result) == 0\n\n # multi column\n result = df.drop_duplicates(["A", "B"])\n expected = df.loc[[0, 2, 3, 6]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(["A", "B"], keep="last")\n expected = df.loc[[1, 5, 6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(["A", "B"], keep=False)\n expected = df.loc[[6]]\n tm.assert_frame_equal(result, expected)\n\n # nan\n df = DataFrame(\n {\n "A": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"],\n "B": ["one", "one", "two", "two", "two", "two", "one", "two"],\n "C": [1.0, np.nan, np.nan, np.nan, 1.0, 1.0, 1, 1.0],\n "D": range(8),\n }\n )\n # single column\n result = df.drop_duplicates("C")\n expected = df[:2]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("C", keep="last")\n expected = df.loc[[3, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("C", keep=False)\n expected = df.loc[[]] # empty df\n tm.assert_frame_equal(result, expected)\n assert len(result) == 0\n\n # multi column\n result = df.drop_duplicates(["C", "B"])\n expected = df.loc[[0, 1, 2, 4]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(["C", "B"], keep="last")\n expected = df.loc[[1, 3, 6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates(["C", "B"], keep=False)\n expected = df.loc[[1]]\n tm.assert_frame_equal(result, expected)\n\n\ndef test_drop_duplicates_NA_for_take_all():\n # none\n df = DataFrame(\n {\n "A": [None, None, "foo", "bar", "foo", "baz", "bar", "qux"],\n "C": [1.0, np.nan, np.nan, np.nan, 1.0, 2.0, 3, 1.0],\n }\n )\n\n # single column\n result = df.drop_duplicates("A")\n expected = df.iloc[[0, 2, 3, 5, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("A", keep="last")\n expected = df.iloc[[1, 4, 5, 6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("A", keep=False)\n expected = df.iloc[[5, 7]]\n tm.assert_frame_equal(result, expected)\n\n # nan\n\n # single column\n result = df.drop_duplicates("C")\n expected = df.iloc[[0, 1, 5, 6]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("C", keep="last")\n expected = df.iloc[[3, 5, 6, 7]]\n tm.assert_frame_equal(result, expected)\n\n result = df.drop_duplicates("C", keep=False)\n expected = df.iloc[[5, 6]]\n tm.assert_frame_equal(result, expected)\n\n\ndef test_drop_duplicates_inplace():\n orig = DataFrame(\n {\n "A": ["foo", "bar", "foo", "bar", "foo", "bar", "bar", "foo"],\n "B": ["one", "one", "two", "two", "two", "two", "one", "two"],\n "C": [1, 1, 2, 2, 2, 2, 1, 2],\n "D": range(8),\n }\n )\n # single column\n df = orig.copy()\n return_value = df.drop_duplicates("A", inplace=True)\n expected = orig[:2]\n result = df\n tm.assert_frame_equal(result, expected)\n assert return_value is None\n\n df = orig.copy()\n return_value = df.drop_duplicates("A", keep="last", inplace=True)\n expected = orig.loc[[6, 7]]\n result = df\n tm.assert_frame_equal(result, expected)\n assert return_value is None\n\n df = orig.copy()\n return_value = df.drop_duplicates("A", keep=False, inplace=True)\n expected = orig.loc[[]]\n result = df\n tm.assert_frame_equal(result, expected)\n assert len(df) == 0\n assert return_value is None\n\n # multi column\n df = orig.copy()\n return_value = df.drop_duplicates(["A", "B"], inplace=True)\n expected = orig.loc[[0, 1, 2, 3]]\n result = df\n tm.assert_frame_equal(result, expected)\n assert return_value is None\n\n df = orig.copy()\n return_value = df.drop_duplicates(["A", "B"], keep="last", inplace=True)\n expected = orig.loc[[0, 5, 6, 7]]\n result = df\n tm.assert_frame_equal(result, expected)\n assert return_value is None\n\n df = orig.copy()\n return_value = df.drop_duplicates(["A", "B"], keep=False, inplace=True)\n expected = orig.loc[[0]]\n result = df\n tm.assert_frame_equal(result, expected)\n assert return_value is None\n\n # consider everything\n orig2 = orig.loc[:, ["A", "B", "C"]].copy()\n\n df2 = orig2.copy()\n return_value = df2.drop_duplicates(inplace=True)\n # in this case only\n expected = orig2.drop_duplicates(["A", "B"])\n result = df2\n tm.assert_frame_equal(result, expected)\n assert return_value is None\n\n df2 = orig2.copy()\n return_value = df2.drop_duplicates(keep="last", inplace=True)\n expected = orig2.drop_duplicates(["A", "B"], keep="last")\n result = df2\n tm.assert_frame_equal(result, expected)\n assert return_value is None\n\n df2 = orig2.copy()\n return_value = df2.drop_duplicates(keep=False, inplace=True)\n expected = orig2.drop_duplicates(["A", "B"], keep=False)\n result = df2\n tm.assert_frame_equal(result, expected)\n assert return_value is None\n\n\n@pytest.mark.parametrize("inplace", [True, False])\n@pytest.mark.parametrize(\n "origin_dict, output_dict, ignore_index, output_index",\n [\n ({"A": [2, 2, 3]}, {"A": [2, 3]}, True, [0, 1]),\n ({"A": [2, 2, 3]}, {"A": [2, 3]}, False, [0, 2]),\n ({"A": [2, 2, 3], "B": [2, 2, 4]}, {"A": [2, 3], "B": [2, 4]}, True, [0, 1]),\n ({"A": [2, 2, 3], "B": [2, 2, 4]}, {"A": [2, 3], "B": [2, 4]}, False, [0, 2]),\n ],\n)\ndef test_drop_duplicates_ignore_index(\n inplace, origin_dict, output_dict, ignore_index, output_index\n):\n # GH 30114\n df = DataFrame(origin_dict)\n expected = DataFrame(output_dict, index=output_index)\n\n if inplace:\n result_df = df.copy()\n result_df.drop_duplicates(ignore_index=ignore_index, inplace=inplace)\n else:\n result_df = df.drop_duplicates(ignore_index=ignore_index, inplace=inplace)\n\n tm.assert_frame_equal(result_df, expected)\n tm.assert_frame_equal(df, DataFrame(origin_dict))\n\n\ndef test_drop_duplicates_null_in_object_column(nulls_fixture):\n # https://github.com/pandas-dev/pandas/issues/32992\n df = DataFrame([[1, nulls_fixture], [2, "a"]], dtype=object)\n result = df.drop_duplicates()\n tm.assert_frame_equal(result, df)\n\n\ndef test_drop_duplicates_series_vs_dataframe(keep):\n # GH#14192\n df = DataFrame(\n {\n "a": [1, 1, 1, "one", "one"],\n "b": [2, 2, np.nan, np.nan, np.nan],\n "c": [3, 3, np.nan, np.nan, "three"],\n "d": [1, 2, 3, 4, 4],\n "e": [\n datetime(2015, 1, 1),\n datetime(2015, 1, 1),\n datetime(2015, 2, 1),\n NaT,\n NaT,\n ],\n }\n )\n for column in df.columns:\n dropped_frame = df[[column]].drop_duplicates(keep=keep)\n dropped_series = df[column].drop_duplicates(keep=keep)\n tm.assert_frame_equal(dropped_frame, dropped_series.to_frame())\n\n\n@pytest.mark.parametrize("arg", [[1], 1, "True", [], 0])\ndef test_drop_duplicates_non_boolean_ignore_index(arg):\n # GH#38274\n df = DataFrame({"a": [1, 2, 1, 3]})\n msg = '^For argument "ignore_index" expected type bool, received type .*.$'\n with pytest.raises(ValueError, match=msg):\n df.drop_duplicates(ignore_index=arg)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_drop_duplicates.py
test_drop_duplicates.py
Python
14,503
0.95
0.035941
0.082902
node-utils
979
2024-11-11T21:47:38.130985
MIT
true
556fb197193279b669fcc7d27ad75de3
from datetime import timedelta\n\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import DatetimeTZDtype\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Series,\n date_range,\n option_context,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameDataTypes:\n def test_empty_frame_dtypes(self):\n empty_df = DataFrame()\n tm.assert_series_equal(empty_df.dtypes, Series(dtype=object))\n\n nocols_df = DataFrame(index=[1, 2, 3])\n tm.assert_series_equal(nocols_df.dtypes, Series(dtype=object))\n\n norows_df = DataFrame(columns=list("abc"))\n tm.assert_series_equal(norows_df.dtypes, Series(object, index=list("abc")))\n\n norows_int_df = DataFrame(columns=list("abc")).astype(np.int32)\n tm.assert_series_equal(\n norows_int_df.dtypes, Series(np.dtype("int32"), index=list("abc"))\n )\n\n df = DataFrame({"a": 1, "b": True, "c": 1.0}, index=[1, 2, 3])\n ex_dtypes = Series({"a": np.int64, "b": np.bool_, "c": np.float64})\n tm.assert_series_equal(df.dtypes, ex_dtypes)\n\n # same but for empty slice of df\n tm.assert_series_equal(df[:0].dtypes, ex_dtypes)\n\n def test_datetime_with_tz_dtypes(self):\n tzframe = DataFrame(\n {\n "A": date_range("20130101", periods=3),\n "B": date_range("20130101", periods=3, tz="US/Eastern"),\n "C": date_range("20130101", periods=3, tz="CET"),\n }\n )\n tzframe.iloc[1, 1] = pd.NaT\n tzframe.iloc[1, 2] = pd.NaT\n result = tzframe.dtypes.sort_index()\n expected = Series(\n [\n np.dtype("datetime64[ns]"),\n DatetimeTZDtype("ns", "US/Eastern"),\n DatetimeTZDtype("ns", "CET"),\n ],\n ["A", "B", "C"],\n )\n\n tm.assert_series_equal(result, expected)\n\n def test_dtypes_are_correct_after_column_slice(self):\n # GH6525\n df = DataFrame(index=range(5), columns=list("abc"), dtype=np.float64)\n tm.assert_series_equal(\n df.dtypes,\n Series({"a": np.float64, "b": np.float64, "c": np.float64}),\n )\n tm.assert_series_equal(df.iloc[:, 2:].dtypes, Series({"c": np.float64}))\n tm.assert_series_equal(\n df.dtypes,\n Series({"a": np.float64, "b": np.float64, "c": np.float64}),\n )\n\n @pytest.mark.parametrize(\n "data",\n [pd.NA, True],\n )\n def test_dtypes_are_correct_after_groupby_last(self, data):\n # GH46409\n df = DataFrame(\n {"id": [1, 2, 3, 4], "test": [True, pd.NA, data, False]}\n ).convert_dtypes()\n result = df.groupby("id").last().test\n expected = df.set_index("id").test\n assert result.dtype == pd.BooleanDtype()\n tm.assert_series_equal(expected, result)\n\n def test_dtypes_gh8722(self, float_string_frame):\n float_string_frame["bool"] = float_string_frame["A"] > 0\n result = float_string_frame.dtypes\n expected = Series(\n {k: v.dtype for k, v in float_string_frame.items()}, index=result.index\n )\n tm.assert_series_equal(result, expected)\n\n # compat, GH 8722\n msg = "use_inf_as_na option is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with option_context("use_inf_as_na", True):\n df = DataFrame([[1]])\n result = df.dtypes\n tm.assert_series_equal(result, Series({0: np.dtype("int64")}))\n\n def test_dtypes_timedeltas(self):\n df = DataFrame(\n {\n "A": Series(date_range("2012-1-1", periods=3, freq="D")),\n "B": Series([timedelta(days=i) for i in range(3)]),\n }\n )\n result = df.dtypes\n expected = Series(\n [np.dtype("datetime64[ns]"), np.dtype("timedelta64[ns]")], index=list("AB")\n )\n tm.assert_series_equal(result, expected)\n\n df["C"] = df["A"] + df["B"]\n result = df.dtypes\n expected = Series(\n [\n np.dtype("datetime64[ns]"),\n np.dtype("timedelta64[ns]"),\n np.dtype("datetime64[ns]"),\n ],\n index=list("ABC"),\n )\n tm.assert_series_equal(result, expected)\n\n # mixed int types\n df["D"] = 1\n result = df.dtypes\n expected = Series(\n [\n np.dtype("datetime64[ns]"),\n np.dtype("timedelta64[ns]"),\n np.dtype("datetime64[ns]"),\n np.dtype("int64"),\n ],\n index=list("ABCD"),\n )\n tm.assert_series_equal(result, expected)\n\n def test_frame_apply_np_array_return_type(self, using_infer_string):\n # GH 35517\n df = DataFrame([["foo"]])\n result = df.apply(lambda col: np.array("bar"))\n expected = Series(np.array("bar"))\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_dtypes.py
test_dtypes.py
Python
5,001
0.95
0.073333
0.046154
node-utils
730
2025-04-04T04:21:08.188153
Apache-2.0
true
ee88f2848b30072e55ccca50f45b7322
import re\nimport sys\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize("subset", ["a", ["a"], ["a", "B"]])\ndef test_duplicated_with_misspelled_column_name(subset):\n # GH 19730\n df = DataFrame({"A": [0, 0, 1], "B": [0, 0, 1], "C": [0, 0, 1]})\n msg = re.escape("Index(['a'], dtype=")\n\n with pytest.raises(KeyError, match=msg):\n df.duplicated(subset)\n\n\ndef test_duplicated_implemented_no_recursion():\n # gh-21524\n # Ensure duplicated isn't implemented using recursion that\n # can fail on wide frames\n df = DataFrame(np.random.default_rng(2).integers(0, 1000, (10, 1000)))\n rec_limit = sys.getrecursionlimit()\n try:\n sys.setrecursionlimit(100)\n result = df.duplicated()\n finally:\n sys.setrecursionlimit(rec_limit)\n\n # Then duplicates produce the bool Series as a result and don't fail during\n # calculation. Actual values doesn't matter here, though usually it's all\n # False in this case\n assert isinstance(result, Series)\n assert result.dtype == np.bool_\n\n\n@pytest.mark.parametrize(\n "keep, expected",\n [\n ("first", Series([False, False, True, False, True])),\n ("last", Series([True, True, False, False, False])),\n (False, Series([True, True, True, False, True])),\n ],\n)\ndef test_duplicated_keep(keep, expected):\n df = DataFrame({"A": [0, 1, 1, 2, 0], "B": ["a", "b", "b", "c", "a"]})\n\n result = df.duplicated(keep=keep)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.xfail(reason="GH#21720; nan/None falsely considered equal")\n@pytest.mark.parametrize(\n "keep, expected",\n [\n ("first", Series([False, False, True, False, True])),\n ("last", Series([True, True, False, False, False])),\n (False, Series([True, True, True, False, True])),\n ],\n)\ndef test_duplicated_nan_none(keep, expected):\n df = DataFrame({"C": [np.nan, 3, 3, None, np.nan], "x": 1}, dtype=object)\n\n result = df.duplicated(keep=keep)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("subset", [None, ["A", "B"], "A"])\ndef test_duplicated_subset(subset, keep):\n df = DataFrame(\n {\n "A": [0, 1, 1, 2, 0],\n "B": ["a", "b", "b", "c", "a"],\n "C": [np.nan, 3, 3, None, np.nan],\n }\n )\n\n if subset is None:\n subset = list(df.columns)\n elif isinstance(subset, str):\n # need to have a DataFrame, not a Series\n # -> select columns with singleton list, not string\n subset = [subset]\n\n expected = df[subset].duplicated(keep=keep)\n result = df.duplicated(keep=keep, subset=subset)\n tm.assert_series_equal(result, expected)\n\n\ndef test_duplicated_on_empty_frame():\n # GH 25184\n\n df = DataFrame(columns=["a", "b"])\n dupes = df.duplicated("a")\n\n result = df[dupes]\n expected = df.copy()\n tm.assert_frame_equal(result, expected)\n\n\ndef test_frame_datetime64_duplicated():\n dates = date_range("2010-07-01", end="2010-08-05")\n\n tst = DataFrame({"symbol": "AAA", "date": dates})\n result = tst.duplicated(["date", "symbol"])\n assert (-result).all()\n\n tst = DataFrame({"date": dates})\n result = tst.date.duplicated()\n assert (-result).all()\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_duplicated.py
test_duplicated.py
Python
3,305
0.95
0.076923
0.10989
vue-tools
760
2025-01-01T22:37:06.744433
BSD-3-Clause
true
1abaca194f25e511e8636863932ae92d
import numpy as np\n\nfrom pandas import (\n DataFrame,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestEquals:\n def test_dataframe_not_equal(self):\n # see GH#28839\n df1 = DataFrame({"a": [1, 2], "b": ["s", "d"]})\n df2 = DataFrame({"a": ["s", "d"], "b": [1, 2]})\n assert df1.equals(df2) is False\n\n def test_equals_different_blocks(self, using_array_manager, using_infer_string):\n # GH#9330\n df0 = DataFrame({"A": ["x", "y"], "B": [1, 2], "C": ["w", "z"]})\n df1 = df0.reset_index()[["A", "B", "C"]]\n if not using_array_manager and not using_infer_string:\n # this assert verifies that the above operations have\n # induced a block rearrangement\n assert df0._mgr.blocks[0].dtype != df1._mgr.blocks[0].dtype\n\n # do the real tests\n tm.assert_frame_equal(df0, df1)\n assert df0.equals(df1)\n assert df1.equals(df0)\n\n def test_equals(self):\n # Add object dtype column with nans\n index = np.random.default_rng(2).random(10)\n df1 = DataFrame(\n np.random.default_rng(2).random(10), index=index, columns=["floats"]\n )\n df1["text"] = "the sky is so blue. we could use more chocolate.".split()\n df1["start"] = date_range("2000-1-1", periods=10, freq="min")\n df1["end"] = date_range("2000-1-1", periods=10, freq="D")\n df1["diff"] = df1["end"] - df1["start"]\n # Explicitly cast to object, to avoid implicit cast when setting np.nan\n df1["bool"] = (np.arange(10) % 3 == 0).astype(object)\n df1.loc[::2] = np.nan\n df2 = df1.copy()\n assert df1["text"].equals(df2["text"])\n assert df1["start"].equals(df2["start"])\n assert df1["end"].equals(df2["end"])\n assert df1["diff"].equals(df2["diff"])\n assert df1["bool"].equals(df2["bool"])\n assert df1.equals(df2)\n assert not df1.equals(object)\n\n # different dtype\n different = df1.copy()\n different["floats"] = different["floats"].astype("float32")\n assert not df1.equals(different)\n\n # different index\n different_index = -index\n different = df2.set_index(different_index)\n assert not df1.equals(different)\n\n # different columns\n different = df2.copy()\n different.columns = df2.columns[::-1]\n assert not df1.equals(different)\n\n # DatetimeIndex\n index = date_range("2000-1-1", periods=10, freq="min")\n df1 = df1.set_index(index)\n df2 = df1.copy()\n assert df1.equals(df2)\n\n # MultiIndex\n df3 = df1.set_index(["text"], append=True)\n df2 = df1.set_index(["text"], append=True)\n assert df3.equals(df2)\n\n df2 = df1.set_index(["floats"], append=True)\n assert not df3.equals(df2)\n\n # NaN in index\n df3 = df1.set_index(["floats"], append=True)\n df2 = df1.set_index(["floats"], append=True)\n assert df3.equals(df2)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_equals.py
test_equals.py
Python
2,996
0.95
0.058824
0.180556
react-lib
391
2024-11-27T11:05:19.626047
GPL-3.0
true
af24648c684d2179f3424bf840f72f44
import re\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\ndef test_error():\n df = pd.DataFrame(\n {"A": pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list("abcd")), "B": 1}\n )\n with pytest.raises(\n ValueError, match="column must be a scalar, tuple, or list thereof"\n ):\n df.explode([list("AA")])\n\n with pytest.raises(ValueError, match="column must be unique"):\n df.explode(list("AA"))\n\n df.columns = list("AA")\n with pytest.raises(\n ValueError,\n match=re.escape("DataFrame columns must be unique. Duplicate columns: ['A']"),\n ):\n df.explode("A")\n\n\n@pytest.mark.parametrize(\n "input_subset, error_message",\n [\n (\n list("AC"),\n "columns must have matching element counts",\n ),\n (\n [],\n "column must be nonempty",\n ),\n (\n list("AC"),\n "columns must have matching element counts",\n ),\n ],\n)\ndef test_error_multi_columns(input_subset, error_message):\n # GH 39240\n df = pd.DataFrame(\n {\n "A": [[0, 1, 2], np.nan, [], (3, 4)],\n "B": 1,\n "C": [["a", "b", "c"], "foo", [], ["d", "e", "f"]],\n },\n index=list("abcd"),\n )\n with pytest.raises(ValueError, match=error_message):\n df.explode(input_subset)\n\n\n@pytest.mark.parametrize(\n "scalar",\n ["a", 0, 1.5, pd.Timedelta("1 days"), pd.Timestamp("2019-12-31")],\n)\ndef test_basic(scalar):\n df = pd.DataFrame(\n {scalar: pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list("abcd")), "B": 1}\n )\n result = df.explode(scalar)\n expected = pd.DataFrame(\n {\n scalar: pd.Series(\n [0, 1, 2, np.nan, np.nan, 3, 4], index=list("aaabcdd"), dtype=object\n ),\n "B": 1,\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_multi_index_rows():\n df = pd.DataFrame(\n {"A": np.array([[0, 1, 2], np.nan, [], (3, 4)], dtype=object), "B": 1},\n index=pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), ("b", 2)]),\n )\n\n result = df.explode("A")\n expected = pd.DataFrame(\n {\n "A": pd.Series(\n [0, 1, 2, np.nan, np.nan, 3, 4],\n index=pd.MultiIndex.from_tuples(\n [\n ("a", 1),\n ("a", 1),\n ("a", 1),\n ("a", 2),\n ("b", 1),\n ("b", 2),\n ("b", 2),\n ]\n ),\n dtype=object,\n ),\n "B": 1,\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_multi_index_columns():\n df = pd.DataFrame(\n {("A", 1): np.array([[0, 1, 2], np.nan, [], (3, 4)], dtype=object), ("A", 2): 1}\n )\n\n result = df.explode(("A", 1))\n expected = pd.DataFrame(\n {\n ("A", 1): pd.Series(\n [0, 1, 2, np.nan, np.nan, 3, 4],\n index=pd.Index([0, 0, 0, 1, 2, 3, 3]),\n dtype=object,\n ),\n ("A", 2): 1,\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_usecase():\n # explode a single column\n # gh-10511\n df = pd.DataFrame(\n [[11, range(5), 10], [22, range(3), 20]], columns=list("ABC")\n ).set_index("C")\n result = df.explode("B")\n\n expected = pd.DataFrame(\n {\n "A": [11, 11, 11, 11, 11, 22, 22, 22],\n "B": np.array([0, 1, 2, 3, 4, 0, 1, 2], dtype=object),\n "C": [10, 10, 10, 10, 10, 20, 20, 20],\n },\n columns=list("ABC"),\n ).set_index("C")\n\n tm.assert_frame_equal(result, expected)\n\n # gh-8517\n df = pd.DataFrame(\n [["2014-01-01", "Alice", "A B"], ["2014-01-02", "Bob", "C D"]],\n columns=["dt", "name", "text"],\n )\n result = df.assign(text=df.text.str.split(" ")).explode("text")\n expected = pd.DataFrame(\n [\n ["2014-01-01", "Alice", "A"],\n ["2014-01-01", "Alice", "B"],\n ["2014-01-02", "Bob", "C"],\n ["2014-01-02", "Bob", "D"],\n ],\n columns=["dt", "name", "text"],\n index=[0, 0, 1, 1],\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "input_dict, input_index, expected_dict, expected_index",\n [\n (\n {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]},\n [0, 0],\n {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]},\n [0, 0, 0, 0],\n ),\n (\n {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]},\n pd.Index([0, 0], name="my_index"),\n {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]},\n pd.Index([0, 0, 0, 0], name="my_index"),\n ),\n (\n {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]},\n pd.MultiIndex.from_arrays(\n [[0, 0], [1, 1]], names=["my_first_index", "my_second_index"]\n ),\n {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]},\n pd.MultiIndex.from_arrays(\n [[0, 0, 0, 0], [1, 1, 1, 1]],\n names=["my_first_index", "my_second_index"],\n ),\n ),\n (\n {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]},\n pd.MultiIndex.from_arrays([[0, 0], [1, 1]], names=["my_index", None]),\n {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]},\n pd.MultiIndex.from_arrays(\n [[0, 0, 0, 0], [1, 1, 1, 1]], names=["my_index", None]\n ),\n ),\n ],\n)\ndef test_duplicate_index(input_dict, input_index, expected_dict, expected_index):\n # GH 28005\n df = pd.DataFrame(input_dict, index=input_index, dtype=object)\n result = df.explode("col1")\n expected = pd.DataFrame(expected_dict, index=expected_index, dtype=object)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_ignore_index():\n # GH 34932\n df = pd.DataFrame({"id": range(0, 20, 10), "values": [list("ab"), list("cd")]})\n result = df.explode("values", ignore_index=True)\n expected = pd.DataFrame(\n {"id": [0, 0, 10, 10], "values": list("abcd")}, index=[0, 1, 2, 3]\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_explode_sets():\n # https://github.com/pandas-dev/pandas/issues/35614\n df = pd.DataFrame({"a": [{"x", "y"}], "b": [1]}, index=[1])\n result = df.explode(column="a").sort_values(by="a")\n expected = pd.DataFrame({"a": ["x", "y"], "b": [1, 1]}, index=[1, 1])\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "input_subset, expected_dict, expected_index",\n [\n (\n list("AC"),\n {\n "A": pd.Series(\n [0, 1, 2, np.nan, np.nan, 3, 4, np.nan],\n index=list("aaabcdde"),\n dtype=object,\n ),\n "B": 1,\n "C": ["a", "b", "c", "foo", np.nan, "d", "e", np.nan],\n },\n list("aaabcdde"),\n ),\n (\n list("A"),\n {\n "A": pd.Series(\n [0, 1, 2, np.nan, np.nan, 3, 4, np.nan],\n index=list("aaabcdde"),\n dtype=object,\n ),\n "B": 1,\n "C": [\n ["a", "b", "c"],\n ["a", "b", "c"],\n ["a", "b", "c"],\n "foo",\n [],\n ["d", "e"],\n ["d", "e"],\n np.nan,\n ],\n },\n list("aaabcdde"),\n ),\n ],\n)\ndef test_multi_columns(input_subset, expected_dict, expected_index):\n # GH 39240\n df = pd.DataFrame(\n {\n "A": [[0, 1, 2], np.nan, [], (3, 4), np.nan],\n "B": 1,\n "C": [["a", "b", "c"], "foo", [], ["d", "e"], np.nan],\n },\n index=list("abcde"),\n )\n result = df.explode(input_subset)\n expected = pd.DataFrame(expected_dict, expected_index)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_multi_columns_nan_empty():\n # GH 46084\n df = pd.DataFrame(\n {\n "A": [[0, 1], [5], [], [2, 3]],\n "B": [9, 8, 7, 6],\n "C": [[1, 2], np.nan, [], [3, 4]],\n }\n )\n result = df.explode(["A", "C"])\n expected = pd.DataFrame(\n {\n "A": np.array([0, 1, 5, np.nan, 2, 3], dtype=object),\n "B": [9, 9, 8, 7, 6, 6],\n "C": np.array([1, 2, np.nan, np.nan, 3, 4], dtype=object),\n },\n index=[0, 0, 1, 2, 3, 3],\n )\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_explode.py
test_explode.py
Python
8,824
0.95
0.036304
0.033088
node-utils
774
2024-04-04T23:56:37.222351
MIT
true
f44583c68ee19d5953b115cf281d8e17
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n Categorical,\n DataFrame,\n DatetimeIndex,\n NaT,\n PeriodIndex,\n Series,\n TimedeltaIndex,\n Timestamp,\n date_range,\n to_datetime,\n)\nimport pandas._testing as tm\nfrom pandas.tests.frame.common import _check_mixed_float\n\n\nclass TestFillNA:\n def test_fillna_dict_inplace_nonunique_columns(\n self, using_copy_on_write, warn_copy_on_write\n ):\n df = DataFrame(\n {"A": [np.nan] * 3, "B": [NaT, Timestamp(1), NaT], "C": [np.nan, "foo", 2]}\n )\n df.columns = ["A", "A", "A"]\n orig = df[:]\n\n # TODO(CoW-warn) better warning message\n with tm.assert_cow_warning(warn_copy_on_write):\n df.fillna({"A": 2}, inplace=True)\n # The first and third columns can be set inplace, while the second cannot.\n\n expected = DataFrame(\n {"A": [2.0] * 3, "B": [2, Timestamp(1), 2], "C": [2, "foo", 2]}\n )\n expected.columns = ["A", "A", "A"]\n tm.assert_frame_equal(df, expected)\n\n # TODO: what's the expected/desired behavior with CoW?\n if not using_copy_on_write:\n assert tm.shares_memory(df.iloc[:, 0], orig.iloc[:, 0])\n assert not tm.shares_memory(df.iloc[:, 1], orig.iloc[:, 1])\n if not using_copy_on_write:\n assert tm.shares_memory(df.iloc[:, 2], orig.iloc[:, 2])\n\n @td.skip_array_manager_not_yet_implemented\n def test_fillna_on_column_view(self, using_copy_on_write):\n # GH#46149 avoid unnecessary copies\n arr = np.full((40, 50), np.nan)\n df = DataFrame(arr, copy=False)\n\n if using_copy_on_write:\n with tm.raises_chained_assignment_error():\n df[0].fillna(-1, inplace=True)\n assert np.isnan(arr[:, 0]).all()\n else:\n with tm.assert_produces_warning(FutureWarning, match="inplace method"):\n df[0].fillna(-1, inplace=True)\n assert (arr[:, 0] == -1).all()\n\n # i.e. we didn't create a new 49-column block\n assert len(df._mgr.arrays) == 1\n assert np.shares_memory(df.values, arr)\n\n def test_fillna_datetime(self, datetime_frame):\n tf = datetime_frame\n tf.loc[tf.index[:5], "A"] = np.nan\n tf.loc[tf.index[-5:], "A"] = np.nan\n\n zero_filled = datetime_frame.fillna(0)\n assert (zero_filled.loc[zero_filled.index[:5], "A"] == 0).all()\n\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n padded = datetime_frame.fillna(method="pad")\n assert np.isnan(padded.loc[padded.index[:5], "A"]).all()\n assert (\n padded.loc[padded.index[-5:], "A"] == padded.loc[padded.index[-5], "A"]\n ).all()\n\n msg = "Must specify a fill 'value' or 'method'"\n with pytest.raises(ValueError, match=msg):\n datetime_frame.fillna()\n msg = "Cannot specify both 'value' and 'method'"\n with pytest.raises(ValueError, match=msg):\n datetime_frame.fillna(5, method="ffill")\n\n def test_fillna_mixed_type(self, float_string_frame):\n mf = float_string_frame\n mf.loc[mf.index[5:20], "foo"] = np.nan\n mf.loc[mf.index[-10:], "A"] = np.nan\n # TODO: make stronger assertion here, GH 25640\n mf.fillna(value=0)\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n mf.fillna(method="pad")\n\n def test_fillna_mixed_float(self, mixed_float_frame):\n # mixed numeric (but no float16)\n mf = mixed_float_frame.reindex(columns=["A", "B", "D"])\n mf.loc[mf.index[-10:], "A"] = np.nan\n result = mf.fillna(value=0)\n _check_mixed_float(result, dtype={"C": None})\n\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = mf.fillna(method="pad")\n _check_mixed_float(result, dtype={"C": None})\n\n def test_fillna_empty(self, using_copy_on_write):\n if using_copy_on_write:\n pytest.skip("condition is unnecessary complex and is deprecated anyway")\n # empty frame (GH#2778)\n df = DataFrame(columns=["x"])\n for m in ["pad", "backfill"]:\n msg = "Series.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n df.x.fillna(method=m, inplace=True)\n df.x.fillna(method=m)\n\n def test_fillna_different_dtype(self):\n # with different dtype (GH#3386)\n df = DataFrame(\n [["a", "a", np.nan, "a"], ["b", "b", np.nan, "b"], ["c", "c", np.nan, "c"]]\n )\n\n result = df.fillna({2: "foo"})\n expected = DataFrame(\n [["a", "a", "foo", "a"], ["b", "b", "foo", "b"], ["c", "c", "foo", "c"]]\n )\n # column is originally float (all-NaN) -> filling with string gives object dtype\n expected[2] = expected[2].astype("object")\n tm.assert_frame_equal(result, expected)\n\n return_value = df.fillna({2: "foo"}, inplace=True)\n tm.assert_frame_equal(df, expected)\n assert return_value is None\n\n def test_fillna_limit_and_value(self):\n # limit and value\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 3)))\n df.iloc[2:7, 0] = np.nan\n df.iloc[3:5, 2] = np.nan\n\n expected = df.copy()\n expected.iloc[2, 0] = 999\n expected.iloc[3, 2] = 999\n result = df.fillna(999, limit=1)\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_datelike(self):\n # with datelike\n # GH#6344\n df = DataFrame(\n {\n "Date": [NaT, Timestamp("2014-1-1")],\n "Date2": [Timestamp("2013-1-1"), NaT],\n }\n )\n\n expected = df.copy()\n expected["Date"] = expected["Date"].fillna(df.loc[df.index[0], "Date2"])\n result = df.fillna(value={"Date": df["Date2"]})\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_tzaware(self):\n # with timezone\n # GH#15855\n df = DataFrame({"A": [Timestamp("2012-11-11 00:00:00+01:00"), NaT]})\n exp = DataFrame(\n {\n "A": [\n Timestamp("2012-11-11 00:00:00+01:00"),\n Timestamp("2012-11-11 00:00:00+01:00"),\n ]\n }\n )\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res = df.fillna(method="pad")\n tm.assert_frame_equal(res, exp)\n\n df = DataFrame({"A": [NaT, Timestamp("2012-11-11 00:00:00+01:00")]})\n exp = DataFrame(\n {\n "A": [\n Timestamp("2012-11-11 00:00:00+01:00"),\n Timestamp("2012-11-11 00:00:00+01:00"),\n ]\n }\n )\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res = df.fillna(method="bfill")\n tm.assert_frame_equal(res, exp)\n\n def test_fillna_tzaware_different_column(self):\n # with timezone in another column\n # GH#15522\n df = DataFrame(\n {\n "A": date_range("20130101", periods=4, tz="US/Eastern"),\n "B": [1, 2, np.nan, np.nan],\n }\n )\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.fillna(method="pad")\n expected = DataFrame(\n {\n "A": date_range("20130101", periods=4, tz="US/Eastern"),\n "B": [1.0, 2.0, 2.0, 2.0],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_na_actions_categorical(self):\n cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3])\n vals = ["a", "b", np.nan, "d"]\n df = DataFrame({"cats": cat, "vals": vals})\n cat2 = Categorical([1, 2, 3, 3], categories=[1, 2, 3])\n vals2 = ["a", "b", "b", "d"]\n df_exp_fill = DataFrame({"cats": cat2, "vals": vals2})\n cat3 = Categorical([1, 2, 3], categories=[1, 2, 3])\n vals3 = ["a", "b", np.nan]\n df_exp_drop_cats = DataFrame({"cats": cat3, "vals": vals3})\n cat4 = Categorical([1, 2], categories=[1, 2, 3])\n vals4 = ["a", "b"]\n df_exp_drop_all = DataFrame({"cats": cat4, "vals": vals4})\n\n # fillna\n res = df.fillna(value={"cats": 3, "vals": "b"})\n tm.assert_frame_equal(res, df_exp_fill)\n\n msg = "Cannot setitem on a Categorical with a new category"\n with pytest.raises(TypeError, match=msg):\n df.fillna(value={"cats": 4, "vals": "c"})\n\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res = df.fillna(method="pad")\n tm.assert_frame_equal(res, df_exp_fill)\n\n # dropna\n res = df.dropna(subset=["cats"])\n tm.assert_frame_equal(res, df_exp_drop_cats)\n\n res = df.dropna()\n tm.assert_frame_equal(res, df_exp_drop_all)\n\n # make sure that fillna takes missing values into account\n c = Categorical([np.nan, "b", np.nan], categories=["a", "b"])\n df = DataFrame({"cats": c, "vals": [1, 2, 3]})\n\n cat_exp = Categorical(["a", "b", "a"], categories=["a", "b"])\n df_exp = DataFrame({"cats": cat_exp, "vals": [1, 2, 3]})\n\n res = df.fillna("a")\n tm.assert_frame_equal(res, df_exp)\n\n def test_fillna_categorical_nan(self):\n # GH#14021\n # np.nan should always be a valid filler\n cat = Categorical([np.nan, 2, np.nan])\n val = Categorical([np.nan, np.nan, np.nan])\n df = DataFrame({"cats": cat, "vals": val})\n\n # GH#32950 df.median() is poorly behaved because there is no\n # Categorical.median\n median = Series({"cats": 2.0, "vals": np.nan})\n\n res = df.fillna(median)\n v_exp = [np.nan, np.nan, np.nan]\n df_exp = DataFrame({"cats": [2, 2, 2], "vals": v_exp}, dtype="category")\n tm.assert_frame_equal(res, df_exp)\n\n result = df.cats.fillna(np.nan)\n tm.assert_series_equal(result, df.cats)\n\n result = df.vals.fillna(np.nan)\n tm.assert_series_equal(result, df.vals)\n\n idx = DatetimeIndex(\n ["2011-01-01 09:00", "2016-01-01 23:45", "2011-01-01 09:00", NaT, NaT]\n )\n df = DataFrame({"a": Categorical(idx)})\n tm.assert_frame_equal(df.fillna(value=NaT), df)\n\n idx = PeriodIndex(["2011-01", "2011-01", "2011-01", NaT, NaT], freq="M")\n df = DataFrame({"a": Categorical(idx)})\n tm.assert_frame_equal(df.fillna(value=NaT), df)\n\n idx = TimedeltaIndex(["1 days", "2 days", "1 days", NaT, NaT])\n df = DataFrame({"a": Categorical(idx)})\n tm.assert_frame_equal(df.fillna(value=NaT), df)\n\n def test_fillna_downcast(self):\n # GH#15277\n # infer int64 from float64\n df = DataFrame({"a": [1.0, np.nan]})\n msg = "The 'downcast' keyword in fillna is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.fillna(0, downcast="infer")\n expected = DataFrame({"a": [1, 0]})\n tm.assert_frame_equal(result, expected)\n\n # infer int64 from float64 when fillna value is a dict\n df = DataFrame({"a": [1.0, np.nan]})\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.fillna({"a": 0}, downcast="infer")\n expected = DataFrame({"a": [1, 0]})\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_downcast_false(self, frame_or_series):\n # GH#45603 preserve object dtype with downcast=False\n obj = frame_or_series([1, 2, 3], dtype="object")\n msg = "The 'downcast' keyword in fillna"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = obj.fillna("", downcast=False)\n tm.assert_equal(result, obj)\n\n def test_fillna_downcast_noop(self, frame_or_series):\n # GH#45423\n # Two relevant paths:\n # 1) not _can_hold_na (e.g. integer)\n # 2) _can_hold_na + noop + not can_hold_element\n\n obj = frame_or_series([1, 2, 3], dtype=np.int64)\n\n msg = "The 'downcast' keyword in fillna"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n # GH#40988\n res = obj.fillna("foo", downcast=np.dtype(np.int32))\n expected = obj.astype(np.int32)\n tm.assert_equal(res, expected)\n\n obj2 = obj.astype(np.float64)\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res2 = obj2.fillna("foo", downcast="infer")\n expected2 = obj # get back int64\n tm.assert_equal(res2, expected2)\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n # GH#40988\n res3 = obj2.fillna("foo", downcast=np.dtype(np.int32))\n tm.assert_equal(res3, expected)\n\n @pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]])\n def test_fillna_dictlike_value_duplicate_colnames(self, columns):\n # GH#43476\n df = DataFrame(np.nan, index=[0, 1], columns=columns)\n with tm.assert_produces_warning(None):\n result = df.fillna({"A": 0})\n\n expected = df.copy()\n expected["A"] = 0.0\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_dtype_conversion(self, using_infer_string):\n # make sure that fillna on an empty frame works\n df = DataFrame(index=["A", "B", "C"], columns=[1, 2, 3, 4, 5])\n result = df.dtypes\n expected = Series([np.dtype("object")] * 5, index=[1, 2, 3, 4, 5])\n tm.assert_series_equal(result, expected)\n\n msg = "Downcasting object dtype arrays"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.fillna(1)\n expected = DataFrame(1, index=["A", "B", "C"], columns=[1, 2, 3, 4, 5])\n tm.assert_frame_equal(result, expected)\n\n # empty block\n df = DataFrame(index=range(3), columns=["A", "B"], dtype="float64")\n result = df.fillna("nan")\n expected = DataFrame("nan", index=range(3), columns=["A", "B"], dtype=object)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("val", ["", 1, np.nan, 1.0])\n def test_fillna_dtype_conversion_equiv_replace(self, val):\n df = DataFrame({"A": [1, np.nan], "B": [1.0, 2.0]})\n expected = df.replace(np.nan, val)\n result = df.fillna(val)\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_datetime_columns(self):\n # GH#7095\n df = DataFrame(\n {\n "A": [-1, -2, np.nan],\n "B": date_range("20130101", periods=3),\n "C": ["foo", "bar", None],\n "D": ["foo2", "bar2", None],\n },\n index=date_range("20130110", periods=3),\n )\n result = df.fillna("?")\n expected = DataFrame(\n {\n "A": [-1, -2, "?"],\n "B": date_range("20130101", periods=3),\n "C": ["foo", "bar", "?"],\n "D": ["foo2", "bar2", "?"],\n },\n index=date_range("20130110", periods=3),\n )\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame(\n {\n "A": [-1, -2, np.nan],\n "B": [Timestamp("2013-01-01"), Timestamp("2013-01-02"), NaT],\n "C": ["foo", "bar", None],\n "D": ["foo2", "bar2", None],\n },\n index=date_range("20130110", periods=3),\n )\n result = df.fillna("?")\n expected = DataFrame(\n {\n "A": [-1, -2, "?"],\n "B": [Timestamp("2013-01-01"), Timestamp("2013-01-02"), "?"],\n "C": ["foo", "bar", "?"],\n "D": ["foo2", "bar2", "?"],\n },\n index=date_range("20130110", periods=3),\n )\n tm.assert_frame_equal(result, expected)\n\n def test_ffill(self, datetime_frame):\n datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan\n datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan\n\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n alt = datetime_frame.fillna(method="ffill")\n tm.assert_frame_equal(datetime_frame.ffill(), alt)\n\n def test_bfill(self, datetime_frame):\n datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan\n datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan\n\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n alt = datetime_frame.fillna(method="bfill")\n\n tm.assert_frame_equal(datetime_frame.bfill(), alt)\n\n def test_frame_pad_backfill_limit(self):\n index = np.arange(10)\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=index)\n\n result = df[:2].reindex(index, method="pad", limit=5)\n\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n expected = df[:2].reindex(index).fillna(method="pad")\n expected.iloc[-3:] = np.nan\n tm.assert_frame_equal(result, expected)\n\n result = df[-2:].reindex(index, method="backfill", limit=5)\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n expected = df[-2:].reindex(index).fillna(method="backfill")\n expected.iloc[:3] = np.nan\n tm.assert_frame_equal(result, expected)\n\n def test_frame_fillna_limit(self):\n index = np.arange(10)\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=index)\n\n result = df[:2].reindex(index)\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = result.fillna(method="pad", limit=5)\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n expected = df[:2].reindex(index).fillna(method="pad")\n expected.iloc[-3:] = np.nan\n tm.assert_frame_equal(result, expected)\n\n result = df[-2:].reindex(index)\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = result.fillna(method="backfill", limit=5)\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n expected = df[-2:].reindex(index).fillna(method="backfill")\n expected.iloc[:3] = np.nan\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_skip_certain_blocks(self):\n # don't try to fill boolean, int blocks\n\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)).astype(int))\n\n # it works!\n df.fillna(np.nan)\n\n @pytest.mark.parametrize("type", [int, float])\n def test_fillna_positive_limit(self, type):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype(type)\n\n msg = "Limit must be greater than 0"\n with pytest.raises(ValueError, match=msg):\n df.fillna(0, limit=-5)\n\n @pytest.mark.parametrize("type", [int, float])\n def test_fillna_integer_limit(self, type):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype(type)\n\n msg = "Limit must be an integer"\n with pytest.raises(ValueError, match=msg):\n df.fillna(0, limit=0.5)\n\n def test_fillna_inplace(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))\n df.loc[:4, 1] = np.nan\n df.loc[-4:, 3] = np.nan\n\n expected = df.fillna(value=0)\n assert expected is not df\n\n df.fillna(value=0, inplace=True)\n tm.assert_frame_equal(df, expected)\n\n expected = df.fillna(value={0: 0}, inplace=True)\n assert expected is None\n\n df.loc[:4, 1] = np.nan\n df.loc[-4:, 3] = np.nan\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n expected = df.fillna(method="ffill")\n assert expected is not df\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n df.fillna(method="ffill", inplace=True)\n tm.assert_frame_equal(df, expected)\n\n def test_fillna_dict_series(self):\n df = DataFrame(\n {\n "a": [np.nan, 1, 2, np.nan, np.nan],\n "b": [1, 2, 3, np.nan, np.nan],\n "c": [np.nan, 1, 2, 3, 4],\n }\n )\n\n result = df.fillna({"a": 0, "b": 5})\n\n expected = df.copy()\n expected["a"] = expected["a"].fillna(0)\n expected["b"] = expected["b"].fillna(5)\n tm.assert_frame_equal(result, expected)\n\n # it works\n result = df.fillna({"a": 0, "b": 5, "d": 7})\n\n # Series treated same as dict\n result = df.fillna(df.max())\n expected = df.fillna(df.max().to_dict())\n tm.assert_frame_equal(result, expected)\n\n # disable this for now\n with pytest.raises(NotImplementedError, match="column by column"):\n df.fillna(df.max(1), axis=1)\n\n def test_fillna_dataframe(self):\n # GH#8377\n df = DataFrame(\n {\n "a": [np.nan, 1, 2, np.nan, np.nan],\n "b": [1, 2, 3, np.nan, np.nan],\n "c": [np.nan, 1, 2, 3, 4],\n },\n index=list("VWXYZ"),\n )\n\n # df2 may have different index and columns\n df2 = DataFrame(\n {\n "a": [np.nan, 10, 20, 30, 40],\n "b": [50, 60, 70, 80, 90],\n "foo": ["bar"] * 5,\n },\n index=list("VWXuZ"),\n )\n\n result = df.fillna(df2)\n\n # only those columns and indices which are shared get filled\n expected = DataFrame(\n {\n "a": [np.nan, 1, 2, np.nan, 40],\n "b": [1, 2, 3, np.nan, 90],\n "c": [np.nan, 1, 2, 3, 4],\n },\n index=list("VWXYZ"),\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_columns(self):\n arr = np.random.default_rng(2).standard_normal((10, 10))\n arr[:, ::2] = np.nan\n df = DataFrame(arr)\n\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.fillna(method="ffill", axis=1)\n with tm.assert_produces_warning(FutureWarning, match=msg):\n expected = df.T.fillna(method="pad").T\n tm.assert_frame_equal(result, expected)\n\n df.insert(6, "foo", 5)\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.fillna(method="ffill", axis=1)\n with tm.assert_produces_warning(FutureWarning, match=msg):\n expected = df.astype(float).fillna(method="ffill", axis=1)\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_invalid_method(self, float_frame):\n with pytest.raises(ValueError, match="ffil"):\n float_frame.fillna(method="ffil")\n\n def test_fillna_invalid_value(self, float_frame):\n # list\n msg = '"value" parameter must be a scalar or dict, but you passed a "{}"'\n with pytest.raises(TypeError, match=msg.format("list")):\n float_frame.fillna([1, 2])\n # tuple\n with pytest.raises(TypeError, match=msg.format("tuple")):\n float_frame.fillna((1, 2))\n # frame with series\n msg = (\n '"value" parameter must be a scalar, dict or Series, but you '\n 'passed a "DataFrame"'\n )\n with pytest.raises(TypeError, match=msg):\n float_frame.iloc[:, 0].fillna(float_frame)\n\n def test_fillna_col_reordering(self):\n cols = ["COL." + str(i) for i in range(5, 0, -1)]\n data = np.random.default_rng(2).random((20, 5))\n df = DataFrame(index=range(20), columns=cols, data=data)\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n filled = df.fillna(method="ffill")\n assert df.columns.tolist() == filled.columns.tolist()\n\n def test_fill_empty(self, float_frame):\n df = float_frame.reindex(columns=[])\n result = df.fillna(value=0)\n tm.assert_frame_equal(result, df)\n\n def test_fillna_downcast_dict(self):\n # GH#40809\n df = DataFrame({"col1": [1, np.nan]})\n\n msg = "The 'downcast' keyword in fillna"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.fillna({"col1": 2}, downcast={"col1": "int64"})\n expected = DataFrame({"col1": [1, 2]})\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_with_columns_and_limit(self):\n # GH40989\n df = DataFrame(\n [\n [np.nan, 2, np.nan, 0],\n [3, 4, np.nan, 1],\n [np.nan, np.nan, np.nan, 5],\n [np.nan, 3, np.nan, 4],\n ],\n columns=list("ABCD"),\n )\n result = df.fillna(axis=1, value=100, limit=1)\n result2 = df.fillna(axis=1, value=100, limit=2)\n\n expected = DataFrame(\n {\n "A": Series([100, 3, 100, 100], dtype="float64"),\n "B": [2, 4, np.nan, 3],\n "C": [np.nan, 100, np.nan, np.nan],\n "D": Series([0, 1, 5, 4], dtype="float64"),\n },\n index=[0, 1, 2, 3],\n )\n expected2 = DataFrame(\n {\n "A": Series([100, 3, 100, 100], dtype="float64"),\n "B": Series([2, 4, 100, 3], dtype="float64"),\n "C": [100, 100, np.nan, 100],\n "D": Series([0, 1, 5, 4], dtype="float64"),\n },\n index=[0, 1, 2, 3],\n )\n\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(result2, expected2)\n\n def test_fillna_datetime_inplace(self):\n # GH#48863\n df = DataFrame(\n {\n "date1": to_datetime(["2018-05-30", None]),\n "date2": to_datetime(["2018-09-30", None]),\n }\n )\n expected = df.copy()\n df.fillna(np.nan, inplace=True)\n tm.assert_frame_equal(df, expected)\n\n def test_fillna_inplace_with_columns_limit_and_value(self):\n # GH40989\n df = DataFrame(\n [\n [np.nan, 2, np.nan, 0],\n [3, 4, np.nan, 1],\n [np.nan, np.nan, np.nan, 5],\n [np.nan, 3, np.nan, 4],\n ],\n columns=list("ABCD"),\n )\n\n expected = df.fillna(axis=1, value=100, limit=1)\n assert expected is not df\n\n df.fillna(axis=1, value=100, limit=1, inplace=True)\n tm.assert_frame_equal(df, expected)\n\n @td.skip_array_manager_invalid_test\n @pytest.mark.parametrize("val", [-1, {"x": -1, "y": -1}])\n def test_inplace_dict_update_view(\n self, val, using_copy_on_write, warn_copy_on_write\n ):\n # GH#47188\n df = DataFrame({"x": [np.nan, 2], "y": [np.nan, 2]})\n df_orig = df.copy()\n result_view = df[:]\n with tm.assert_cow_warning(warn_copy_on_write):\n df.fillna(val, inplace=True)\n expected = DataFrame({"x": [-1, 2.0], "y": [-1.0, 2]})\n tm.assert_frame_equal(df, expected)\n if using_copy_on_write:\n tm.assert_frame_equal(result_view, df_orig)\n else:\n tm.assert_frame_equal(result_view, expected)\n\n def test_single_block_df_with_horizontal_axis(self):\n # GH 47713\n df = DataFrame(\n {\n "col1": [5, 0, np.nan, 10, np.nan],\n "col2": [7, np.nan, np.nan, 5, 3],\n "col3": [12, np.nan, 1, 2, 0],\n "col4": [np.nan, 1, 1, np.nan, 18],\n }\n )\n result = df.fillna(50, limit=1, axis=1)\n expected = DataFrame(\n [\n [5.0, 7.0, 12.0, 50.0],\n [0.0, 50.0, np.nan, 1.0],\n [50.0, np.nan, 1.0, 1.0],\n [10.0, 5.0, 2.0, 50.0],\n [50.0, 3.0, 0.0, 18.0],\n ],\n columns=["col1", "col2", "col3", "col4"],\n )\n tm.assert_frame_equal(result, expected)\n\n def test_fillna_with_multi_index_frame(self):\n # GH 47649\n pdf = DataFrame(\n {\n ("x", "a"): [np.nan, 2.0, 3.0],\n ("x", "b"): [1.0, 2.0, np.nan],\n ("y", "c"): [1.0, 2.0, np.nan],\n }\n )\n expected = DataFrame(\n {\n ("x", "a"): [-1.0, 2.0, 3.0],\n ("x", "b"): [1.0, 2.0, -1.0],\n ("y", "c"): [1.0, 2.0, np.nan],\n }\n )\n tm.assert_frame_equal(pdf.fillna({"x": -1}), expected)\n tm.assert_frame_equal(pdf.fillna({"x": -1, ("x", "b"): -2}), expected)\n\n expected = DataFrame(\n {\n ("x", "a"): [-1.0, 2.0, 3.0],\n ("x", "b"): [1.0, 2.0, -2.0],\n ("y", "c"): [1.0, 2.0, np.nan],\n }\n )\n tm.assert_frame_equal(pdf.fillna({("x", "b"): -2, "x": -1}), expected)\n\n\ndef test_fillna_nonconsolidated_frame():\n # https://github.com/pandas-dev/pandas/issues/36495\n df = DataFrame(\n [\n [1, 1, 1, 1.0],\n [2, 2, 2, 2.0],\n [3, 3, 3, 3.0],\n ],\n columns=["i1", "i2", "i3", "f1"],\n )\n df_nonconsol = df.pivot(index="i1", columns="i2")\n result = df_nonconsol.fillna(0)\n assert result.isna().sum().sum() == 0\n\n\ndef test_fillna_nones_inplace():\n # GH 48480\n df = DataFrame(\n [[None, None], [None, None]],\n columns=["A", "B"],\n )\n msg = "Downcasting object dtype arrays"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n df.fillna(value={"A": 1, "B": 2}, inplace=True)\n\n expected = DataFrame([[1, 2], [1, 2]], columns=["A", "B"])\n tm.assert_frame_equal(df, expected)\n\n\n@pytest.mark.parametrize("func", ["pad", "backfill"])\ndef test_pad_backfill_deprecated(func):\n # GH#33396\n df = DataFrame({"a": [1, 2, 3]})\n with tm.assert_produces_warning(FutureWarning):\n getattr(df, func)()\n\n\n@pytest.mark.parametrize(\n "data, expected_data, method, kwargs",\n (\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan],\n "ffill",\n {"limit_area": "inside"},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan],\n "ffill",\n {"limit_area": "inside", "limit": 1},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0],\n "ffill",\n {"limit_area": "outside"},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan],\n "ffill",\n {"limit_area": "outside", "limit": 1},\n ),\n (\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n "ffill",\n {"limit_area": "outside", "limit": 1},\n ),\n (\n range(5),\n range(5),\n "ffill",\n {"limit_area": "outside", "limit": 1},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan],\n "bfill",\n {"limit_area": "inside"},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan],\n "bfill",\n {"limit_area": "inside", "limit": 1},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],\n "bfill",\n {"limit_area": "outside"},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],\n "bfill",\n {"limit_area": "outside", "limit": 1},\n ),\n ),\n)\ndef test_ffill_bfill_limit_area(data, expected_data, method, kwargs):\n # GH#56492\n df = DataFrame(data)\n expected = DataFrame(expected_data)\n result = getattr(df, method)(**kwargs)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_fillna.py
test_fillna.py
Python
33,281
0.95
0.0625
0.076628
python-kit
577
2023-08-21T10:17:48.744292
BSD-3-Clause
true
e7cf156618aac3bbbfbdd7d212dc53ba
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\nclass TestDataFrameFilter:\n def test_filter(self, float_frame, float_string_frame):\n # Items\n filtered = float_frame.filter(["A", "B", "E"])\n assert len(filtered.columns) == 2\n assert "E" not in filtered\n\n filtered = float_frame.filter(["A", "B", "E"], axis="columns")\n assert len(filtered.columns) == 2\n assert "E" not in filtered\n\n # Other axis\n idx = float_frame.index[0:4]\n filtered = float_frame.filter(idx, axis="index")\n expected = float_frame.reindex(index=idx)\n tm.assert_frame_equal(filtered, expected)\n\n # like\n fcopy = float_frame.copy()\n fcopy["AA"] = 1\n\n filtered = fcopy.filter(like="A")\n assert len(filtered.columns) == 2\n assert "AA" in filtered\n\n # like with ints in column names\n df = DataFrame(0.0, index=[0, 1, 2], columns=[0, 1, "_A", "_B"])\n filtered = df.filter(like="_")\n assert len(filtered.columns) == 2\n\n # regex with ints in column names\n # from PR #10384\n df = DataFrame(0.0, index=[0, 1, 2], columns=["A1", 1, "B", 2, "C"])\n expected = DataFrame(\n 0.0, index=[0, 1, 2], columns=pd.Index([1, 2], dtype=object)\n )\n filtered = df.filter(regex="^[0-9]+$")\n tm.assert_frame_equal(filtered, expected)\n\n expected = DataFrame(0.0, index=[0, 1, 2], columns=[0, "0", 1, "1"])\n # shouldn't remove anything\n filtered = expected.filter(regex="^[0-9]+$")\n tm.assert_frame_equal(filtered, expected)\n\n # pass in None\n with pytest.raises(TypeError, match="Must pass"):\n float_frame.filter()\n with pytest.raises(TypeError, match="Must pass"):\n float_frame.filter(items=None)\n with pytest.raises(TypeError, match="Must pass"):\n float_frame.filter(axis=1)\n\n # test mutually exclusive arguments\n with pytest.raises(TypeError, match="mutually exclusive"):\n float_frame.filter(items=["one", "three"], regex="e$", like="bbi")\n with pytest.raises(TypeError, match="mutually exclusive"):\n float_frame.filter(items=["one", "three"], regex="e$", axis=1)\n with pytest.raises(TypeError, match="mutually exclusive"):\n float_frame.filter(items=["one", "three"], regex="e$")\n with pytest.raises(TypeError, match="mutually exclusive"):\n float_frame.filter(items=["one", "three"], like="bbi", axis=0)\n with pytest.raises(TypeError, match="mutually exclusive"):\n float_frame.filter(items=["one", "three"], like="bbi")\n\n # objects\n filtered = float_string_frame.filter(like="foo")\n assert "foo" in filtered\n\n # unicode columns, won't ascii-encode\n df = float_frame.rename(columns={"B": "\u2202"})\n filtered = df.filter(like="C")\n assert "C" in filtered\n\n def test_filter_regex_search(self, float_frame):\n fcopy = float_frame.copy()\n fcopy["AA"] = 1\n\n # regex\n filtered = fcopy.filter(regex="[A]+")\n assert len(filtered.columns) == 2\n assert "AA" in filtered\n\n # doesn't have to be at beginning\n df = DataFrame(\n {"aBBa": [1, 2], "BBaBB": [1, 2], "aCCa": [1, 2], "aCCaBB": [1, 2]}\n )\n\n result = df.filter(regex="BB")\n exp = df[[x for x in df.columns if "BB" in x]]\n tm.assert_frame_equal(result, exp)\n\n @pytest.mark.parametrize(\n "name,expected",\n [\n ("a", DataFrame({"a": [1, 2]})),\n ("a", DataFrame({"a": [1, 2]})),\n ("あ", DataFrame({"あ": [3, 4]})),\n ],\n )\n def test_filter_unicode(self, name, expected):\n # GH13101\n df = DataFrame({"a": [1, 2], "あ": [3, 4]})\n\n tm.assert_frame_equal(df.filter(like=name), expected)\n tm.assert_frame_equal(df.filter(regex=name), expected)\n\n @pytest.mark.parametrize("name", ["a", "a"])\n def test_filter_bytestring(self, name):\n # GH13101\n df = DataFrame({b"a": [1, 2], b"b": [3, 4]})\n expected = DataFrame({b"a": [1, 2]})\n\n tm.assert_frame_equal(df.filter(like=name), expected)\n tm.assert_frame_equal(df.filter(regex=name), expected)\n\n def test_filter_corner(self):\n empty = DataFrame()\n\n result = empty.filter([])\n tm.assert_frame_equal(result, empty)\n\n result = empty.filter(like="foo")\n tm.assert_frame_equal(result, empty)\n\n def test_filter_regex_non_string(self):\n # GH#5798 trying to filter on non-string columns should drop,\n # not raise\n df = DataFrame(np.random.default_rng(2).random((3, 2)), columns=["STRING", 123])\n result = df.filter(regex="STRING")\n expected = df[["STRING"]]\n tm.assert_frame_equal(result, expected)\n\n def test_filter_keep_order(self):\n # GH#54980\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})\n result = df.filter(items=["B", "A"])\n expected = df[["B", "A"]]\n tm.assert_frame_equal(result, expected)\n\n def test_filter_different_dtype(self):\n # GH#54980\n df = DataFrame({1: [1, 2, 3], 2: [4, 5, 6]})\n result = df.filter(items=["B", "A"])\n expected = df[[]]\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_filter.py
test_filter.py
Python
5,422
0.95
0.071895
0.152
awesome-app
219
2025-03-27T14:23:48.946070
MIT
true
f9a858b5b23b7fc725015a8e885e1584
"""\nNote: includes tests for `last`\n"""\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n bdate_range,\n date_range,\n)\nimport pandas._testing as tm\n\ndeprecated_msg = "first is deprecated"\nlast_deprecated_msg = "last is deprecated"\n\n\nclass TestFirst:\n def test_first_subset(self, frame_or_series):\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((100, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=date_range("2000-01-01", periods=100, freq="12h"),\n )\n ts = tm.get_obj(ts, frame_or_series)\n with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):\n result = ts.first("10d")\n assert len(result) == 20\n\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((100, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=date_range("2000-01-01", periods=100, freq="D"),\n )\n ts = tm.get_obj(ts, frame_or_series)\n with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):\n result = ts.first("10d")\n assert len(result) == 10\n\n with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):\n result = ts.first("3ME")\n expected = ts[:"3/31/2000"]\n tm.assert_equal(result, expected)\n\n with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):\n result = ts.first("21D")\n expected = ts[:21]\n tm.assert_equal(result, expected)\n\n with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):\n result = ts[:0].first("3ME")\n tm.assert_equal(result, ts[:0])\n\n def test_first_last_raises(self, frame_or_series):\n # GH#20725\n obj = DataFrame([[1, 2, 3], [4, 5, 6]])\n obj = tm.get_obj(obj, frame_or_series)\n\n msg = "'first' only supports a DatetimeIndex index"\n with tm.assert_produces_warning(\n FutureWarning, match=deprecated_msg\n ), pytest.raises(\n TypeError, match=msg\n ): # index is not a DatetimeIndex\n obj.first("1D")\n\n msg = "'last' only supports a DatetimeIndex index"\n with tm.assert_produces_warning(\n FutureWarning, match=last_deprecated_msg\n ), pytest.raises(\n TypeError, match=msg\n ): # index is not a DatetimeIndex\n obj.last("1D")\n\n def test_last_subset(self, frame_or_series):\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((100, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=date_range("2000-01-01", periods=100, freq="12h"),\n )\n ts = tm.get_obj(ts, frame_or_series)\n with tm.assert_produces_warning(FutureWarning, match=last_deprecated_msg):\n result = ts.last("10d")\n assert len(result) == 20\n\n ts = DataFrame(\n np.random.default_rng(2).standard_normal((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=date_range("2000-01-01", periods=30, freq="D"),\n )\n ts = tm.get_obj(ts, frame_or_series)\n with tm.assert_produces_warning(FutureWarning, match=last_deprecated_msg):\n result = ts.last("10d")\n assert len(result) == 10\n\n with tm.assert_produces_warning(FutureWarning, match=last_deprecated_msg):\n result = ts.last("21D")\n expected = ts["2000-01-10":]\n tm.assert_equal(result, expected)\n\n with tm.assert_produces_warning(FutureWarning, match=last_deprecated_msg):\n result = ts.last("21D")\n expected = ts[-21:]\n tm.assert_equal(result, expected)\n\n with tm.assert_produces_warning(FutureWarning, match=last_deprecated_msg):\n result = ts[:0].last("3ME")\n tm.assert_equal(result, ts[:0])\n\n @pytest.mark.parametrize("start, periods", [("2010-03-31", 1), ("2010-03-30", 2)])\n def test_first_with_first_day_last_of_month(self, frame_or_series, start, periods):\n # GH#29623\n x = frame_or_series([1] * 100, index=bdate_range(start, periods=100))\n with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):\n result = x.first("1ME")\n expected = frame_or_series(\n [1] * periods, index=bdate_range(start, periods=periods)\n )\n tm.assert_equal(result, expected)\n\n def test_first_with_first_day_end_of_frq_n_greater_one(self, frame_or_series):\n # GH#29623\n x = frame_or_series([1] * 100, index=bdate_range("2010-03-31", periods=100))\n with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):\n result = x.first("2ME")\n expected = frame_or_series(\n [1] * 23, index=bdate_range("2010-03-31", "2010-04-30")\n )\n tm.assert_equal(result, expected)\n\n def test_empty_not_input(self):\n # GH#51032\n df = DataFrame(index=pd.DatetimeIndex([]))\n with tm.assert_produces_warning(FutureWarning, match=last_deprecated_msg):\n result = df.last(offset=1)\n\n with tm.assert_produces_warning(FutureWarning, match=deprecated_msg):\n result = df.first(offset=1)\n\n tm.assert_frame_equal(df, result)\n assert df is not result\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_first_and_last.py
test_first_and_last.py
Python
5,349
0.95
0.055944
0.032787
vue-tools
115
2024-12-01T07:20:23.806120
BSD-3-Clause
true
81d7f70860db701628615b588cf94ce0
"""\nIncludes test for last_valid_index.\n"""\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n date_range,\n)\n\n\nclass TestFirstValidIndex:\n def test_first_valid_index_single_nan(self, frame_or_series):\n # GH#9752 Series/DataFrame should both return None, not raise\n obj = frame_or_series([np.nan])\n\n assert obj.first_valid_index() is None\n assert obj.iloc[:0].first_valid_index() is None\n\n @pytest.mark.parametrize(\n "empty", [DataFrame(), Series(dtype=object), Series([], index=[], dtype=object)]\n )\n def test_first_valid_index_empty(self, empty):\n # GH#12800\n assert empty.last_valid_index() is None\n assert empty.first_valid_index() is None\n\n @pytest.mark.parametrize(\n "data,idx,expected_first,expected_last",\n [\n ({"A": [1, 2, 3]}, [1, 1, 2], 1, 2),\n ({"A": [1, 2, 3]}, [1, 2, 2], 1, 2),\n ({"A": [1, 2, 3, 4]}, ["d", "d", "d", "d"], "d", "d"),\n ({"A": [1, np.nan, 3]}, [1, 1, 2], 1, 2),\n ({"A": [np.nan, np.nan, 3]}, [1, 1, 2], 2, 2),\n ({"A": [1, np.nan, 3]}, [1, 2, 2], 1, 2),\n ],\n )\n def test_first_last_valid_frame(self, data, idx, expected_first, expected_last):\n # GH#21441\n df = DataFrame(data, index=idx)\n assert expected_first == df.first_valid_index()\n assert expected_last == df.last_valid_index()\n\n @pytest.mark.parametrize(\n "index",\n [Index([str(i) for i in range(20)]), date_range("2020-01-01", periods=20)],\n )\n def test_first_last_valid(self, index):\n mat = np.random.default_rng(2).standard_normal(len(index))\n mat[:5] = np.nan\n mat[-5:] = np.nan\n\n frame = DataFrame({"foo": mat}, index=index)\n assert frame.first_valid_index() == frame.index[5]\n assert frame.last_valid_index() == frame.index[-6]\n\n ser = frame["foo"]\n assert ser.first_valid_index() == frame.index[5]\n assert ser.last_valid_index() == frame.index[-6]\n\n @pytest.mark.parametrize(\n "index",\n [Index([str(i) for i in range(10)]), date_range("2020-01-01", periods=10)],\n )\n def test_first_last_valid_all_nan(self, index):\n # GH#17400: no valid entries\n frame = DataFrame(np.nan, columns=["foo"], index=index)\n\n assert frame.last_valid_index() is None\n assert frame.first_valid_index() is None\n\n ser = frame["foo"]\n assert ser.first_valid_index() is None\n assert ser.last_valid_index() is None\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_first_valid_index.py
test_first_valid_index.py
Python
2,574
0.95
0.115385
0.060606
react-lib
571
2024-07-28T07:35:29.409023
MIT
true
12cbd70db4cfca59de239c1051e7a985
import numpy as np\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n Index,\n Series,\n Timestamp,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import IntervalArray\n\n\nclass TestGetNumericData:\n def test_get_numeric_data_preserve_dtype(self):\n # get the numeric data\n obj = DataFrame({"A": [1, "2", 3.0]}, columns=Index(["A"], dtype="object"))\n result = obj._get_numeric_data()\n expected = DataFrame(dtype=object, index=pd.RangeIndex(3), columns=[])\n tm.assert_frame_equal(result, expected)\n\n def test_get_numeric_data(self, using_infer_string):\n datetime64name = np.dtype("M8[s]").name\n objectname = np.dtype(np.object_).name\n\n df = DataFrame(\n {"a": 1.0, "b": 2, "c": "foo", "f": Timestamp("20010102")},\n index=np.arange(10),\n )\n result = df.dtypes\n expected = Series(\n [\n np.dtype("float64"),\n np.dtype("int64"),\n np.dtype(objectname)\n if not using_infer_string\n else pd.StringDtype(na_value=np.nan),\n np.dtype(datetime64name),\n ],\n index=["a", "b", "c", "f"],\n )\n tm.assert_series_equal(result, expected)\n\n df = DataFrame(\n {\n "a": 1.0,\n "b": 2,\n "c": "foo",\n "d": np.array([1.0] * 10, dtype="float32"),\n "e": np.array([1] * 10, dtype="int32"),\n "f": np.array([1] * 10, dtype="int16"),\n "g": Timestamp("20010102"),\n },\n index=np.arange(10),\n )\n\n result = df._get_numeric_data()\n expected = df.loc[:, ["a", "b", "d", "e", "f"]]\n tm.assert_frame_equal(result, expected)\n\n only_obj = df.loc[:, ["c", "g"]]\n result = only_obj._get_numeric_data()\n expected = df.loc[:, []]\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame.from_dict({"a": [1, 2], "b": ["foo", "bar"], "c": [np.pi, np.e]})\n result = df._get_numeric_data()\n expected = DataFrame.from_dict({"a": [1, 2], "c": [np.pi, np.e]})\n tm.assert_frame_equal(result, expected)\n\n df = result.copy()\n result = df._get_numeric_data()\n expected = df\n tm.assert_frame_equal(result, expected)\n\n def test_get_numeric_data_mixed_dtype(self):\n # numeric and object columns\n\n df = DataFrame(\n {\n "a": [1, 2, 3],\n "b": [True, False, True],\n "c": ["foo", "bar", "baz"],\n "d": [None, None, None],\n "e": [3.14, 0.577, 2.773],\n }\n )\n result = df._get_numeric_data()\n tm.assert_index_equal(result.columns, Index(["a", "b", "e"]))\n\n def test_get_numeric_data_extension_dtype(self):\n # GH#22290\n df = DataFrame(\n {\n "A": pd.array([-10, np.nan, 0, 10, 20, 30], dtype="Int64"),\n "B": Categorical(list("abcabc")),\n "C": pd.array([0, 1, 2, 3, np.nan, 5], dtype="UInt8"),\n "D": IntervalArray.from_breaks(range(7)),\n }\n )\n result = df._get_numeric_data()\n expected = df.loc[:, ["A", "C"]]\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_get_numeric_data.py
test_get_numeric_data.py
Python
3,368
0.95
0.057692
0.032967
vue-tools
917
2023-08-17T20:43:52.007729
MIT
true
8a79f37923bf185c60df2532df92864f
import numpy as np\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\ndef test_head_tail_generic(index, frame_or_series):\n # GH#5370\n\n ndim = 2 if frame_or_series is DataFrame else 1\n shape = (len(index),) * ndim\n vals = np.random.default_rng(2).standard_normal(shape)\n obj = frame_or_series(vals, index=index)\n\n tm.assert_equal(obj.head(), obj.iloc[:5])\n tm.assert_equal(obj.tail(), obj.iloc[-5:])\n\n # 0-len\n tm.assert_equal(obj.head(0), obj.iloc[0:0])\n tm.assert_equal(obj.tail(0), obj.iloc[0:0])\n\n # bounded\n tm.assert_equal(obj.head(len(obj) + 1), obj)\n tm.assert_equal(obj.tail(len(obj) + 1), obj)\n\n # neg index\n tm.assert_equal(obj.head(-3), obj.head(len(index) - 3))\n tm.assert_equal(obj.tail(-3), obj.tail(len(index) - 3))\n\n\ndef test_head_tail(float_frame):\n tm.assert_frame_equal(float_frame.head(), float_frame[:5])\n tm.assert_frame_equal(float_frame.tail(), float_frame[-5:])\n\n tm.assert_frame_equal(float_frame.head(0), float_frame[0:0])\n tm.assert_frame_equal(float_frame.tail(0), float_frame[0:0])\n\n tm.assert_frame_equal(float_frame.head(-1), float_frame[:-1])\n tm.assert_frame_equal(float_frame.tail(-1), float_frame[1:])\n tm.assert_frame_equal(float_frame.head(1), float_frame[:1])\n tm.assert_frame_equal(float_frame.tail(1), float_frame[-1:])\n # with a float index\n df = float_frame.copy()\n df.index = np.arange(len(float_frame)) + 0.1\n tm.assert_frame_equal(df.head(), df.iloc[:5])\n tm.assert_frame_equal(df.tail(), df.iloc[-5:])\n tm.assert_frame_equal(df.head(0), df[0:0])\n tm.assert_frame_equal(df.tail(0), df[0:0])\n tm.assert_frame_equal(df.head(-1), df.iloc[:-1])\n tm.assert_frame_equal(df.tail(-1), df.iloc[1:])\n\n\ndef test_head_tail_empty():\n # test empty dataframe\n empty_df = DataFrame()\n tm.assert_frame_equal(empty_df.tail(), empty_df)\n tm.assert_frame_equal(empty_df.head(), empty_df)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_head_tail.py
test_head_tail.py
Python
1,935
0.95
0.070175
0.139535
awesome-app
696
2024-07-31T09:29:10.707796
GPL-3.0
true
26d7f93063886d33cef7c0972a332d72
from datetime import datetime\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\nclass TestInferObjects:\n def test_infer_objects(self):\n # GH#11221\n df = DataFrame(\n {\n "a": ["a", 1, 2, 3],\n "b": ["b", 2.0, 3.0, 4.1],\n "c": [\n "c",\n datetime(2016, 1, 1),\n datetime(2016, 1, 2),\n datetime(2016, 1, 3),\n ],\n "d": [1, 2, 3, "d"],\n },\n columns=["a", "b", "c", "d"],\n )\n df = df.iloc[1:].infer_objects()\n\n assert df["a"].dtype == "int64"\n assert df["b"].dtype == "float64"\n assert df["c"].dtype == "M8[ns]"\n assert df["d"].dtype == "object"\n\n expected = DataFrame(\n {\n "a": [1, 2, 3],\n "b": [2.0, 3.0, 4.1],\n "c": [datetime(2016, 1, 1), datetime(2016, 1, 2), datetime(2016, 1, 3)],\n "d": [2, 3, "d"],\n },\n columns=["a", "b", "c", "d"],\n )\n # reconstruct frame to verify inference is same\n result = df.reset_index(drop=True)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_infer_objects.py
test_infer_objects.py
Python
1,241
0.95
0.047619
0.054054
python-kit
470
2024-02-16T19:18:56.108427
Apache-2.0
true
bf1f27261d377ae30b12d21fd81c33df
from io import StringIO\nimport re\nfrom string import ascii_uppercase\nimport sys\nimport textwrap\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nfrom pandas.compat import (\n HAS_PYARROW,\n IS64,\n PYPY,\n is_platform_arm,\n)\n\nfrom pandas import (\n CategoricalIndex,\n DataFrame,\n Index,\n MultiIndex,\n Series,\n date_range,\n option_context,\n)\nimport pandas._testing as tm\nfrom pandas.util.version import Version\n\n\n@pytest.fixture\ndef duplicate_columns_frame():\n """Dataframe with duplicate column names."""\n return DataFrame(\n np.random.default_rng(2).standard_normal((1500, 4)),\n columns=["a", "a", "b", "b"],\n )\n\n\ndef test_info_empty():\n # GH #45494\n df = DataFrame()\n buf = StringIO()\n df.info(buf=buf)\n result = buf.getvalue()\n expected = textwrap.dedent(\n """\\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 0 entries\n Empty DataFrame\n"""\n )\n assert result == expected\n\n\ndef test_info_categorical_column_smoke_test():\n n = 2500\n df = DataFrame({"int64": np.random.default_rng(2).integers(100, size=n, dtype=int)})\n df["category"] = Series(\n np.array(list("abcdefghij")).take(\n np.random.default_rng(2).integers(0, 10, size=n, dtype=int)\n )\n ).astype("category")\n df.isna()\n buf = StringIO()\n df.info(buf=buf)\n\n df2 = df[df["category"] == "d"]\n buf = StringIO()\n df2.info(buf=buf)\n\n\n@pytest.mark.parametrize(\n "fixture_func_name",\n [\n "int_frame",\n "float_frame",\n "datetime_frame",\n "duplicate_columns_frame",\n "float_string_frame",\n ],\n)\ndef test_info_smoke_test(fixture_func_name, request):\n frame = request.getfixturevalue(fixture_func_name)\n buf = StringIO()\n frame.info(buf=buf)\n result = buf.getvalue().splitlines()\n assert len(result) > 10\n\n buf = StringIO()\n frame.info(buf=buf, verbose=False)\n\n\ndef test_info_smoke_test2(float_frame):\n # pretty useless test, used to be mixed into the repr tests\n buf = StringIO()\n float_frame.reindex(columns=["A"]).info(verbose=False, buf=buf)\n float_frame.reindex(columns=["A", "B"]).info(verbose=False, buf=buf)\n\n # no columns or index\n DataFrame().info(buf=buf)\n\n\n@pytest.mark.parametrize(\n "num_columns, max_info_columns, verbose",\n [\n (10, 100, True),\n (10, 11, True),\n (10, 10, True),\n (10, 9, False),\n (10, 1, False),\n ],\n)\ndef test_info_default_verbose_selection(num_columns, max_info_columns, verbose):\n frame = DataFrame(np.random.default_rng(2).standard_normal((5, num_columns)))\n with option_context("display.max_info_columns", max_info_columns):\n io_default = StringIO()\n frame.info(buf=io_default)\n result = io_default.getvalue()\n\n io_explicit = StringIO()\n frame.info(buf=io_explicit, verbose=verbose)\n expected = io_explicit.getvalue()\n\n assert result == expected\n\n\ndef test_info_verbose_check_header_separator_body():\n buf = StringIO()\n size = 1001\n start = 5\n frame = DataFrame(np.random.default_rng(2).standard_normal((3, size)))\n frame.info(verbose=True, buf=buf)\n\n res = buf.getvalue()\n header = " # Column Dtype \n--- ------ ----- "\n assert header in res\n\n frame.info(verbose=True, buf=buf)\n buf.seek(0)\n lines = buf.readlines()\n assert len(lines) > 0\n\n for i, line in enumerate(lines):\n if start <= i < start + size:\n line_nr = f" {i - start} "\n assert line.startswith(line_nr)\n\n\n@pytest.mark.parametrize(\n "size, header_exp, separator_exp, first_line_exp, last_line_exp",\n [\n (\n 4,\n " # Column Non-Null Count Dtype ",\n "--- ------ -------------- ----- ",\n " 0 0 3 non-null float64",\n " 3 3 3 non-null float64",\n ),\n (\n 11,\n " # Column Non-Null Count Dtype ",\n "--- ------ -------------- ----- ",\n " 0 0 3 non-null float64",\n " 10 10 3 non-null float64",\n ),\n (\n 101,\n " # Column Non-Null Count Dtype ",\n "--- ------ -------------- ----- ",\n " 0 0 3 non-null float64",\n " 100 100 3 non-null float64",\n ),\n (\n 1001,\n " # Column Non-Null Count Dtype ",\n "--- ------ -------------- ----- ",\n " 0 0 3 non-null float64",\n " 1000 1000 3 non-null float64",\n ),\n (\n 10001,\n " # Column Non-Null Count Dtype ",\n "--- ------ -------------- ----- ",\n " 0 0 3 non-null float64",\n " 10000 10000 3 non-null float64",\n ),\n ],\n)\ndef test_info_verbose_with_counts_spacing(\n size, header_exp, separator_exp, first_line_exp, last_line_exp\n):\n """Test header column, spacer, first line and last line in verbose mode."""\n frame = DataFrame(np.random.default_rng(2).standard_normal((3, size)))\n with StringIO() as buf:\n frame.info(verbose=True, show_counts=True, buf=buf)\n all_lines = buf.getvalue().splitlines()\n # Here table would contain only header, separator and table lines\n # dframe repr, index summary, memory usage and dtypes are excluded\n table = all_lines[3:-2]\n header, separator, first_line, *rest, last_line = table\n assert header == header_exp\n assert separator == separator_exp\n assert first_line == first_line_exp\n assert last_line == last_line_exp\n\n\ndef test_info_memory():\n # https://github.com/pandas-dev/pandas/issues/21056\n df = DataFrame({"a": Series([1, 2], dtype="i8")})\n buf = StringIO()\n df.info(buf=buf)\n result = buf.getvalue()\n bytes = float(df.memory_usage().sum())\n expected = textwrap.dedent(\n f"""\\n <class 'pandas.core.frame.DataFrame'>\n RangeIndex: 2 entries, 0 to 1\n Data columns (total 1 columns):\n # Column Non-Null Count Dtype\n --- ------ -------------- -----\n 0 a 2 non-null int64\n dtypes: int64(1)\n memory usage: {bytes} bytes\n """\n )\n assert result == expected\n\n\ndef test_info_wide():\n io = StringIO()\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 101)))\n df.info(buf=io)\n\n io = StringIO()\n df.info(buf=io, max_cols=101)\n result = io.getvalue()\n assert len(result.splitlines()) > 100\n\n expected = result\n with option_context("display.max_info_columns", 101):\n io = StringIO()\n df.info(buf=io)\n result = io.getvalue()\n assert result == expected\n\n\ndef test_info_duplicate_columns_shows_correct_dtypes():\n # GH11761\n io = StringIO()\n frame = DataFrame([[1, 2.0]], columns=["a", "a"])\n frame.info(buf=io)\n lines = io.getvalue().splitlines(True)\n assert " 0 a 1 non-null int64 \n" == lines[5]\n assert " 1 a 1 non-null float64\n" == lines[6]\n\n\ndef test_info_shows_column_dtypes():\n dtypes = [\n "int64",\n "float64",\n "datetime64[ns]",\n "timedelta64[ns]",\n "complex128",\n "object",\n "bool",\n ]\n data = {}\n n = 10\n for i, dtype in enumerate(dtypes):\n data[i] = np.random.default_rng(2).integers(2, size=n).astype(dtype)\n df = DataFrame(data)\n buf = StringIO()\n df.info(buf=buf)\n res = buf.getvalue()\n header = (\n " # Column Non-Null Count Dtype \n"\n "--- ------ -------------- ----- "\n )\n assert header in res\n for i, dtype in enumerate(dtypes):\n name = f" {i:d} {i:d} {n:d} non-null {dtype}"\n assert name in res\n\n\ndef test_info_max_cols():\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))\n for len_, verbose in [(5, None), (5, False), (12, True)]:\n # For verbose always ^ setting ^ summarize ^ full output\n with option_context("max_info_columns", 4):\n buf = StringIO()\n df.info(buf=buf, verbose=verbose)\n res = buf.getvalue()\n assert len(res.strip().split("\n")) == len_\n\n for len_, verbose in [(12, None), (5, False), (12, True)]:\n # max_cols not exceeded\n with option_context("max_info_columns", 5):\n buf = StringIO()\n df.info(buf=buf, verbose=verbose)\n res = buf.getvalue()\n assert len(res.strip().split("\n")) == len_\n\n for len_, max_cols in [(12, 5), (5, 4)]:\n # setting truncates\n with option_context("max_info_columns", 4):\n buf = StringIO()\n df.info(buf=buf, max_cols=max_cols)\n res = buf.getvalue()\n assert len(res.strip().split("\n")) == len_\n\n # setting wouldn't truncate\n with option_context("max_info_columns", 5):\n buf = StringIO()\n df.info(buf=buf, max_cols=max_cols)\n res = buf.getvalue()\n assert len(res.strip().split("\n")) == len_\n\n\ndef test_info_memory_usage():\n # Ensure memory usage is displayed, when asserted, on the last line\n dtypes = [\n "int64",\n "float64",\n "datetime64[ns]",\n "timedelta64[ns]",\n "complex128",\n "object",\n "bool",\n ]\n data = {}\n n = 10\n for i, dtype in enumerate(dtypes):\n data[i] = np.random.default_rng(2).integers(2, size=n).astype(dtype)\n df = DataFrame(data)\n buf = StringIO()\n\n # display memory usage case\n df.info(buf=buf, memory_usage=True)\n res = buf.getvalue().splitlines()\n assert "memory usage: " in res[-1]\n\n # do not display memory usage case\n df.info(buf=buf, memory_usage=False)\n res = buf.getvalue().splitlines()\n assert "memory usage: " not in res[-1]\n\n df.info(buf=buf, memory_usage=True)\n res = buf.getvalue().splitlines()\n\n # memory usage is a lower bound, so print it as XYZ+ MB\n assert re.match(r"memory usage: [^+]+\+", res[-1])\n\n df.iloc[:, :5].info(buf=buf, memory_usage=True)\n res = buf.getvalue().splitlines()\n\n # excluded column with object dtype, so estimate is accurate\n assert not re.match(r"memory usage: [^+]+\+", res[-1])\n\n # Test a DataFrame with duplicate columns\n dtypes = ["int64", "int64", "int64", "float64"]\n data = {}\n n = 100\n for i, dtype in enumerate(dtypes):\n data[i] = np.random.default_rng(2).integers(2, size=n).astype(dtype)\n df = DataFrame(data)\n df.columns = dtypes\n\n df_with_object_index = DataFrame({"a": [1]}, index=Index(["foo"], dtype=object))\n df_with_object_index.info(buf=buf, memory_usage=True)\n res = buf.getvalue().splitlines()\n assert re.match(r"memory usage: [^+]+\+", res[-1])\n\n df_with_object_index.info(buf=buf, memory_usage="deep")\n res = buf.getvalue().splitlines()\n assert re.match(r"memory usage: [^+]+$", res[-1])\n\n # Ensure df size is as expected\n # (cols * rows * bytes) + index size\n df_size = df.memory_usage().sum()\n exp_size = len(dtypes) * n * 8 + df.index.nbytes\n assert df_size == exp_size\n\n # Ensure number of cols in memory_usage is the same as df\n size_df = np.size(df.columns.values) + 1 # index=True; default\n assert size_df == np.size(df.memory_usage())\n\n # assert deep works only on object\n assert df.memory_usage().sum() == df.memory_usage(deep=True).sum()\n\n # test for validity\n DataFrame(1, index=["a"], columns=["A"]).memory_usage(index=True)\n DataFrame(1, index=["a"], columns=["A"]).index.nbytes\n df = DataFrame(\n data=1, index=MultiIndex.from_product([["a"], range(1000)]), columns=["A"]\n )\n df.index.nbytes\n df.memory_usage(index=True)\n df.index.values.nbytes\n\n mem = df.memory_usage(deep=True).sum()\n assert mem > 0\n\n\n@pytest.mark.skipif(PYPY, reason="on PyPy deep=True doesn't change result")\ndef test_info_memory_usage_deep_not_pypy():\n df_with_object_index = DataFrame({"a": [1]}, index=Index(["foo"], dtype=object))\n assert (\n df_with_object_index.memory_usage(index=True, deep=True).sum()\n > df_with_object_index.memory_usage(index=True).sum()\n )\n\n df_object = DataFrame({"a": Series(["a"], dtype=object)})\n assert df_object.memory_usage(deep=True).sum() > df_object.memory_usage().sum()\n\n\n@pytest.mark.xfail(not PYPY, reason="on PyPy deep=True does not change result")\ndef test_info_memory_usage_deep_pypy():\n df_with_object_index = DataFrame({"a": [1]}, index=Index(["foo"], dtype=object))\n assert (\n df_with_object_index.memory_usage(index=True, deep=True).sum()\n == df_with_object_index.memory_usage(index=True).sum()\n )\n\n df_object = DataFrame({"a": Series(["a"], dtype=object)})\n assert df_object.memory_usage(deep=True).sum() == df_object.memory_usage().sum()\n\n\n@pytest.mark.skipif(PYPY, reason="PyPy getsizeof() fails by design")\ndef test_usage_via_getsizeof():\n df = DataFrame(\n data=1, index=MultiIndex.from_product([["a"], range(1000)]), columns=["A"]\n )\n mem = df.memory_usage(deep=True).sum()\n # sys.getsizeof will call the .memory_usage with\n # deep=True, and add on some GC overhead\n diff = mem - sys.getsizeof(df)\n assert abs(diff) < 100\n\n\ndef test_info_memory_usage_qualified(using_infer_string):\n buf = StringIO()\n df = DataFrame(1, columns=list("ab"), index=[1, 2, 3])\n df.info(buf=buf)\n assert "+" not in buf.getvalue()\n\n buf = StringIO()\n df = DataFrame(1, columns=list("ab"), index=Index(list("ABC"), dtype=object))\n df.info(buf=buf)\n assert "+" in buf.getvalue()\n\n buf = StringIO()\n df = DataFrame(1, columns=list("ab"), index=Index(list("ABC"), dtype="str"))\n df.info(buf=buf)\n if using_infer_string and HAS_PYARROW:\n assert "+" not in buf.getvalue()\n else:\n assert "+" in buf.getvalue()\n\n buf = StringIO()\n df = DataFrame(\n 1, columns=list("ab"), index=MultiIndex.from_product([range(3), range(3)])\n )\n df.info(buf=buf)\n assert "+" not in buf.getvalue()\n\n buf = StringIO()\n df = DataFrame(\n 1, columns=list("ab"), index=MultiIndex.from_product([range(3), ["foo", "bar"]])\n )\n df.info(buf=buf)\n if using_infer_string and HAS_PYARROW:\n assert "+" not in buf.getvalue()\n else:\n assert "+" in buf.getvalue()\n\n\ndef test_info_memory_usage_bug_on_multiindex():\n # GH 14308\n # memory usage introspection should not materialize .values\n\n def memory_usage(f):\n return f.memory_usage(deep=True).sum()\n\n N = 100\n M = len(ascii_uppercase)\n index = MultiIndex.from_product(\n [list(ascii_uppercase), date_range("20160101", periods=N)],\n names=["id", "date"],\n )\n df = DataFrame(\n {"value": np.random.default_rng(2).standard_normal(N * M)}, index=index\n )\n\n unstacked = df.unstack("id")\n assert df.values.nbytes == unstacked.values.nbytes\n assert memory_usage(df) > memory_usage(unstacked)\n\n # high upper bound\n assert memory_usage(unstacked) - memory_usage(df) < 2000\n\n\ndef test_info_categorical():\n # GH14298\n idx = CategoricalIndex(["a", "b"])\n df = DataFrame(np.zeros((2, 2)), index=idx, columns=idx)\n\n buf = StringIO()\n df.info(buf=buf)\n\n\n@pytest.mark.xfail(not IS64, reason="GH 36579: fail on 32-bit system")\ndef test_info_int_columns(using_infer_string):\n # GH#37245\n df = DataFrame({1: [1, 2], 2: [2, 3]}, index=["A", "B"])\n buf = StringIO()\n df.info(show_counts=True, buf=buf)\n result = buf.getvalue()\n expected = textwrap.dedent(\n f"""\\n <class 'pandas.core.frame.DataFrame'>\n Index: 2 entries, A to B\n Data columns (total 2 columns):\n # Column Non-Null Count Dtype\n --- ------ -------------- -----\n 0 1 2 non-null int64\n 1 2 2 non-null int64\n dtypes: int64(2)\n memory usage: {'50.0' if using_infer_string and HAS_PYARROW else '48.0+'} bytes\n """\n )\n assert result == expected\n\n\n@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")\ndef test_memory_usage_empty_no_warning(using_infer_string):\n # GH#50066\n df = DataFrame(index=["a", "b"])\n with tm.assert_produces_warning(None):\n result = df.memory_usage()\n if using_infer_string and HAS_PYARROW:\n value = 18\n else:\n value = 16 if IS64 else 8\n expected = Series(value, index=["Index"])\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.single_cpu\ndef test_info_compute_numba():\n # GH#51922\n numba = pytest.importorskip("numba")\n if Version(numba.__version__) == Version("0.61") and is_platform_arm():\n pytest.skip(f"Segfaults on ARM platforms with numba {numba.__version__}")\n df = DataFrame([[1, 2], [3, 4]])\n\n with option_context("compute.use_numba", True):\n buf = StringIO()\n df.info(buf=buf)\n result = buf.getvalue()\n\n buf = StringIO()\n df.info(buf=buf)\n expected = buf.getvalue()\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "row, columns, show_counts, result",\n [\n [20, 20, None, True],\n [20, 20, True, True],\n [20, 20, False, False],\n [5, 5, None, False],\n [5, 5, True, False],\n [5, 5, False, False],\n ],\n)\ndef test_info_show_counts(row, columns, show_counts, result):\n # Explicit cast to float to avoid implicit cast when setting nan\n df = DataFrame(1, columns=range(10), index=range(10)).astype({1: "float"})\n df.iloc[1, 1] = np.nan\n\n with option_context(\n "display.max_info_rows", row, "display.max_info_columns", columns\n ):\n with StringIO() as buf:\n df.info(buf=buf, show_counts=show_counts)\n assert ("non-null" in buf.getvalue()) is result\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_info.py
test_info.py
Python
17,923
0.95
0.074703
0.068548
python-kit
586
2025-03-02T19:42:04.915908
MIT
true
a915d8333da835ba0ba19a2390b48157
import numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nfrom pandas.errors import ChainedAssignmentError\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n DataFrame,\n NaT,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameInterpolate:\n def test_interpolate_complex(self):\n # GH#53635\n ser = Series([complex("1+1j"), float("nan"), complex("2+2j")])\n assert ser.dtype.kind == "c"\n\n res = ser.interpolate()\n expected = Series([ser[0], ser[0] * 1.5, ser[2]])\n tm.assert_series_equal(res, expected)\n\n df = ser.to_frame()\n res = df.interpolate()\n expected = expected.to_frame()\n tm.assert_frame_equal(res, expected)\n\n def test_interpolate_datetimelike_values(self, frame_or_series):\n # GH#11312, GH#51005\n orig = Series(date_range("2012-01-01", periods=5))\n ser = orig.copy()\n ser[2] = NaT\n\n res = frame_or_series(ser).interpolate()\n expected = frame_or_series(orig)\n tm.assert_equal(res, expected)\n\n # datetime64tz cast\n ser_tz = ser.dt.tz_localize("US/Pacific")\n res_tz = frame_or_series(ser_tz).interpolate()\n expected_tz = frame_or_series(orig.dt.tz_localize("US/Pacific"))\n tm.assert_equal(res_tz, expected_tz)\n\n # timedelta64 cast\n ser_td = ser - ser[0]\n res_td = frame_or_series(ser_td).interpolate()\n expected_td = frame_or_series(orig - orig[0])\n tm.assert_equal(res_td, expected_td)\n\n def test_interpolate_inplace(self, frame_or_series, using_array_manager, request):\n # GH#44749\n if using_array_manager and frame_or_series is DataFrame:\n mark = pytest.mark.xfail(reason=".values-based in-place check is invalid")\n request.applymarker(mark)\n\n obj = frame_or_series([1, np.nan, 2])\n orig = obj.values\n\n obj.interpolate(inplace=True)\n expected = frame_or_series([1, 1.5, 2])\n tm.assert_equal(obj, expected)\n\n # check we operated *actually* inplace\n assert np.shares_memory(orig, obj.values)\n assert orig.squeeze()[1] == 1.5\n\n def test_interp_basic(self, using_copy_on_write, using_infer_string):\n df = DataFrame(\n {\n "A": [1, 2, np.nan, 4],\n "B": [1, 4, 9, np.nan],\n "C": [1, 2, 3, 5],\n "D": list("abcd"),\n }\n )\n expected = DataFrame(\n {\n "A": [1.0, 2.0, 3.0, 4.0],\n "B": [1.0, 4.0, 9.0, 9.0],\n "C": [1, 2, 3, 5],\n "D": list("abcd"),\n }\n )\n if using_infer_string:\n dtype = "str" if using_infer_string else "object"\n msg = f"[Cc]annot interpolate with {dtype} dtype"\n with pytest.raises(TypeError, match=msg):\n df.interpolate()\n return\n\n msg = "DataFrame.interpolate with object dtype"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.interpolate()\n tm.assert_frame_equal(result, expected)\n\n # check we didn't operate inplace GH#45791\n cvalues = df["C"]._values\n dvalues = df["D"].values\n if using_copy_on_write:\n assert np.shares_memory(cvalues, result["C"]._values)\n assert np.shares_memory(dvalues, result["D"]._values)\n else:\n assert not np.shares_memory(cvalues, result["C"]._values)\n assert not np.shares_memory(dvalues, result["D"]._values)\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res = df.interpolate(inplace=True)\n assert res is None\n tm.assert_frame_equal(df, expected)\n\n # check we DID operate inplace\n assert tm.shares_memory(df["C"]._values, cvalues)\n assert tm.shares_memory(df["D"]._values, dvalues)\n\n @pytest.mark.xfail(\n using_string_dtype(), reason="interpolate doesn't work for string"\n )\n def test_interp_basic_with_non_range_index(self, using_infer_string):\n df = DataFrame(\n {\n "A": [1, 2, np.nan, 4],\n "B": [1, 4, 9, np.nan],\n "C": [1, 2, 3, 5],\n "D": list("abcd"),\n }\n )\n\n msg = "DataFrame.interpolate with object dtype"\n warning = FutureWarning if not using_infer_string else None\n with tm.assert_produces_warning(warning, match=msg):\n result = df.set_index("C").interpolate()\n expected = df.set_index("C")\n expected.loc[3, "A"] = 3\n expected.loc[5, "B"] = 9\n tm.assert_frame_equal(result, expected)\n\n def test_interp_empty(self):\n # https://github.com/pandas-dev/pandas/issues/35598\n df = DataFrame()\n result = df.interpolate()\n assert result is not df\n expected = df\n tm.assert_frame_equal(result, expected)\n\n def test_interp_bad_method(self):\n df = DataFrame(\n {\n "A": [1, 2, np.nan, 4],\n "B": [1, 4, 9, np.nan],\n "C": [1, 2, 3, 5],\n }\n )\n msg = (\n r"method must be one of \['linear', 'time', 'index', 'values', "\n r"'nearest', 'zero', 'slinear', 'quadratic', 'cubic', "\n r"'barycentric', 'krogh', 'spline', 'polynomial', "\n r"'from_derivatives', 'piecewise_polynomial', 'pchip', 'akima', "\n r"'cubicspline'\]. Got 'not_a_method' instead."\n )\n with pytest.raises(ValueError, match=msg):\n df.interpolate(method="not_a_method")\n\n def test_interp_combo(self):\n df = DataFrame(\n {\n "A": [1.0, 2.0, np.nan, 4.0],\n "B": [1, 4, 9, np.nan],\n "C": [1, 2, 3, 5],\n "D": list("abcd"),\n }\n )\n\n result = df["A"].interpolate()\n expected = Series([1.0, 2.0, 3.0, 4.0], name="A")\n tm.assert_series_equal(result, expected)\n\n msg = "The 'downcast' keyword in Series.interpolate is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df["A"].interpolate(downcast="infer")\n expected = Series([1, 2, 3, 4], name="A")\n tm.assert_series_equal(result, expected)\n\n def test_inerpolate_invalid_downcast(self):\n # GH#53103\n df = DataFrame(\n {\n "A": [1.0, 2.0, np.nan, 4.0],\n "B": [1, 4, 9, np.nan],\n "C": [1, 2, 3, 5],\n "D": list("abcd"),\n }\n )\n\n msg = "downcast must be either None or 'infer'"\n msg2 = "The 'downcast' keyword in DataFrame.interpolate is deprecated"\n msg3 = "The 'downcast' keyword in Series.interpolate is deprecated"\n with pytest.raises(ValueError, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=msg2):\n df.interpolate(downcast="int64")\n with pytest.raises(ValueError, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=msg3):\n df["A"].interpolate(downcast="int64")\n\n def test_interp_nan_idx(self):\n df = DataFrame({"A": [1, 2, np.nan, 4], "B": [np.nan, 2, 3, 4]})\n df = df.set_index("A")\n msg = (\n "Interpolation with NaNs in the index has not been implemented. "\n "Try filling those NaNs before interpolating."\n )\n with pytest.raises(NotImplementedError, match=msg):\n df.interpolate(method="values")\n\n def test_interp_various(self):\n pytest.importorskip("scipy")\n df = DataFrame(\n {"A": [1, 2, np.nan, 4, 5, np.nan, 7], "C": [1, 2, 3, 5, 8, 13, 21]}\n )\n df = df.set_index("C")\n expected = df.copy()\n result = df.interpolate(method="polynomial", order=1)\n\n expected.loc[3, "A"] = 2.66666667\n expected.loc[13, "A"] = 5.76923076\n tm.assert_frame_equal(result, expected)\n\n result = df.interpolate(method="cubic")\n # GH #15662.\n expected.loc[3, "A"] = 2.81547781\n expected.loc[13, "A"] = 5.52964175\n tm.assert_frame_equal(result, expected)\n\n result = df.interpolate(method="nearest")\n expected.loc[3, "A"] = 2\n expected.loc[13, "A"] = 5\n tm.assert_frame_equal(result, expected, check_dtype=False)\n\n result = df.interpolate(method="quadratic")\n expected.loc[3, "A"] = 2.82150771\n expected.loc[13, "A"] = 6.12648668\n tm.assert_frame_equal(result, expected)\n\n result = df.interpolate(method="slinear")\n expected.loc[3, "A"] = 2.66666667\n expected.loc[13, "A"] = 5.76923077\n tm.assert_frame_equal(result, expected)\n\n result = df.interpolate(method="zero")\n expected.loc[3, "A"] = 2.0\n expected.loc[13, "A"] = 5\n tm.assert_frame_equal(result, expected, check_dtype=False)\n\n def test_interp_alt_scipy(self):\n pytest.importorskip("scipy")\n df = DataFrame(\n {"A": [1, 2, np.nan, 4, 5, np.nan, 7], "C": [1, 2, 3, 5, 8, 13, 21]}\n )\n result = df.interpolate(method="barycentric")\n expected = df.copy()\n expected.loc[2, "A"] = 3\n expected.loc[5, "A"] = 6\n tm.assert_frame_equal(result, expected)\n\n msg = "The 'downcast' keyword in DataFrame.interpolate is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.interpolate(method="barycentric", downcast="infer")\n tm.assert_frame_equal(result, expected.astype(np.int64))\n\n result = df.interpolate(method="krogh")\n expectedk = df.copy()\n expectedk["A"] = expected["A"]\n tm.assert_frame_equal(result, expectedk)\n\n result = df.interpolate(method="pchip")\n expected.loc[2, "A"] = 3\n expected.loc[5, "A"] = 6.0\n\n tm.assert_frame_equal(result, expected)\n\n def test_interp_rowwise(self):\n df = DataFrame(\n {\n 0: [1, 2, np.nan, 4],\n 1: [2, 3, 4, np.nan],\n 2: [np.nan, 4, 5, 6],\n 3: [4, np.nan, 6, 7],\n 4: [1, 2, 3, 4],\n }\n )\n result = df.interpolate(axis=1)\n expected = df.copy()\n expected.loc[3, 1] = 5\n expected.loc[0, 2] = 3\n expected.loc[1, 3] = 3\n expected[4] = expected[4].astype(np.float64)\n tm.assert_frame_equal(result, expected)\n\n result = df.interpolate(axis=1, method="values")\n tm.assert_frame_equal(result, expected)\n\n result = df.interpolate(axis=0)\n expected = df.interpolate()\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "axis_name, axis_number",\n [\n pytest.param("rows", 0, id="rows_0"),\n pytest.param("index", 0, id="index_0"),\n pytest.param("columns", 1, id="columns_1"),\n ],\n )\n def test_interp_axis_names(self, axis_name, axis_number):\n # GH 29132: test axis names\n data = {0: [0, np.nan, 6], 1: [1, np.nan, 7], 2: [2, 5, 8]}\n\n df = DataFrame(data, dtype=np.float64)\n result = df.interpolate(axis=axis_name, method="linear")\n expected = df.interpolate(axis=axis_number, method="linear")\n tm.assert_frame_equal(result, expected)\n\n def test_rowwise_alt(self):\n df = DataFrame(\n {\n 0: [0, 0.5, 1.0, np.nan, 4, 8, np.nan, np.nan, 64],\n 1: [1, 2, 3, 4, 3, 2, 1, 0, -1],\n }\n )\n df.interpolate(axis=0)\n # TODO: assert something?\n\n @pytest.mark.parametrize(\n "check_scipy", [False, pytest.param(True, marks=td.skip_if_no("scipy"))]\n )\n def test_interp_leading_nans(self, check_scipy):\n df = DataFrame(\n {"A": [np.nan, np.nan, 0.5, 0.25, 0], "B": [np.nan, -3, -3.5, np.nan, -4]}\n )\n result = df.interpolate()\n expected = df.copy()\n expected.loc[3, "B"] = -3.75\n tm.assert_frame_equal(result, expected)\n\n if check_scipy:\n result = df.interpolate(method="polynomial", order=1)\n tm.assert_frame_equal(result, expected)\n\n def test_interp_raise_on_only_mixed(self, axis):\n df = DataFrame(\n {\n "A": [1, 2, np.nan, 4],\n "B": ["a", "b", "c", "d"],\n "C": [np.nan, 2, 5, 7],\n "D": [np.nan, np.nan, 9, 9],\n "E": [1, 2, 3, 4],\n }\n )\n msg = (\n "Cannot interpolate with all object-dtype columns "\n "in the DataFrame. Try setting at least one "\n "column to a numeric dtype."\n )\n with pytest.raises(TypeError, match=msg):\n df.astype("object").interpolate(axis=axis)\n\n def test_interp_raise_on_all_object_dtype(self):\n # GH 22985\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, dtype="object")\n msg = (\n "Cannot interpolate with all object-dtype columns "\n "in the DataFrame. Try setting at least one "\n "column to a numeric dtype."\n )\n with pytest.raises(TypeError, match=msg):\n df.interpolate()\n\n def test_interp_inplace(self, using_copy_on_write):\n df = DataFrame({"a": [1.0, 2.0, np.nan, 4.0]})\n expected = DataFrame({"a": [1.0, 2.0, 3.0, 4.0]})\n expected_cow = df.copy()\n result = df.copy()\n\n if using_copy_on_write:\n with tm.raises_chained_assignment_error():\n return_value = result["a"].interpolate(inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected_cow)\n else:\n with tm.assert_produces_warning(FutureWarning, match="inplace method"):\n return_value = result["a"].interpolate(inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n msg = "The 'downcast' keyword in Series.interpolate is deprecated"\n\n if using_copy_on_write:\n with tm.assert_produces_warning(\n (FutureWarning, ChainedAssignmentError), match=msg\n ):\n return_value = result["a"].interpolate(inplace=True, downcast="infer")\n assert return_value is None\n tm.assert_frame_equal(result, expected_cow)\n else:\n with tm.assert_produces_warning(FutureWarning, match=msg):\n return_value = result["a"].interpolate(inplace=True, downcast="infer")\n assert return_value is None\n tm.assert_frame_equal(result, expected.astype("int64"))\n\n def test_interp_inplace_row(self):\n # GH 10395\n result = DataFrame(\n {"a": [1.0, 2.0, 3.0, 4.0], "b": [np.nan, 2.0, 3.0, 4.0], "c": [3, 2, 2, 2]}\n )\n expected = result.interpolate(method="linear", axis=1, inplace=False)\n return_value = result.interpolate(method="linear", axis=1, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n def test_interp_ignore_all_good(self):\n # GH\n df = DataFrame(\n {\n "A": [1, 2, np.nan, 4],\n "B": [1, 2, 3, 4],\n "C": [1.0, 2.0, np.nan, 4.0],\n "D": [1.0, 2.0, 3.0, 4.0],\n }\n )\n expected = DataFrame(\n {\n "A": np.array([1, 2, 3, 4], dtype="float64"),\n "B": np.array([1, 2, 3, 4], dtype="int64"),\n "C": np.array([1.0, 2.0, 3, 4.0], dtype="float64"),\n "D": np.array([1.0, 2.0, 3.0, 4.0], dtype="float64"),\n }\n )\n\n msg = "The 'downcast' keyword in DataFrame.interpolate is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.interpolate(downcast=None)\n tm.assert_frame_equal(result, expected)\n\n # all good\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df[["B", "D"]].interpolate(downcast=None)\n tm.assert_frame_equal(result, df[["B", "D"]])\n\n def test_interp_time_inplace_axis(self):\n # GH 9687\n periods = 5\n idx = date_range(start="2014-01-01", periods=periods)\n data = np.random.default_rng(2).random((periods, periods))\n data[data < 0.5] = np.nan\n expected = DataFrame(index=idx, columns=idx, data=data)\n\n result = expected.interpolate(axis=0, method="time")\n return_value = expected.interpolate(axis=0, method="time", inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("axis_name, axis_number", [("index", 0), ("columns", 1)])\n def test_interp_string_axis(self, axis_name, axis_number):\n # https://github.com/pandas-dev/pandas/issues/25190\n x = np.linspace(0, 100, 1000)\n y = np.sin(x)\n df = DataFrame(\n data=np.tile(y, (10, 1)), index=np.arange(10), columns=x\n ).reindex(columns=x * 1.005)\n result = df.interpolate(method="linear", axis=axis_name)\n expected = df.interpolate(method="linear", axis=axis_number)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("multiblock", [True, False])\n @pytest.mark.parametrize("method", ["ffill", "bfill", "pad"])\n def test_interp_fillna_methods(\n self, request, axis, multiblock, method, using_array_manager\n ):\n # GH 12918\n if using_array_manager and axis in (1, "columns"):\n # TODO(ArrayManager) support axis=1\n td.mark_array_manager_not_yet_implemented(request)\n\n df = DataFrame(\n {\n "A": [1.0, 2.0, 3.0, 4.0, np.nan, 5.0],\n "B": [2.0, 4.0, 6.0, np.nan, 8.0, 10.0],\n "C": [3.0, 6.0, 9.0, np.nan, np.nan, 30.0],\n }\n )\n if multiblock:\n df["D"] = np.nan\n df["E"] = 1.0\n\n method2 = method if method != "pad" else "ffill"\n expected = getattr(df, method2)(axis=axis)\n msg = f"DataFrame.interpolate with method={method} is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.interpolate(method=method, axis=axis)\n tm.assert_frame_equal(result, expected)\n\n def test_interpolate_empty_df(self):\n # GH#53199\n df = DataFrame()\n expected = df.copy()\n result = df.interpolate(inplace=True)\n assert result is None\n tm.assert_frame_equal(df, expected)\n\n def test_interpolate_ea(self, any_int_ea_dtype):\n # GH#55347\n df = DataFrame({"a": [1, None, None, None, 3]}, dtype=any_int_ea_dtype)\n orig = df.copy()\n result = df.interpolate(limit=2)\n expected = DataFrame({"a": [1, 1.5, 2.0, None, 3]}, dtype="Float64")\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(df, orig)\n\n @pytest.mark.parametrize(\n "dtype",\n [\n "Float64",\n "Float32",\n pytest.param("float32[pyarrow]", marks=td.skip_if_no("pyarrow")),\n pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow")),\n ],\n )\n def test_interpolate_ea_float(self, dtype):\n # GH#55347\n df = DataFrame({"a": [1, None, None, None, 3]}, dtype=dtype)\n orig = df.copy()\n result = df.interpolate(limit=2)\n expected = DataFrame({"a": [1, 1.5, 2.0, None, 3]}, dtype=dtype)\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(df, orig)\n\n @pytest.mark.parametrize(\n "dtype",\n ["int64", "uint64", "int32", "int16", "int8", "uint32", "uint16", "uint8"],\n )\n def test_interpolate_arrow(self, dtype):\n # GH#55347\n pytest.importorskip("pyarrow")\n df = DataFrame({"a": [1, None, None, None, 3]}, dtype=dtype + "[pyarrow]")\n result = df.interpolate(limit=2)\n expected = DataFrame({"a": [1, 1.5, 2.0, None, 3]}, dtype="float64[pyarrow]")\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_interpolate.py
test_interpolate.py
Python
20,273
0.95
0.074275
0.051867
awesome-app
982
2025-06-29T07:09:39.602755
GPL-3.0
true
42725eda6c73071ef65980de2fef64f7
import pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameSetItem:\n def test_isetitem_ea_df(self):\n # GH#49922\n df = DataFrame([[1, 2, 3], [4, 5, 6]])\n rhs = DataFrame([[11, 12], [13, 14]], dtype="Int64")\n\n df.isetitem([0, 1], rhs)\n expected = DataFrame(\n {\n 0: Series([11, 13], dtype="Int64"),\n 1: Series([12, 14], dtype="Int64"),\n 2: [3, 6],\n }\n )\n tm.assert_frame_equal(df, expected)\n\n def test_isetitem_ea_df_scalar_indexer(self):\n # GH#49922\n df = DataFrame([[1, 2, 3], [4, 5, 6]])\n rhs = DataFrame([[11], [13]], dtype="Int64")\n\n df.isetitem(2, rhs)\n expected = DataFrame(\n {\n 0: [1, 4],\n 1: [2, 5],\n 2: Series([11, 13], dtype="Int64"),\n }\n )\n tm.assert_frame_equal(df, expected)\n\n def test_isetitem_dimension_mismatch(self):\n # GH#51701\n df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]})\n value = df.copy()\n with pytest.raises(ValueError, match="Got 2 positions but value has 3 columns"):\n df.isetitem([1, 2], value)\n\n value = df.copy()\n with pytest.raises(ValueError, match="Got 2 positions but value has 1 columns"):\n df.isetitem([1, 2], value[["a"]])\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_isetitem.py
test_isetitem.py
Python
1,428
0.95
0.08
0.071429
vue-tools
823
2024-07-01T22:42:25.852239
BSD-3-Clause
true
15ec672428e925c1cdcfd0a2166ecba9
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n MultiIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameIsIn:\n def test_isin(self):\n # GH#4211\n df = DataFrame(\n {\n "vals": [1, 2, 3, 4],\n "ids": ["a", "b", "f", "n"],\n "ids2": ["a", "n", "c", "n"],\n },\n index=["foo", "bar", "baz", "qux"],\n )\n other = ["a", "b", "c"]\n\n result = df.isin(other)\n expected = DataFrame([df.loc[s].isin(other) for s in df.index])\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("empty", [[], Series(dtype=object), np.array([])])\n def test_isin_empty(self, empty):\n # GH#16991\n df = DataFrame({"A": ["a", "b", "c"], "B": ["a", "e", "f"]})\n expected = DataFrame(False, df.index, df.columns)\n\n result = df.isin(empty)\n tm.assert_frame_equal(result, expected)\n\n def test_isin_dict(self):\n df = DataFrame({"A": ["a", "b", "c"], "B": ["a", "e", "f"]})\n d = {"A": ["a"]}\n\n expected = DataFrame(False, df.index, df.columns)\n expected.loc[0, "A"] = True\n\n result = df.isin(d)\n tm.assert_frame_equal(result, expected)\n\n # non unique columns\n df = DataFrame({"A": ["a", "b", "c"], "B": ["a", "e", "f"]})\n df.columns = ["A", "A"]\n expected = DataFrame(False, df.index, df.columns)\n expected.loc[0, "A"] = True\n result = df.isin(d)\n tm.assert_frame_equal(result, expected)\n\n def test_isin_with_string_scalar(self):\n # GH#4763\n df = DataFrame(\n {\n "vals": [1, 2, 3, 4],\n "ids": ["a", "b", "f", "n"],\n "ids2": ["a", "n", "c", "n"],\n },\n index=["foo", "bar", "baz", "qux"],\n )\n msg = (\n r"only list-like or dict-like objects are allowed "\n r"to be passed to DataFrame.isin\(\), you passed a 'str'"\n )\n with pytest.raises(TypeError, match=msg):\n df.isin("a")\n\n with pytest.raises(TypeError, match=msg):\n df.isin("aaa")\n\n def test_isin_df(self):\n df1 = DataFrame({"A": [1, 2, 3, 4], "B": [2, np.nan, 4, 4]})\n df2 = DataFrame({"A": [0, 2, 12, 4], "B": [2, np.nan, 4, 5]})\n expected = DataFrame(False, df1.index, df1.columns)\n result = df1.isin(df2)\n expected.loc[[1, 3], "A"] = True\n expected.loc[[0, 2], "B"] = True\n tm.assert_frame_equal(result, expected)\n\n # partial overlapping columns\n df2.columns = ["A", "C"]\n result = df1.isin(df2)\n expected["B"] = False\n tm.assert_frame_equal(result, expected)\n\n def test_isin_tuples(self):\n # GH#16394\n df = DataFrame({"A": [1, 2, 3], "B": ["a", "b", "f"]})\n df["C"] = list(zip(df["A"], df["B"]))\n result = df["C"].isin([(1, "a")])\n tm.assert_series_equal(result, Series([True, False, False], name="C"))\n\n def test_isin_df_dupe_values(self):\n df1 = DataFrame({"A": [1, 2, 3, 4], "B": [2, np.nan, 4, 4]})\n # just cols duped\n df2 = DataFrame([[0, 2], [12, 4], [2, np.nan], [4, 5]], columns=["B", "B"])\n msg = r"cannot compute isin with a duplicate axis\."\n with pytest.raises(ValueError, match=msg):\n df1.isin(df2)\n\n # just index duped\n df2 = DataFrame(\n [[0, 2], [12, 4], [2, np.nan], [4, 5]],\n columns=["A", "B"],\n index=[0, 0, 1, 1],\n )\n with pytest.raises(ValueError, match=msg):\n df1.isin(df2)\n\n # cols and index:\n df2.columns = ["B", "B"]\n with pytest.raises(ValueError, match=msg):\n df1.isin(df2)\n\n def test_isin_dupe_self(self):\n other = DataFrame({"A": [1, 0, 1, 0], "B": [1, 1, 0, 0]})\n df = DataFrame([[1, 1], [1, 0], [0, 0]], columns=["A", "A"])\n result = df.isin(other)\n expected = DataFrame(False, index=df.index, columns=df.columns)\n expected.loc[0] = True\n expected.iloc[1, 1] = True\n tm.assert_frame_equal(result, expected)\n\n def test_isin_against_series(self):\n df = DataFrame(\n {"A": [1, 2, 3, 4], "B": [2, np.nan, 4, 4]}, index=["a", "b", "c", "d"]\n )\n s = Series([1, 3, 11, 4], index=["a", "b", "c", "d"])\n expected = DataFrame(False, index=df.index, columns=df.columns)\n expected.loc["a", "A"] = True\n expected.loc["d"] = True\n result = df.isin(s)\n tm.assert_frame_equal(result, expected)\n\n def test_isin_multiIndex(self):\n idx = MultiIndex.from_tuples(\n [\n (0, "a", "foo"),\n (0, "a", "bar"),\n (0, "b", "bar"),\n (0, "b", "baz"),\n (2, "a", "foo"),\n (2, "a", "bar"),\n (2, "c", "bar"),\n (2, "c", "baz"),\n (1, "b", "foo"),\n (1, "b", "bar"),\n (1, "c", "bar"),\n (1, "c", "baz"),\n ]\n )\n df1 = DataFrame({"A": np.ones(12), "B": np.zeros(12)}, index=idx)\n df2 = DataFrame(\n {\n "A": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],\n "B": [1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1],\n }\n )\n # against regular index\n expected = DataFrame(False, index=df1.index, columns=df1.columns)\n result = df1.isin(df2)\n tm.assert_frame_equal(result, expected)\n\n df2.index = idx\n expected = df2.values.astype(bool)\n expected[:, 1] = ~expected[:, 1]\n expected = DataFrame(expected, columns=["A", "B"], index=idx)\n\n result = df1.isin(df2)\n tm.assert_frame_equal(result, expected)\n\n def test_isin_empty_datetimelike(self):\n # GH#15473\n df1_ts = DataFrame({"date": pd.to_datetime(["2014-01-01", "2014-01-02"])})\n df1_td = DataFrame({"date": [pd.Timedelta(1, "s"), pd.Timedelta(2, "s")]})\n df2 = DataFrame({"date": []})\n df3 = DataFrame()\n\n expected = DataFrame({"date": [False, False]})\n\n result = df1_ts.isin(df2)\n tm.assert_frame_equal(result, expected)\n result = df1_ts.isin(df3)\n tm.assert_frame_equal(result, expected)\n\n result = df1_td.isin(df2)\n tm.assert_frame_equal(result, expected)\n result = df1_td.isin(df3)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "values",\n [\n DataFrame({"a": [1, 2, 3]}, dtype="category"),\n Series([1, 2, 3], dtype="category"),\n ],\n )\n def test_isin_category_frame(self, values):\n # GH#34256\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n expected = DataFrame({"a": [True, True, True], "b": [False, False, False]})\n\n result = df.isin(values)\n tm.assert_frame_equal(result, expected)\n\n def test_isin_read_only(self):\n # https://github.com/pandas-dev/pandas/issues/37174\n arr = np.array([1, 2, 3])\n arr.setflags(write=False)\n df = DataFrame([1, 2, 3])\n result = df.isin(arr)\n expected = DataFrame([True, True, True])\n tm.assert_frame_equal(result, expected)\n\n def test_isin_not_lossy(self):\n # GH 53514\n val = 1666880195890293744\n df = DataFrame({"a": [val], "b": [1.0]})\n result = df.isin([val])\n expected = DataFrame({"a": [True], "b": [False]})\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_isin.py
test_isin.py
Python
7,599
0.95
0.070485
0.071429
vue-tools
377
2024-04-21T13:25:32.993156
MIT
true
3c1e82c47ddccbd83e1bca4f4c793ee7
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n Categorical,\n DataFrame,\n)\n\n# _is_homogeneous_type always returns True for ArrayManager\npytestmark = td.skip_array_manager_invalid_test\n\n\n@pytest.mark.parametrize(\n "data, expected",\n [\n # empty\n (DataFrame(), True),\n # multi-same\n (DataFrame({"A": [1, 2], "B": [1, 2]}), True),\n # multi-object\n (\n DataFrame(\n {\n "A": np.array([1, 2], dtype=object),\n "B": np.array(["a", "b"], dtype=object),\n },\n dtype="object",\n ),\n True,\n ),\n # multi-extension\n (\n DataFrame({"A": Categorical(["a", "b"]), "B": Categorical(["a", "b"])}),\n True,\n ),\n # differ types\n (DataFrame({"A": [1, 2], "B": [1.0, 2.0]}), False),\n # differ sizes\n (\n DataFrame(\n {\n "A": np.array([1, 2], dtype=np.int32),\n "B": np.array([1, 2], dtype=np.int64),\n }\n ),\n False,\n ),\n # multi-extension differ\n (\n DataFrame({"A": Categorical(["a", "b"]), "B": Categorical(["b", "c"])}),\n False,\n ),\n ],\n)\ndef test_is_homogeneous_type(data, expected):\n assert data._is_homogeneous_type is expected\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_is_homogeneous_dtype.py
test_is_homogeneous_dtype.py
Python
1,455
0.95
0.034483
0.150943
vue-tools
364
2024-07-05T18:04:04.786653
MIT
true
081f90f3677698e11777dbb7980d9743
from pandas import (\n DataFrame,\n Timedelta,\n)\n\n\ndef test_no_overflow_of_freq_and_time_in_dataframe():\n # GH 35665\n df = DataFrame(\n {\n "some_string": ["2222Y3"],\n "time": [Timedelta("0 days 00:00:00.990000")],\n }\n )\n for _, row in df.iterrows():\n assert row.dtype == "object"\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_iterrows.py
test_iterrows.py
Python
338
0.95
0.125
0.071429
node-utils
295
2023-07-27T13:21:49.579829
Apache-2.0
true
a47a2c65ea16865192fefc61df94fec8
from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import MergeError\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\nfrom pandas.core.reshape.concat import concat\n\n\n@pytest.fixture\ndef frame_with_period_index():\n return DataFrame(\n data=np.arange(20).reshape(4, 5),\n columns=list("abcde"),\n index=period_range(start="2000", freq="Y", periods=4),\n )\n\n\n@pytest.fixture\ndef left():\n return DataFrame({"a": [20, 10, 0]}, index=[2, 1, 0])\n\n\n@pytest.fixture\ndef right():\n return DataFrame({"b": [300, 100, 200]}, index=[3, 1, 2])\n\n\n@pytest.fixture\ndef left_no_dup():\n return DataFrame(\n {"a": ["a", "b", "c", "d"], "b": ["cat", "dog", "weasel", "horse"]},\n index=range(4),\n )\n\n\n@pytest.fixture\ndef right_no_dup():\n return DataFrame(\n {\n "a": ["a", "b", "c", "d", "e"],\n "c": ["meow", "bark", "um... weasel noise?", "nay", "chirp"],\n },\n index=range(5),\n ).set_index("a")\n\n\n@pytest.fixture\ndef left_w_dups(left_no_dup):\n return concat(\n [left_no_dup, DataFrame({"a": ["a"], "b": ["cow"]}, index=[3])], sort=True\n )\n\n\n@pytest.fixture\ndef right_w_dups(right_no_dup):\n return concat(\n [right_no_dup, DataFrame({"a": ["e"], "c": ["moo"]}, index=[3])]\n ).set_index("a")\n\n\n@pytest.mark.parametrize(\n "how, sort, expected",\n [\n ("inner", False, DataFrame({"a": [20, 10], "b": [200, 100]}, index=[2, 1])),\n ("inner", True, DataFrame({"a": [10, 20], "b": [100, 200]}, index=[1, 2])),\n (\n "left",\n False,\n DataFrame({"a": [20, 10, 0], "b": [200, 100, np.nan]}, index=[2, 1, 0]),\n ),\n (\n "left",\n True,\n DataFrame({"a": [0, 10, 20], "b": [np.nan, 100, 200]}, index=[0, 1, 2]),\n ),\n (\n "right",\n False,\n DataFrame({"a": [np.nan, 10, 20], "b": [300, 100, 200]}, index=[3, 1, 2]),\n ),\n (\n "right",\n True,\n DataFrame({"a": [10, 20, np.nan], "b": [100, 200, 300]}, index=[1, 2, 3]),\n ),\n (\n "outer",\n False,\n DataFrame(\n {"a": [0, 10, 20, np.nan], "b": [np.nan, 100, 200, 300]},\n index=[0, 1, 2, 3],\n ),\n ),\n (\n "outer",\n True,\n DataFrame(\n {"a": [0, 10, 20, np.nan], "b": [np.nan, 100, 200, 300]},\n index=[0, 1, 2, 3],\n ),\n ),\n ],\n)\ndef test_join(left, right, how, sort, expected):\n result = left.join(right, how=how, sort=sort, validate="1:1")\n tm.assert_frame_equal(result, expected)\n\n\ndef test_suffix_on_list_join():\n first = DataFrame({"key": [1, 2, 3, 4, 5]})\n second = DataFrame({"key": [1, 8, 3, 2, 5], "v1": [1, 2, 3, 4, 5]})\n third = DataFrame({"keys": [5, 2, 3, 4, 1], "v2": [1, 2, 3, 4, 5]})\n\n # check proper errors are raised\n msg = "Suffixes not supported when joining multiple DataFrames"\n with pytest.raises(ValueError, match=msg):\n first.join([second], lsuffix="y")\n with pytest.raises(ValueError, match=msg):\n first.join([second, third], rsuffix="x")\n with pytest.raises(ValueError, match=msg):\n first.join([second, third], lsuffix="y", rsuffix="x")\n with pytest.raises(ValueError, match="Indexes have overlapping values"):\n first.join([second, third])\n\n # no errors should be raised\n arr_joined = first.join([third])\n norm_joined = first.join(third)\n tm.assert_frame_equal(arr_joined, norm_joined)\n\n\ndef test_join_invalid_validate(left_no_dup, right_no_dup):\n # GH 46622\n # Check invalid arguments\n msg = (\n '"invalid" is not a valid argument. '\n "Valid arguments are:\n"\n '- "1:1"\n'\n '- "1:m"\n'\n '- "m:1"\n'\n '- "m:m"\n'\n '- "one_to_one"\n'\n '- "one_to_many"\n'\n '- "many_to_one"\n'\n '- "many_to_many"'\n )\n with pytest.raises(ValueError, match=msg):\n left_no_dup.merge(right_no_dup, on="a", validate="invalid")\n\n\n@pytest.mark.parametrize("dtype", ["object", "string[pyarrow]"])\ndef test_join_on_single_col_dup_on_right(left_no_dup, right_w_dups, dtype):\n # GH 46622\n # Dups on right allowed by one_to_many constraint\n if dtype == "string[pyarrow]":\n pytest.importorskip("pyarrow")\n left_no_dup = left_no_dup.astype(dtype)\n right_w_dups.index = right_w_dups.index.astype(dtype)\n left_no_dup.join(\n right_w_dups,\n on="a",\n validate="one_to_many",\n )\n\n # Dups on right not allowed by one_to_one constraint\n msg = "Merge keys are not unique in right dataset; not a one-to-one merge"\n with pytest.raises(MergeError, match=msg):\n left_no_dup.join(\n right_w_dups,\n on="a",\n validate="one_to_one",\n )\n\n\ndef test_join_on_single_col_dup_on_left(left_w_dups, right_no_dup):\n # GH 46622\n # Dups on left allowed by many_to_one constraint\n left_w_dups.join(\n right_no_dup,\n on="a",\n validate="many_to_one",\n )\n\n # Dups on left not allowed by one_to_one constraint\n msg = "Merge keys are not unique in left dataset; not a one-to-one merge"\n with pytest.raises(MergeError, match=msg):\n left_w_dups.join(\n right_no_dup,\n on="a",\n validate="one_to_one",\n )\n\n\ndef test_join_on_single_col_dup_on_both(left_w_dups, right_w_dups):\n # GH 46622\n # Dups on both allowed by many_to_many constraint\n left_w_dups.join(right_w_dups, on="a", validate="many_to_many")\n\n # Dups on both not allowed by many_to_one constraint\n msg = "Merge keys are not unique in right dataset; not a many-to-one merge"\n with pytest.raises(MergeError, match=msg):\n left_w_dups.join(\n right_w_dups,\n on="a",\n validate="many_to_one",\n )\n\n # Dups on both not allowed by one_to_many constraint\n msg = "Merge keys are not unique in left dataset; not a one-to-many merge"\n with pytest.raises(MergeError, match=msg):\n left_w_dups.join(\n right_w_dups,\n on="a",\n validate="one_to_many",\n )\n\n\ndef test_join_on_multi_col_check_dup():\n # GH 46622\n # Two column join, dups in both, but jointly no dups\n left = DataFrame(\n {\n "a": ["a", "a", "b", "b"],\n "b": [0, 1, 0, 1],\n "c": ["cat", "dog", "weasel", "horse"],\n },\n index=range(4),\n ).set_index(["a", "b"])\n\n right = DataFrame(\n {\n "a": ["a", "a", "b"],\n "b": [0, 1, 0],\n "d": ["meow", "bark", "um... weasel noise?"],\n },\n index=range(3),\n ).set_index(["a", "b"])\n\n expected_multi = DataFrame(\n {\n "a": ["a", "a", "b"],\n "b": [0, 1, 0],\n "c": ["cat", "dog", "weasel"],\n "d": ["meow", "bark", "um... weasel noise?"],\n },\n index=range(3),\n ).set_index(["a", "b"])\n\n # Jointly no dups allowed by one_to_one constraint\n result = left.join(right, how="inner", validate="1:1")\n tm.assert_frame_equal(result, expected_multi)\n\n\ndef test_join_index(float_frame):\n # left / right\n\n f = float_frame.loc[float_frame.index[:10], ["A", "B"]]\n f2 = float_frame.loc[float_frame.index[5:], ["C", "D"]].iloc[::-1]\n\n joined = f.join(f2)\n tm.assert_index_equal(f.index, joined.index)\n expected_columns = Index(["A", "B", "C", "D"])\n tm.assert_index_equal(joined.columns, expected_columns)\n\n joined = f.join(f2, how="left")\n tm.assert_index_equal(joined.index, f.index)\n tm.assert_index_equal(joined.columns, expected_columns)\n\n joined = f.join(f2, how="right")\n tm.assert_index_equal(joined.index, f2.index)\n tm.assert_index_equal(joined.columns, expected_columns)\n\n # inner\n\n joined = f.join(f2, how="inner")\n tm.assert_index_equal(joined.index, f.index[5:10])\n tm.assert_index_equal(joined.columns, expected_columns)\n\n # outer\n\n joined = f.join(f2, how="outer")\n tm.assert_index_equal(joined.index, float_frame.index.sort_values())\n tm.assert_index_equal(joined.columns, expected_columns)\n\n with pytest.raises(ValueError, match="join method"):\n f.join(f2, how="foo")\n\n # corner case - overlapping columns\n msg = "columns overlap but no suffix"\n for how in ("outer", "left", "inner"):\n with pytest.raises(ValueError, match=msg):\n float_frame.join(float_frame, how=how)\n\n\ndef test_join_index_more(float_frame):\n af = float_frame.loc[:, ["A", "B"]]\n bf = float_frame.loc[::2, ["C", "D"]]\n\n expected = af.copy()\n expected["C"] = float_frame["C"][::2]\n expected["D"] = float_frame["D"][::2]\n\n result = af.join(bf)\n tm.assert_frame_equal(result, expected)\n\n result = af.join(bf, how="right")\n tm.assert_frame_equal(result, expected[::2])\n\n result = bf.join(af, how="right")\n tm.assert_frame_equal(result, expected.loc[:, result.columns])\n\n\ndef test_join_index_series(float_frame):\n df = float_frame.copy()\n ser = df.pop(float_frame.columns[-1])\n joined = df.join(ser)\n\n tm.assert_frame_equal(joined, float_frame)\n\n ser.name = None\n with pytest.raises(ValueError, match="must have a name"):\n df.join(ser)\n\n\ndef test_join_overlap(float_frame):\n df1 = float_frame.loc[:, ["A", "B", "C"]]\n df2 = float_frame.loc[:, ["B", "C", "D"]]\n\n joined = df1.join(df2, lsuffix="_df1", rsuffix="_df2")\n df1_suf = df1.loc[:, ["B", "C"]].add_suffix("_df1")\n df2_suf = df2.loc[:, ["B", "C"]].add_suffix("_df2")\n\n no_overlap = float_frame.loc[:, ["A", "D"]]\n expected = df1_suf.join(df2_suf).join(no_overlap)\n\n # column order not necessarily sorted\n tm.assert_frame_equal(joined, expected.loc[:, joined.columns])\n\n\ndef test_join_period_index(frame_with_period_index):\n other = frame_with_period_index.rename(columns=lambda key: f"{key}{key}")\n\n joined_values = np.concatenate([frame_with_period_index.values] * 2, axis=1)\n\n joined_cols = frame_with_period_index.columns.append(other.columns)\n\n joined = frame_with_period_index.join(other)\n expected = DataFrame(\n data=joined_values, columns=joined_cols, index=frame_with_period_index.index\n )\n\n tm.assert_frame_equal(joined, expected)\n\n\ndef test_join_left_sequence_non_unique_index():\n # https://github.com/pandas-dev/pandas/issues/19607\n df1 = DataFrame({"a": [0, 10, 20]}, index=[1, 2, 3])\n df2 = DataFrame({"b": [100, 200, 300]}, index=[4, 3, 2])\n df3 = DataFrame({"c": [400, 500, 600]}, index=[2, 2, 4])\n\n joined = df1.join([df2, df3], how="left")\n\n expected = DataFrame(\n {\n "a": [0, 10, 10, 20],\n "b": [np.nan, 300, 300, 200],\n "c": [np.nan, 400, 500, np.nan],\n },\n index=[1, 2, 2, 3],\n )\n\n tm.assert_frame_equal(joined, expected)\n\n\ndef test_join_list_series(float_frame):\n # GH#46850\n # Join a DataFrame with a list containing both a Series and a DataFrame\n left = float_frame.A.to_frame()\n right = [float_frame.B, float_frame[["C", "D"]]]\n result = left.join(right)\n tm.assert_frame_equal(result, float_frame)\n\n\n@pytest.mark.parametrize("sort_kw", [True, False])\ndef test_suppress_future_warning_with_sort_kw(sort_kw):\n a = DataFrame({"col1": [1, 2]}, index=["c", "a"])\n\n b = DataFrame({"col2": [4, 5]}, index=["b", "a"])\n\n c = DataFrame({"col3": [7, 8]}, index=["a", "b"])\n\n expected = DataFrame(\n {\n "col1": {"a": 2.0, "b": float("nan"), "c": 1.0},\n "col2": {"a": 5.0, "b": 4.0, "c": float("nan")},\n "col3": {"a": 7.0, "b": 8.0, "c": float("nan")},\n }\n )\n if sort_kw is False:\n expected = expected.reindex(index=["c", "a", "b"])\n\n with tm.assert_produces_warning(None):\n result = a.join([b, c], how="outer", sort=sort_kw)\n tm.assert_frame_equal(result, expected)\n\n\nclass TestDataFrameJoin:\n def test_join(self, multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n\n a = frame.loc[frame.index[:5], ["A"]]\n b = frame.loc[frame.index[2:], ["B", "C"]]\n\n joined = a.join(b, how="outer").reindex(frame.index)\n expected = frame.copy().values.copy()\n expected[np.isnan(joined.values)] = np.nan\n expected = DataFrame(expected, index=frame.index, columns=frame.columns)\n\n assert not np.isnan(joined.values).all()\n\n tm.assert_frame_equal(joined, expected)\n\n def test_join_segfault(self):\n # GH#1532\n df1 = DataFrame({"a": [1, 1], "b": [1, 2], "x": [1, 2]})\n df2 = DataFrame({"a": [2, 2], "b": [1, 2], "y": [1, 2]})\n df1 = df1.set_index(["a", "b"])\n df2 = df2.set_index(["a", "b"])\n # it works!\n for how in ["left", "right", "outer"]:\n df1.join(df2, how=how)\n\n def test_join_str_datetime(self):\n str_dates = ["20120209", "20120222"]\n dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)]\n\n A = DataFrame(str_dates, index=range(2), columns=["aa"])\n C = DataFrame([[1, 2], [3, 4]], index=str_dates, columns=dt_dates)\n\n tst = A.join(C, on="aa")\n\n assert len(tst.columns) == 3\n\n def test_join_multiindex_leftright(self):\n # GH 10741\n df1 = DataFrame(\n [\n ["a", "x", 0.471780],\n ["a", "y", 0.774908],\n ["a", "z", 0.563634],\n ["b", "x", -0.353756],\n ["b", "y", 0.368062],\n ["b", "z", -1.721840],\n ["c", "x", 1],\n ["c", "y", 2],\n ["c", "z", 3],\n ],\n columns=["first", "second", "value1"],\n ).set_index(["first", "second"])\n\n df2 = DataFrame([["a", 10], ["b", 20]], columns=["first", "value2"]).set_index(\n ["first"]\n )\n\n exp = DataFrame(\n [\n [0.471780, 10],\n [0.774908, 10],\n [0.563634, 10],\n [-0.353756, 20],\n [0.368062, 20],\n [-1.721840, 20],\n [1.000000, np.nan],\n [2.000000, np.nan],\n [3.000000, np.nan],\n ],\n index=df1.index,\n columns=["value1", "value2"],\n )\n\n # these must be the same results (but columns are flipped)\n tm.assert_frame_equal(df1.join(df2, how="left"), exp)\n tm.assert_frame_equal(df2.join(df1, how="right"), exp[["value2", "value1"]])\n\n exp_idx = MultiIndex.from_product(\n [["a", "b"], ["x", "y", "z"]], names=["first", "second"]\n )\n exp = DataFrame(\n [\n [0.471780, 10],\n [0.774908, 10],\n [0.563634, 10],\n [-0.353756, 20],\n [0.368062, 20],\n [-1.721840, 20],\n ],\n index=exp_idx,\n columns=["value1", "value2"],\n )\n\n tm.assert_frame_equal(df1.join(df2, how="right"), exp)\n tm.assert_frame_equal(df2.join(df1, how="left"), exp[["value2", "value1"]])\n\n def test_join_multiindex_dates(self):\n # GH 33692\n date = pd.Timestamp(2000, 1, 1).date()\n\n df1_index = MultiIndex.from_tuples([(0, date)], names=["index_0", "date"])\n df1 = DataFrame({"col1": [0]}, index=df1_index)\n df2_index = MultiIndex.from_tuples([(0, date)], names=["index_0", "date"])\n df2 = DataFrame({"col2": [0]}, index=df2_index)\n df3_index = MultiIndex.from_tuples([(0, date)], names=["index_0", "date"])\n df3 = DataFrame({"col3": [0]}, index=df3_index)\n\n result = df1.join([df2, df3])\n\n expected_index = MultiIndex.from_tuples([(0, date)], names=["index_0", "date"])\n expected = DataFrame(\n {"col1": [0], "col2": [0], "col3": [0]}, index=expected_index\n )\n\n tm.assert_equal(result, expected)\n\n def test_merge_join_different_levels_raises(self):\n # GH#9455\n # GH 40993: For raising, enforced in 2.0\n\n # first dataframe\n df1 = DataFrame(columns=["a", "b"], data=[[1, 11], [0, 22]])\n\n # second dataframe\n columns = MultiIndex.from_tuples([("a", ""), ("c", "c1")])\n df2 = DataFrame(columns=columns, data=[[1, 33], [0, 44]])\n\n # merge\n with pytest.raises(\n MergeError, match="Not allowed to merge between different levels"\n ):\n pd.merge(df1, df2, on="a")\n\n # join, see discussion in GH#12219\n with pytest.raises(\n MergeError, match="Not allowed to merge between different levels"\n ):\n df1.join(df2, on="a")\n\n def test_frame_join_tzaware(self):\n test1 = DataFrame(\n np.zeros((6, 3)),\n index=date_range(\n "2012-11-15 00:00:00", periods=6, freq="100ms", tz="US/Central"\n ),\n )\n test2 = DataFrame(\n np.zeros((3, 3)),\n index=date_range(\n "2012-11-15 00:00:00", periods=3, freq="250ms", tz="US/Central"\n ),\n columns=range(3, 6),\n )\n\n result = test1.join(test2, how="outer")\n expected = test1.index.union(test2.index)\n\n tm.assert_index_equal(result.index, expected)\n assert result.index.tz.zone == "US/Central"\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_join.py
test_join.py
Python
17,523
0.95
0.059028
0.078261
vue-tools
914
2024-09-10T03:37:18.077058
BSD-3-Clause
true
24d379f90961137967bf3410ca22ae06
from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Series,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\n\nfrom pandas.tseries.offsets import BDay\n\n\ndef test_map(float_frame):\n result = float_frame.map(lambda x: x * 2)\n tm.assert_frame_equal(result, float_frame * 2)\n float_frame.map(type)\n\n # GH 465: function returning tuples\n result = float_frame.map(lambda x: (x, x))["A"].iloc[0]\n assert isinstance(result, tuple)\n\n\n@pytest.mark.parametrize("val", [1, 1.0])\ndef test_map_float_object_conversion(val):\n # GH 2909: object conversion to float in constructor?\n df = DataFrame(data=[val, "a"])\n result = df.map(lambda x: x).dtypes[0]\n assert result == object\n\n\n@pytest.mark.parametrize("na_action", [None, "ignore"])\ndef test_map_keeps_dtype(na_action):\n # GH52219\n arr = Series(["a", np.nan, "b"])\n sparse_arr = arr.astype(pd.SparseDtype(object))\n df = DataFrame(data={"a": arr, "b": sparse_arr})\n\n def func(x):\n return str.upper(x) if not pd.isna(x) else x\n\n result = df.map(func, na_action=na_action)\n\n expected_sparse = pd.array(["A", np.nan, "B"], dtype=pd.SparseDtype(object))\n expected_arr = expected_sparse.astype(object)\n expected = DataFrame({"a": expected_arr, "b": expected_sparse})\n\n tm.assert_frame_equal(result, expected)\n\n result_empty = df.iloc[:0, :].map(func, na_action=na_action)\n expected_empty = expected.iloc[:0, :]\n tm.assert_frame_equal(result_empty, expected_empty)\n\n\ndef test_map_str():\n # GH 2786\n df = DataFrame(np.random.default_rng(2).random((3, 4)))\n df2 = df.copy()\n cols = ["a", "a", "a", "a"]\n df.columns = cols\n\n expected = df2.map(str)\n expected.columns = cols\n result = df.map(str)\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "col, val",\n [["datetime", Timestamp("20130101")], ["timedelta", pd.Timedelta("1 min")]],\n)\ndef test_map_datetimelike(col, val):\n # datetime/timedelta\n df = DataFrame(np.random.default_rng(2).random((3, 4)))\n df[col] = val\n result = df.map(str)\n assert result.loc[0, col] == str(df.loc[0, col])\n\n\n@pytest.mark.parametrize(\n "expected",\n [\n DataFrame(),\n DataFrame(columns=list("ABC")),\n DataFrame(index=list("ABC")),\n DataFrame({"A": [], "B": [], "C": []}),\n ],\n)\n@pytest.mark.parametrize("func", [round, lambda x: x])\ndef test_map_empty(expected, func):\n # GH 8222\n result = expected.map(func)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_map_kwargs():\n # GH 40652\n result = DataFrame([[1, 2], [3, 4]]).map(lambda x, y: x + y, y=2)\n expected = DataFrame([[3, 4], [5, 6]])\n tm.assert_frame_equal(result, expected)\n\n\ndef test_map_na_ignore(float_frame):\n # GH 23803\n strlen_frame = float_frame.map(lambda x: len(str(x)))\n float_frame_with_na = float_frame.copy()\n mask = np.random.default_rng(2).integers(0, 2, size=float_frame.shape, dtype=bool)\n float_frame_with_na[mask] = pd.NA\n strlen_frame_na_ignore = float_frame_with_na.map(\n lambda x: len(str(x)), na_action="ignore"\n )\n # Set float64 type to avoid upcast when setting NA below\n strlen_frame_with_na = strlen_frame.copy().astype("float64")\n strlen_frame_with_na[mask] = pd.NA\n tm.assert_frame_equal(strlen_frame_na_ignore, strlen_frame_with_na)\n\n\ndef test_map_box_timestamps():\n # GH 2689, GH 2627\n ser = Series(date_range("1/1/2000", periods=10))\n\n def func(x):\n return (x.hour, x.day, x.month)\n\n # it works!\n DataFrame(ser).map(func)\n\n\ndef test_map_box():\n # ufunc will not be boxed. Same test cases as the test_map_box\n df = DataFrame(\n {\n "a": [Timestamp("2011-01-01"), Timestamp("2011-01-02")],\n "b": [\n Timestamp("2011-01-01", tz="US/Eastern"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n ],\n "c": [pd.Timedelta("1 days"), pd.Timedelta("2 days")],\n "d": [\n pd.Period("2011-01-01", freq="M"),\n pd.Period("2011-01-02", freq="M"),\n ],\n }\n )\n\n result = df.map(lambda x: type(x).__name__)\n expected = DataFrame(\n {\n "a": ["Timestamp", "Timestamp"],\n "b": ["Timestamp", "Timestamp"],\n "c": ["Timedelta", "Timedelta"],\n "d": ["Period", "Period"],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_frame_map_dont_convert_datetime64():\n df = DataFrame({"x1": [datetime(1996, 1, 1)]})\n\n df = df.map(lambda x: x + BDay())\n df = df.map(lambda x: x + BDay())\n\n result = df.x1.dtype\n assert result == "M8[ns]"\n\n\ndef test_map_function_runs_once():\n df = DataFrame({"a": [1, 2, 3]})\n values = [] # Save values function is applied to\n\n def reducing_function(val):\n values.append(val)\n\n def non_reducing_function(val):\n values.append(val)\n return val\n\n for func in [reducing_function, non_reducing_function]:\n del values[:]\n\n df.map(func)\n assert values == df.a.to_list()\n\n\ndef test_map_type():\n # GH 46719\n df = DataFrame(\n {"col1": [3, "string", float], "col2": [0.25, datetime(2020, 1, 1), np.nan]},\n index=["a", "b", "c"],\n )\n\n result = df.map(type)\n expected = DataFrame(\n {"col1": [int, str, type], "col2": [float, datetime, float]},\n index=["a", "b", "c"],\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_map_invalid_na_action(float_frame):\n # GH 23803\n with pytest.raises(ValueError, match="na_action must be .*Got 'abc'"):\n float_frame.map(lambda x: len(str(x)), na_action="abc")\n\n\ndef test_applymap_deprecated():\n # GH52353\n df = DataFrame({"a": [1, 2, 3]})\n msg = "DataFrame.applymap has been deprecated. Use DataFrame.map instead."\n with tm.assert_produces_warning(FutureWarning, match=msg):\n df.applymap(lambda x: x)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_map.py
test_map.py
Python
5,994
0.95
0.106481
0.090361
python-kit
741
2024-01-08T11:37:53.902484
Apache-2.0
true
3b48c0886ea67798255c233bd2a755fd
import operator\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestMatMul:\n def test_matmul(self):\n # matmul test is for GH#10259\n a = DataFrame(\n np.random.default_rng(2).standard_normal((3, 4)),\n index=["a", "b", "c"],\n columns=["p", "q", "r", "s"],\n )\n b = DataFrame(\n np.random.default_rng(2).standard_normal((4, 2)),\n index=["p", "q", "r", "s"],\n columns=["one", "two"],\n )\n\n # DataFrame @ DataFrame\n result = operator.matmul(a, b)\n expected = DataFrame(\n np.dot(a.values, b.values), index=["a", "b", "c"], columns=["one", "two"]\n )\n tm.assert_frame_equal(result, expected)\n\n # DataFrame @ Series\n result = operator.matmul(a, b.one)\n expected = Series(np.dot(a.values, b.one.values), index=["a", "b", "c"])\n tm.assert_series_equal(result, expected)\n\n # np.array @ DataFrame\n result = operator.matmul(a.values, b)\n assert isinstance(result, DataFrame)\n assert result.columns.equals(b.columns)\n assert result.index.equals(Index(range(3)))\n expected = np.dot(a.values, b.values)\n tm.assert_almost_equal(result.values, expected)\n\n # nested list @ DataFrame (__rmatmul__)\n result = operator.matmul(a.values.tolist(), b)\n expected = DataFrame(\n np.dot(a.values, b.values), index=["a", "b", "c"], columns=["one", "two"]\n )\n tm.assert_almost_equal(result.values, expected.values)\n\n # mixed dtype DataFrame @ DataFrame\n a["q"] = a.q.round().astype(int)\n result = operator.matmul(a, b)\n expected = DataFrame(\n np.dot(a.values, b.values), index=["a", "b", "c"], columns=["one", "two"]\n )\n tm.assert_frame_equal(result, expected)\n\n # different dtypes DataFrame @ DataFrame\n a = a.astype(int)\n result = operator.matmul(a, b)\n expected = DataFrame(\n np.dot(a.values, b.values), index=["a", "b", "c"], columns=["one", "two"]\n )\n tm.assert_frame_equal(result, expected)\n\n # unaligned\n df = DataFrame(\n np.random.default_rng(2).standard_normal((3, 4)),\n index=[1, 2, 3],\n columns=range(4),\n )\n df2 = DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)),\n index=range(5),\n columns=[1, 2, 3],\n )\n\n with pytest.raises(ValueError, match="aligned"):\n operator.matmul(df, df2)\n\n def test_matmul_message_shapes(self):\n # GH#21581 exception message should reflect original shapes,\n # not transposed shapes\n a = np.random.default_rng(2).random((10, 4))\n b = np.random.default_rng(2).random((5, 3))\n\n df = DataFrame(b)\n\n msg = r"shapes \(10, 4\) and \(5, 3\) not aligned"\n with pytest.raises(ValueError, match=msg):\n a @ df\n with pytest.raises(ValueError, match=msg):\n a.tolist() @ df\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_matmul.py
test_matmul.py
Python
3,137
0.95
0.040816
0.120482
awesome-app
265
2024-11-09T10:00:23.980239
MIT
true
c93448733a67b164aa3bf13a9b001a98
"""\nNote: for naming purposes, most tests are title with as e.g. "test_nlargest_foo"\nbut are implicitly also testing nsmallest_foo.\n"""\nfrom string import ascii_lowercase\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.util.version import Version\n\n\n@pytest.fixture\ndef df_duplicates():\n return pd.DataFrame(\n {"a": [1, 2, 3, 4, 4], "b": [1, 1, 1, 1, 1], "c": [0, 1, 2, 5, 4]},\n index=[0, 0, 1, 1, 1],\n )\n\n\n@pytest.fixture\ndef df_strings():\n return pd.DataFrame(\n {\n "a": np.random.default_rng(2).permutation(10),\n "b": list(ascii_lowercase[:10]),\n "c": np.random.default_rng(2).permutation(10).astype("float64"),\n }\n )\n\n\n@pytest.fixture\ndef df_main_dtypes():\n return pd.DataFrame(\n {\n "group": [1, 1, 2],\n "int": [1, 2, 3],\n "float": [4.0, 5.0, 6.0],\n "string": list("abc"),\n "category_string": pd.Series(list("abc")).astype("category"),\n "category_int": [7, 8, 9],\n "datetime": pd.date_range("20130101", periods=3),\n "datetimetz": pd.date_range("20130101", periods=3, tz="US/Eastern"),\n "timedelta": pd.timedelta_range("1 s", periods=3, freq="s"),\n },\n columns=[\n "group",\n "int",\n "float",\n "string",\n "category_string",\n "category_int",\n "datetime",\n "datetimetz",\n "timedelta",\n ],\n )\n\n\nclass TestNLargestNSmallest:\n # ----------------------------------------------------------------------\n # Top / bottom\n @pytest.mark.parametrize(\n "order",\n [\n ["a"],\n ["c"],\n ["a", "b"],\n ["a", "c"],\n ["b", "a"],\n ["b", "c"],\n ["a", "b", "c"],\n ["c", "a", "b"],\n ["c", "b", "a"],\n ["b", "c", "a"],\n ["b", "a", "c"],\n # dups!\n ["b", "c", "c"],\n ],\n )\n @pytest.mark.parametrize("n", range(1, 11))\n def test_nlargest_n(self, df_strings, nselect_method, n, order):\n # GH#10393\n df = df_strings\n if "b" in order:\n error_msg = (\n f"Column 'b' has dtype (object|str), "\n f"cannot use method '{nselect_method}' with this dtype"\n )\n with pytest.raises(TypeError, match=error_msg):\n getattr(df, nselect_method)(n, order)\n else:\n ascending = nselect_method == "nsmallest"\n result = getattr(df, nselect_method)(n, order)\n expected = df.sort_values(order, ascending=ascending).head(n)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "columns", [["group", "category_string"], ["group", "string"]]\n )\n def test_nlargest_error(self, df_main_dtypes, nselect_method, columns):\n df = df_main_dtypes\n col = columns[1]\n error_msg = (\n f"Column '{col}' has dtype {df[col].dtype}, "\n f"cannot use method '{nselect_method}' with this dtype"\n )\n # escape some characters that may be in the repr\n error_msg = (\n error_msg.replace("(", "\\(")\n .replace(")", "\\)")\n .replace("[", "\\[")\n .replace("]", "\\]")\n )\n with pytest.raises(TypeError, match=error_msg):\n getattr(df, nselect_method)(2, columns)\n\n def test_nlargest_all_dtypes(self, df_main_dtypes):\n df = df_main_dtypes\n df.nsmallest(2, list(set(df) - {"category_string", "string"}))\n df.nlargest(2, list(set(df) - {"category_string", "string"}))\n\n def test_nlargest_duplicates_on_starter_columns(self):\n # regression test for GH#22752\n\n df = pd.DataFrame({"a": [2, 2, 2, 1, 1, 1], "b": [1, 2, 3, 3, 2, 1]})\n\n result = df.nlargest(4, columns=["a", "b"])\n expected = pd.DataFrame(\n {"a": [2, 2, 2, 1], "b": [3, 2, 1, 3]}, index=[2, 1, 0, 3]\n )\n tm.assert_frame_equal(result, expected)\n\n result = df.nsmallest(4, columns=["a", "b"])\n expected = pd.DataFrame(\n {"a": [1, 1, 1, 2], "b": [1, 2, 3, 1]}, index=[5, 4, 3, 0]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_nlargest_n_identical_values(self):\n # GH#15297\n df = pd.DataFrame({"a": [1] * 5, "b": [1, 2, 3, 4, 5]})\n\n result = df.nlargest(3, "a")\n expected = pd.DataFrame({"a": [1] * 3, "b": [1, 2, 3]}, index=[0, 1, 2])\n tm.assert_frame_equal(result, expected)\n\n result = df.nsmallest(3, "a")\n expected = pd.DataFrame({"a": [1] * 3, "b": [1, 2, 3]})\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "order",\n [["a", "b", "c"], ["c", "b", "a"], ["a"], ["b"], ["a", "b"], ["c", "b"]],\n )\n @pytest.mark.parametrize("n", range(1, 6))\n def test_nlargest_n_duplicate_index(self, df_duplicates, n, order, request):\n # GH#13412\n\n df = df_duplicates\n result = df.nsmallest(n, order)\n expected = df.sort_values(order).head(n)\n tm.assert_frame_equal(result, expected)\n\n result = df.nlargest(n, order)\n expected = df.sort_values(order, ascending=False).head(n)\n if Version(np.__version__) >= Version("1.25") and (\n (order == ["a"] and n in (1, 2, 3, 4)) or (order == ["a", "b"]) and n == 5\n ):\n request.applymarker(\n pytest.mark.xfail(\n reason=(\n "pandas default unstable sorting of duplicates"\n "issue with numpy>=1.25 with AVX instructions"\n ),\n strict=False,\n )\n )\n tm.assert_frame_equal(result, expected)\n\n def test_nlargest_duplicate_keep_all_ties(self):\n # GH#16818\n df = pd.DataFrame(\n {"a": [5, 4, 4, 2, 3, 3, 3, 3], "b": [10, 9, 8, 7, 5, 50, 10, 20]}\n )\n result = df.nlargest(4, "a", keep="all")\n expected = pd.DataFrame(\n {\n "a": {0: 5, 1: 4, 2: 4, 4: 3, 5: 3, 6: 3, 7: 3},\n "b": {0: 10, 1: 9, 2: 8, 4: 5, 5: 50, 6: 10, 7: 20},\n }\n )\n tm.assert_frame_equal(result, expected)\n\n result = df.nsmallest(2, "a", keep="all")\n expected = pd.DataFrame(\n {\n "a": {3: 2, 4: 3, 5: 3, 6: 3, 7: 3},\n "b": {3: 7, 4: 5, 5: 50, 6: 10, 7: 20},\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_nlargest_multiindex_column_lookup(self):\n # Check whether tuples are correctly treated as multi-level lookups.\n # GH#23033\n df = pd.DataFrame(\n columns=pd.MultiIndex.from_product([["x"], ["a", "b"]]),\n data=[[0.33, 0.13], [0.86, 0.25], [0.25, 0.70], [0.85, 0.91]],\n )\n\n # nsmallest\n result = df.nsmallest(3, ("x", "a"))\n expected = df.iloc[[2, 0, 3]]\n tm.assert_frame_equal(result, expected)\n\n # nlargest\n result = df.nlargest(3, ("x", "b"))\n expected = df.iloc[[3, 2, 1]]\n tm.assert_frame_equal(result, expected)\n\n def test_nlargest_nan(self):\n # GH#43060\n df = pd.DataFrame([np.nan, np.nan, 0, 1, 2, 3])\n result = df.nlargest(5, 0)\n expected = df.sort_values(0, ascending=False).head(5)\n tm.assert_frame_equal(result, expected)\n\n def test_nsmallest_nan_after_n_element(self):\n # GH#46589\n df = pd.DataFrame(\n {\n "a": [1, 2, 3, 4, 5, None, 7],\n "b": [7, 6, 5, 4, 3, 2, 1],\n "c": [1, 1, 2, 2, 3, 3, 3],\n },\n index=range(7),\n )\n result = df.nsmallest(5, columns=["a", "b"])\n expected = pd.DataFrame(\n {\n "a": [1, 2, 3, 4, 5],\n "b": [7, 6, 5, 4, 3],\n "c": [1, 1, 2, 2, 3],\n },\n index=range(5),\n ).astype({"a": "float"})\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_nlargest.py
test_nlargest.py
Python
8,192
0.95
0.072
0.067873
vue-tools
91
2023-12-05T20:50:19.759392
GPL-3.0
true
7b0af12534db2f2f703d19298958e46e
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFramePctChange:\n @pytest.mark.parametrize(\n "periods, fill_method, limit, exp",\n [\n (1, "ffill", None, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, 0]),\n (1, "ffill", 1, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, np.nan]),\n (1, "bfill", None, [np.nan, 0, 0, 1, 1, 1.5, np.nan, np.nan]),\n (1, "bfill", 1, [np.nan, np.nan, 0, 1, 1, 1.5, np.nan, np.nan]),\n (-1, "ffill", None, [np.nan, np.nan, -0.5, -0.5, -0.6, 0, 0, np.nan]),\n (-1, "ffill", 1, [np.nan, np.nan, -0.5, -0.5, -0.6, 0, np.nan, np.nan]),\n (-1, "bfill", None, [0, 0, -0.5, -0.5, -0.6, np.nan, np.nan, np.nan]),\n (-1, "bfill", 1, [np.nan, 0, -0.5, -0.5, -0.6, np.nan, np.nan, np.nan]),\n ],\n )\n def test_pct_change_with_nas(\n self, periods, fill_method, limit, exp, frame_or_series\n ):\n vals = [np.nan, np.nan, 1, 2, 4, 10, np.nan, np.nan]\n obj = frame_or_series(vals)\n\n msg = (\n "The 'fill_method' keyword being not None and the 'limit' keyword in "\n f"{type(obj).__name__}.pct_change are deprecated"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res = obj.pct_change(periods=periods, fill_method=fill_method, limit=limit)\n tm.assert_equal(res, frame_or_series(exp))\n\n def test_pct_change_numeric(self):\n # GH#11150\n pnl = DataFrame(\n [np.arange(0, 40, 10), np.arange(0, 40, 10), np.arange(0, 40, 10)]\n ).astype(np.float64)\n pnl.iat[1, 0] = np.nan\n pnl.iat[1, 1] = np.nan\n pnl.iat[2, 3] = 60\n\n msg = (\n "The 'fill_method' keyword being not None and the 'limit' keyword in "\n "DataFrame.pct_change are deprecated"\n )\n\n for axis in range(2):\n expected = pnl.ffill(axis=axis) / pnl.ffill(axis=axis).shift(axis=axis) - 1\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = pnl.pct_change(axis=axis, fill_method="pad")\n tm.assert_frame_equal(result, expected)\n\n def test_pct_change(self, datetime_frame):\n msg = (\n "The 'fill_method' keyword being not None and the 'limit' keyword in "\n "DataFrame.pct_change are deprecated"\n )\n\n rs = datetime_frame.pct_change(fill_method=None)\n tm.assert_frame_equal(rs, datetime_frame / datetime_frame.shift(1) - 1)\n\n rs = datetime_frame.pct_change(2)\n filled = datetime_frame.ffill()\n tm.assert_frame_equal(rs, filled / filled.shift(2) - 1)\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n rs = datetime_frame.pct_change(fill_method="bfill", limit=1)\n filled = datetime_frame.bfill(limit=1)\n tm.assert_frame_equal(rs, filled / filled.shift(1) - 1)\n\n rs = datetime_frame.pct_change(freq="5D")\n filled = datetime_frame.ffill()\n tm.assert_frame_equal(\n rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled)\n )\n\n def test_pct_change_shift_over_nas(self):\n s = Series([1.0, 1.5, np.nan, 2.5, 3.0])\n\n df = DataFrame({"a": s, "b": s})\n\n msg = "The default fill_method='pad' in DataFrame.pct_change is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n chg = df.pct_change()\n\n expected = Series([np.nan, 0.5, 0.0, 2.5 / 1.5 - 1, 0.2])\n edf = DataFrame({"a": expected, "b": expected})\n tm.assert_frame_equal(chg, edf)\n\n @pytest.mark.parametrize(\n "freq, periods, fill_method, limit",\n [\n ("5B", 5, None, None),\n ("3B", 3, None, None),\n ("3B", 3, "bfill", None),\n ("7B", 7, "pad", 1),\n ("7B", 7, "bfill", 3),\n ("14B", 14, None, None),\n ],\n )\n def test_pct_change_periods_freq(\n self, datetime_frame, freq, periods, fill_method, limit\n ):\n msg = (\n "The 'fill_method' keyword being not None and the 'limit' keyword in "\n "DataFrame.pct_change are deprecated"\n )\n\n # GH#7292\n with tm.assert_produces_warning(FutureWarning, match=msg):\n rs_freq = datetime_frame.pct_change(\n freq=freq, fill_method=fill_method, limit=limit\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n rs_periods = datetime_frame.pct_change(\n periods, fill_method=fill_method, limit=limit\n )\n tm.assert_frame_equal(rs_freq, rs_periods)\n\n empty_ts = DataFrame(index=datetime_frame.index, columns=datetime_frame.columns)\n with tm.assert_produces_warning(FutureWarning, match=msg):\n rs_freq = empty_ts.pct_change(\n freq=freq, fill_method=fill_method, limit=limit\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n rs_periods = empty_ts.pct_change(\n periods, fill_method=fill_method, limit=limit\n )\n tm.assert_frame_equal(rs_freq, rs_periods)\n\n\n@pytest.mark.parametrize("fill_method", ["pad", "ffill", None])\ndef test_pct_change_with_duplicated_indices(fill_method):\n # GH30463\n data = DataFrame(\n {0: [np.nan, 1, 2, 3, 9, 18], 1: [0, 1, np.nan, 3, 9, 18]}, index=["a", "b"] * 3\n )\n\n warn = None if fill_method is None else FutureWarning\n msg = (\n "The 'fill_method' keyword being not None and the 'limit' keyword in "\n "DataFrame.pct_change are deprecated"\n )\n with tm.assert_produces_warning(warn, match=msg):\n result = data.pct_change(fill_method=fill_method)\n\n if fill_method is None:\n second_column = [np.nan, np.inf, np.nan, np.nan, 2.0, 1.0]\n else:\n second_column = [np.nan, np.inf, 0.0, 2.0, 2.0, 1.0]\n expected = DataFrame(\n {0: [np.nan, np.nan, 1.0, 0.5, 2.0, 1.0], 1: second_column},\n index=["a", "b"] * 3,\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_pct_change_none_beginning_no_warning():\n # GH#54481\n df = DataFrame(\n [\n [1, None],\n [2, 1],\n [3, 2],\n [4, 3],\n [5, 4],\n ]\n )\n result = df.pct_change()\n expected = DataFrame(\n {0: [np.nan, 1, 0.5, 1 / 3, 0.25], 1: [np.nan, np.nan, 1, 0.5, 1 / 3]}\n )\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_pct_change.py
test_pct_change.py
Python
6,530
0.95
0.061111
0.025974
node-utils
205
2024-04-16T06:40:01.284960
Apache-2.0
true
9396434c43e861ba7ae1d5783add4e34
import pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestPipe:\n def test_pipe(self, frame_or_series):\n obj = DataFrame({"A": [1, 2, 3]})\n expected = DataFrame({"A": [1, 4, 9]})\n if frame_or_series is Series:\n obj = obj["A"]\n expected = expected["A"]\n\n f = lambda x, y: x**y\n result = obj.pipe(f, 2)\n tm.assert_equal(result, expected)\n\n def test_pipe_tuple(self, frame_or_series):\n obj = DataFrame({"A": [1, 2, 3]})\n obj = tm.get_obj(obj, frame_or_series)\n\n f = lambda x, y: y\n result = obj.pipe((f, "y"), 0)\n tm.assert_equal(result, obj)\n\n def test_pipe_tuple_error(self, frame_or_series):\n obj = DataFrame({"A": [1, 2, 3]})\n obj = tm.get_obj(obj, frame_or_series)\n\n f = lambda x, y: y\n\n msg = "y is both the pipe target and a keyword argument"\n\n with pytest.raises(ValueError, match=msg):\n obj.pipe((f, "y"), x=1, y=0)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_pipe.py
test_pipe.py
Python
1,023
0.85
0.128205
0
python-kit
659
2024-03-02T00:56:32.769928
BSD-3-Clause
true
d4ea548a00148c858730505e94bc44bc
import numpy as np\n\nfrom pandas import (\n DataFrame,\n MultiIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFramePop:\n def test_pop(self, float_frame, warn_copy_on_write):\n float_frame.columns.name = "baz"\n\n float_frame.pop("A")\n assert "A" not in float_frame\n\n float_frame["foo"] = "bar"\n float_frame.pop("foo")\n assert "foo" not in float_frame\n assert float_frame.columns.name == "baz"\n\n # gh-10912: inplace ops cause caching issue\n a = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"], index=["X", "Y"])\n b = a.pop("B")\n with tm.assert_cow_warning(warn_copy_on_write):\n b += 1\n\n # original frame\n expected = DataFrame([[1, 3], [4, 6]], columns=["A", "C"], index=["X", "Y"])\n tm.assert_frame_equal(a, expected)\n\n # result\n expected = Series([2, 5], index=["X", "Y"], name="B") + 1\n tm.assert_series_equal(b, expected)\n\n def test_pop_non_unique_cols(self):\n df = DataFrame({0: [0, 1], 1: [0, 1], 2: [4, 5]})\n df.columns = ["a", "b", "a"]\n\n res = df.pop("a")\n assert type(res) == DataFrame\n assert len(res) == 2\n assert len(df.columns) == 1\n assert "b" in df.columns\n assert "a" not in df.columns\n assert len(df.index) == 2\n\n def test_mixed_depth_pop(self):\n arrays = [\n ["a", "top", "top", "routine1", "routine1", "routine2"],\n ["", "OD", "OD", "result1", "result2", "result1"],\n ["", "wx", "wy", "", "", ""],\n ]\n\n tuples = sorted(zip(*arrays))\n index = MultiIndex.from_tuples(tuples)\n df = DataFrame(np.random.default_rng(2).standard_normal((4, 6)), columns=index)\n\n df1 = df.copy()\n df2 = df.copy()\n result = df1.pop("a")\n expected = df2.pop(("a", "", ""))\n tm.assert_series_equal(expected, result, check_names=False)\n tm.assert_frame_equal(df1, df2)\n assert result.name == "a"\n\n expected = df1["top"]\n df1 = df1.drop(["top"], axis=1)\n result = df2.pop("top")\n tm.assert_frame_equal(expected, result)\n tm.assert_frame_equal(df1, df2)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_pop.py
test_pop.py
Python
2,223
0.95
0.055556
0.051724
react-lib
633
2025-04-24T20:34:43.845166
BSD-3-Clause
true
1dec88e3c5c9e1c379ac2eaec8331d46
import numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n Timestamp,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture(\n params=[["linear", "single"], ["nearest", "table"]], ids=lambda x: "-".join(x)\n)\ndef interp_method(request):\n """(interpolation, method) arguments for quantile"""\n return request.param\n\n\nclass TestDataFrameQuantile:\n @pytest.mark.parametrize(\n "df,expected",\n [\n [\n DataFrame(\n {\n 0: Series(pd.arrays.SparseArray([1, 2])),\n 1: Series(pd.arrays.SparseArray([3, 4])),\n }\n ),\n Series([1.5, 3.5], name=0.5),\n ],\n [\n DataFrame(Series([0.0, None, 1.0, 2.0], dtype="Sparse[float]")),\n Series([1.0], name=0.5),\n ],\n ],\n )\n def test_quantile_sparse(self, df, expected):\n # GH#17198\n # GH#24600\n result = df.quantile()\n expected = expected.astype("Sparse[float]")\n tm.assert_series_equal(result, expected)\n\n def test_quantile(\n self, datetime_frame, interp_method, using_array_manager, request\n ):\n interpolation, method = interp_method\n df = datetime_frame\n result = df.quantile(\n 0.1, axis=0, numeric_only=True, interpolation=interpolation, method=method\n )\n expected = Series(\n [np.percentile(df[col], 10) for col in df.columns],\n index=df.columns,\n name=0.1,\n )\n if interpolation == "linear":\n # np.percentile values only comparable to linear interpolation\n tm.assert_series_equal(result, expected)\n else:\n tm.assert_index_equal(result.index, expected.index)\n request.applymarker(\n pytest.mark.xfail(\n using_array_manager, reason="Name set incorrectly for arraymanager"\n )\n )\n assert result.name == expected.name\n\n result = df.quantile(\n 0.9, axis=1, numeric_only=True, interpolation=interpolation, method=method\n )\n expected = Series(\n [np.percentile(df.loc[date], 90) for date in df.index],\n index=df.index,\n name=0.9,\n )\n if interpolation == "linear":\n # np.percentile values only comparable to linear interpolation\n tm.assert_series_equal(result, expected)\n else:\n tm.assert_index_equal(result.index, expected.index)\n request.applymarker(\n pytest.mark.xfail(\n using_array_manager, reason="Name set incorrectly for arraymanager"\n )\n )\n assert result.name == expected.name\n\n def test_empty(self, interp_method):\n interpolation, method = interp_method\n q = DataFrame({"x": [], "y": []}).quantile(\n 0.1, axis=0, numeric_only=True, interpolation=interpolation, method=method\n )\n assert np.isnan(q["x"]) and np.isnan(q["y"])\n\n def test_non_numeric_exclusion(self, interp_method, request, using_array_manager):\n interpolation, method = interp_method\n df = DataFrame({"col1": ["A", "A", "B", "B"], "col2": [1, 2, 3, 4]})\n rs = df.quantile(\n 0.5, numeric_only=True, interpolation=interpolation, method=method\n )\n xp = df.median(numeric_only=True).rename(0.5)\n if interpolation == "nearest":\n xp = (xp + 0.5).astype(np.int64)\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n tm.assert_series_equal(rs, xp)\n\n def test_axis(self, interp_method, request, using_array_manager):\n # axis\n interpolation, method = interp_method\n df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3])\n result = df.quantile(0.5, axis=1, interpolation=interpolation, method=method)\n expected = Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5)\n if interpolation == "nearest":\n expected = expected.astype(np.int64)\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n tm.assert_series_equal(result, expected)\n\n result = df.quantile(\n [0.5, 0.75], axis=1, interpolation=interpolation, method=method\n )\n expected = DataFrame(\n {1: [1.5, 1.75], 2: [2.5, 2.75], 3: [3.5, 3.75]}, index=[0.5, 0.75]\n )\n if interpolation == "nearest":\n expected.iloc[0, :] -= 0.5\n expected.iloc[1, :] += 0.25\n expected = expected.astype(np.int64)\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n def test_axis_numeric_only_true(self, interp_method, request, using_array_manager):\n # We may want to break API in the future to change this\n # so that we exclude non-numeric along the same axis\n # See GH #7312\n interpolation, method = interp_method\n df = DataFrame([[1, 2, 3], ["a", "b", 4]])\n result = df.quantile(\n 0.5, axis=1, numeric_only=True, interpolation=interpolation, method=method\n )\n expected = Series([3.0, 4.0], index=[0, 1], name=0.5)\n if interpolation == "nearest":\n expected = expected.astype(np.int64)\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n tm.assert_series_equal(result, expected)\n\n def test_quantile_date_range(self, interp_method, request, using_array_manager):\n # GH 2460\n interpolation, method = interp_method\n dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")\n ser = Series(dti)\n df = DataFrame(ser)\n\n result = df.quantile(\n numeric_only=False, interpolation=interpolation, method=method\n )\n expected = Series(\n ["2016-01-02 00:00:00"], name=0.5, dtype="datetime64[ns, US/Pacific]"\n )\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n\n tm.assert_series_equal(result, expected)\n\n def test_quantile_axis_mixed(self, interp_method, request, using_array_manager):\n # mixed on axis=1\n interpolation, method = interp_method\n df = DataFrame(\n {\n "A": [1, 2, 3],\n "B": [2.0, 3.0, 4.0],\n "C": pd.date_range("20130101", periods=3),\n "D": ["foo", "bar", "baz"],\n }\n )\n result = df.quantile(\n 0.5, axis=1, numeric_only=True, interpolation=interpolation, method=method\n )\n expected = Series([1.5, 2.5, 3.5], name=0.5)\n if interpolation == "nearest":\n expected -= 0.5\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n tm.assert_series_equal(result, expected)\n\n # must raise\n msg = "'<' not supported between instances of 'Timestamp' and 'float'"\n with pytest.raises(TypeError, match=msg):\n df.quantile(0.5, axis=1, numeric_only=False)\n\n def test_quantile_axis_parameter(self, interp_method, request, using_array_manager):\n # GH 9543/9544\n interpolation, method = interp_method\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3])\n\n result = df.quantile(0.5, axis=0, interpolation=interpolation, method=method)\n\n expected = Series([2.0, 3.0], index=["A", "B"], name=0.5)\n if interpolation == "nearest":\n expected = expected.astype(np.int64)\n tm.assert_series_equal(result, expected)\n\n expected = df.quantile(\n 0.5, axis="index", interpolation=interpolation, method=method\n )\n if interpolation == "nearest":\n expected = expected.astype(np.int64)\n tm.assert_series_equal(result, expected)\n\n result = df.quantile(0.5, axis=1, interpolation=interpolation, method=method)\n\n expected = Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5)\n if interpolation == "nearest":\n expected = expected.astype(np.int64)\n tm.assert_series_equal(result, expected)\n\n result = df.quantile(\n 0.5, axis="columns", interpolation=interpolation, method=method\n )\n tm.assert_series_equal(result, expected)\n\n msg = "No axis named -1 for object type DataFrame"\n with pytest.raises(ValueError, match=msg):\n df.quantile(0.1, axis=-1, interpolation=interpolation, method=method)\n msg = "No axis named column for object type DataFrame"\n with pytest.raises(ValueError, match=msg):\n df.quantile(0.1, axis="column")\n\n def test_quantile_interpolation(self):\n # see gh-10174\n\n # interpolation method other than default linear\n df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3])\n result = df.quantile(0.5, axis=1, interpolation="nearest")\n expected = Series([1, 2, 3], index=[1, 2, 3], name=0.5)\n tm.assert_series_equal(result, expected)\n\n # cross-check interpolation=nearest results in original dtype\n exp = np.percentile(\n np.array([[1, 2, 3], [2, 3, 4]]),\n 0.5,\n axis=0,\n method="nearest",\n )\n expected = Series(exp, index=[1, 2, 3], name=0.5, dtype="int64")\n tm.assert_series_equal(result, expected)\n\n # float\n df = DataFrame({"A": [1.0, 2.0, 3.0], "B": [2.0, 3.0, 4.0]}, index=[1, 2, 3])\n result = df.quantile(0.5, axis=1, interpolation="nearest")\n expected = Series([1.0, 2.0, 3.0], index=[1, 2, 3], name=0.5)\n tm.assert_series_equal(result, expected)\n exp = np.percentile(\n np.array([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]]),\n 0.5,\n axis=0,\n method="nearest",\n )\n expected = Series(exp, index=[1, 2, 3], name=0.5, dtype="float64")\n tm.assert_series_equal(result, expected)\n\n # axis\n result = df.quantile([0.5, 0.75], axis=1, interpolation="lower")\n expected = DataFrame(\n {1: [1.0, 1.0], 2: [2.0, 2.0], 3: [3.0, 3.0]}, index=[0.5, 0.75]\n )\n tm.assert_frame_equal(result, expected)\n\n # test degenerate case\n df = DataFrame({"x": [], "y": []})\n q = df.quantile(0.1, axis=0, interpolation="higher")\n assert np.isnan(q["x"]) and np.isnan(q["y"])\n\n # multi\n df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"])\n result = df.quantile([0.25, 0.5], interpolation="midpoint")\n\n # https://github.com/numpy/numpy/issues/7163\n expected = DataFrame(\n [[1.5, 1.5, 1.5], [2.0, 2.0, 2.0]],\n index=[0.25, 0.5],\n columns=["a", "b", "c"],\n )\n tm.assert_frame_equal(result, expected)\n\n def test_quantile_interpolation_datetime(self, datetime_frame):\n # see gh-10174\n\n # interpolation = linear (default case)\n df = datetime_frame\n q = df.quantile(0.1, axis=0, numeric_only=True, interpolation="linear")\n assert q["A"] == np.percentile(df["A"], 10)\n\n def test_quantile_interpolation_int(self, int_frame):\n # see gh-10174\n\n df = int_frame\n # interpolation = linear (default case)\n q = df.quantile(0.1)\n assert q["A"] == np.percentile(df["A"], 10)\n\n # test with and without interpolation keyword\n q1 = df.quantile(0.1, axis=0, interpolation="linear")\n assert q1["A"] == np.percentile(df["A"], 10)\n tm.assert_series_equal(q, q1)\n\n def test_quantile_multi(self, interp_method, request, using_array_manager):\n interpolation, method = interp_method\n df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"])\n result = df.quantile([0.25, 0.5], interpolation=interpolation, method=method)\n expected = DataFrame(\n [[1.5, 1.5, 1.5], [2.0, 2.0, 2.0]],\n index=[0.25, 0.5],\n columns=["a", "b", "c"],\n )\n if interpolation == "nearest":\n expected = expected.astype(np.int64)\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n tm.assert_frame_equal(result, expected)\n\n def test_quantile_multi_axis_1(self, interp_method, request, using_array_manager):\n interpolation, method = interp_method\n df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"])\n result = df.quantile(\n [0.25, 0.5], axis=1, interpolation=interpolation, method=method\n )\n expected = DataFrame(\n [[1.0, 2.0, 3.0]] * 2, index=[0.25, 0.5], columns=[0, 1, 2]\n )\n if interpolation == "nearest":\n expected = expected.astype(np.int64)\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n tm.assert_frame_equal(result, expected)\n\n def test_quantile_multi_empty(self, interp_method):\n interpolation, method = interp_method\n result = DataFrame({"x": [], "y": []}).quantile(\n [0.1, 0.9], axis=0, interpolation=interpolation, method=method\n )\n expected = DataFrame(\n {"x": [np.nan, np.nan], "y": [np.nan, np.nan]}, index=[0.1, 0.9]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_quantile_datetime(self, unit):\n dti = pd.to_datetime(["2010", "2011"]).as_unit(unit)\n df = DataFrame({"a": dti, "b": [0, 5]})\n\n # exclude datetime\n result = df.quantile(0.5, numeric_only=True)\n expected = Series([2.5], index=["b"], name=0.5)\n tm.assert_series_equal(result, expected)\n\n # datetime\n result = df.quantile(0.5, numeric_only=False)\n expected = Series(\n [Timestamp("2010-07-02 12:00:00"), 2.5], index=["a", "b"], name=0.5\n )\n tm.assert_series_equal(result, expected)\n\n # datetime w/ multi\n result = df.quantile([0.5], numeric_only=False)\n expected = DataFrame(\n {"a": Timestamp("2010-07-02 12:00:00").as_unit(unit), "b": 2.5},\n index=[0.5],\n )\n tm.assert_frame_equal(result, expected)\n\n # axis = 1\n df["c"] = pd.to_datetime(["2011", "2012"]).as_unit(unit)\n result = df[["a", "c"]].quantile(0.5, axis=1, numeric_only=False)\n expected = Series(\n [Timestamp("2010-07-02 12:00:00"), Timestamp("2011-07-02 12:00:00")],\n index=[0, 1],\n name=0.5,\n dtype=f"M8[{unit}]",\n )\n tm.assert_series_equal(result, expected)\n\n result = df[["a", "c"]].quantile([0.5], axis=1, numeric_only=False)\n expected = DataFrame(\n [[Timestamp("2010-07-02 12:00:00"), Timestamp("2011-07-02 12:00:00")]],\n index=[0.5],\n columns=[0, 1],\n dtype=f"M8[{unit}]",\n )\n tm.assert_frame_equal(result, expected)\n\n # empty when numeric_only=True\n result = df[["a", "c"]].quantile(0.5, numeric_only=True)\n expected = Series([], index=[], dtype=np.float64, name=0.5)\n tm.assert_series_equal(result, expected)\n\n result = df[["a", "c"]].quantile([0.5], numeric_only=True)\n expected = DataFrame(index=[0.5], columns=[])\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "dtype",\n [\n "datetime64[ns]",\n "datetime64[ns, US/Pacific]",\n "timedelta64[ns]",\n "Period[D]",\n ],\n )\n def test_quantile_dt64_empty(self, dtype, interp_method):\n # GH#41544\n interpolation, method = interp_method\n df = DataFrame(columns=["a", "b"], dtype=dtype)\n\n res = df.quantile(\n 0.5, axis=1, numeric_only=False, interpolation=interpolation, method=method\n )\n expected = Series([], index=[], name=0.5, dtype=dtype)\n tm.assert_series_equal(res, expected)\n\n # no columns in result, so no dtype preservation\n res = df.quantile(\n [0.5],\n axis=1,\n numeric_only=False,\n interpolation=interpolation,\n method=method,\n )\n expected = DataFrame(index=[0.5], columns=[])\n tm.assert_frame_equal(res, expected)\n\n @pytest.mark.parametrize("invalid", [-1, 2, [0.5, -1], [0.5, 2]])\n def test_quantile_invalid(self, invalid, datetime_frame, interp_method):\n msg = "percentiles should all be in the interval \\[0, 1\\]"\n interpolation, method = interp_method\n with pytest.raises(ValueError, match=msg):\n datetime_frame.quantile(invalid, interpolation=interpolation, method=method)\n\n def test_quantile_box(self, interp_method, request, using_array_manager):\n interpolation, method = interp_method\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n df = DataFrame(\n {\n "A": [\n Timestamp("2011-01-01"),\n Timestamp("2011-01-02"),\n Timestamp("2011-01-03"),\n ],\n "B": [\n Timestamp("2011-01-01", tz="US/Eastern"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n Timestamp("2011-01-03", tz="US/Eastern"),\n ],\n "C": [\n pd.Timedelta("1 days"),\n pd.Timedelta("2 days"),\n pd.Timedelta("3 days"),\n ],\n }\n )\n\n res = df.quantile(\n 0.5, numeric_only=False, interpolation=interpolation, method=method\n )\n\n exp = Series(\n [\n Timestamp("2011-01-02"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n pd.Timedelta("2 days"),\n ],\n name=0.5,\n index=["A", "B", "C"],\n )\n tm.assert_series_equal(res, exp)\n\n res = df.quantile(\n [0.5], numeric_only=False, interpolation=interpolation, method=method\n )\n exp = DataFrame(\n [\n [\n Timestamp("2011-01-02"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n pd.Timedelta("2 days"),\n ]\n ],\n index=[0.5],\n columns=["A", "B", "C"],\n )\n tm.assert_frame_equal(res, exp)\n\n def test_quantile_box_nat(self):\n # DatetimeLikeBlock may be consolidated and contain NaT in different loc\n df = DataFrame(\n {\n "A": [\n Timestamp("2011-01-01"),\n pd.NaT,\n Timestamp("2011-01-02"),\n Timestamp("2011-01-03"),\n ],\n "a": [\n Timestamp("2011-01-01"),\n Timestamp("2011-01-02"),\n pd.NaT,\n Timestamp("2011-01-03"),\n ],\n "B": [\n Timestamp("2011-01-01", tz="US/Eastern"),\n pd.NaT,\n Timestamp("2011-01-02", tz="US/Eastern"),\n Timestamp("2011-01-03", tz="US/Eastern"),\n ],\n "b": [\n Timestamp("2011-01-01", tz="US/Eastern"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n pd.NaT,\n Timestamp("2011-01-03", tz="US/Eastern"),\n ],\n "C": [\n pd.Timedelta("1 days"),\n pd.Timedelta("2 days"),\n pd.Timedelta("3 days"),\n pd.NaT,\n ],\n "c": [\n pd.NaT,\n pd.Timedelta("1 days"),\n pd.Timedelta("2 days"),\n pd.Timedelta("3 days"),\n ],\n },\n columns=list("AaBbCc"),\n )\n\n res = df.quantile(0.5, numeric_only=False)\n exp = Series(\n [\n Timestamp("2011-01-02"),\n Timestamp("2011-01-02"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n pd.Timedelta("2 days"),\n pd.Timedelta("2 days"),\n ],\n name=0.5,\n index=list("AaBbCc"),\n )\n tm.assert_series_equal(res, exp)\n\n res = df.quantile([0.5], numeric_only=False)\n exp = DataFrame(\n [\n [\n Timestamp("2011-01-02"),\n Timestamp("2011-01-02"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n pd.Timedelta("2 days"),\n pd.Timedelta("2 days"),\n ]\n ],\n index=[0.5],\n columns=list("AaBbCc"),\n )\n tm.assert_frame_equal(res, exp)\n\n def test_quantile_nan(self, interp_method, request, using_array_manager):\n interpolation, method = interp_method\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n # GH 14357 - float block where some cols have missing values\n df = DataFrame({"a": np.arange(1, 6.0), "b": np.arange(1, 6.0)})\n df.iloc[-1, 1] = np.nan\n\n res = df.quantile(0.5, interpolation=interpolation, method=method)\n exp = Series(\n [3.0, 2.5 if interpolation == "linear" else 3.0], index=["a", "b"], name=0.5\n )\n tm.assert_series_equal(res, exp)\n\n res = df.quantile([0.5, 0.75], interpolation=interpolation, method=method)\n exp = DataFrame(\n {\n "a": [3.0, 4.0],\n "b": [2.5, 3.25] if interpolation == "linear" else [3.0, 4.0],\n },\n index=[0.5, 0.75],\n )\n tm.assert_frame_equal(res, exp)\n\n res = df.quantile(0.5, axis=1, interpolation=interpolation, method=method)\n exp = Series(np.arange(1.0, 6.0), name=0.5)\n tm.assert_series_equal(res, exp)\n\n res = df.quantile(\n [0.5, 0.75], axis=1, interpolation=interpolation, method=method\n )\n exp = DataFrame([np.arange(1.0, 6.0)] * 2, index=[0.5, 0.75])\n if interpolation == "nearest":\n exp.iloc[1, -1] = np.nan\n tm.assert_frame_equal(res, exp)\n\n # full-nan column\n df["b"] = np.nan\n\n res = df.quantile(0.5, interpolation=interpolation, method=method)\n exp = Series([3.0, np.nan], index=["a", "b"], name=0.5)\n tm.assert_series_equal(res, exp)\n\n res = df.quantile([0.5, 0.75], interpolation=interpolation, method=method)\n exp = DataFrame({"a": [3.0, 4.0], "b": [np.nan, np.nan]}, index=[0.5, 0.75])\n tm.assert_frame_equal(res, exp)\n\n def test_quantile_nat(self, interp_method, request, using_array_manager, unit):\n interpolation, method = interp_method\n if method == "table" and using_array_manager:\n request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set."))\n # full NaT column\n df = DataFrame({"a": [pd.NaT, pd.NaT, pd.NaT]}, dtype=f"M8[{unit}]")\n\n res = df.quantile(\n 0.5, numeric_only=False, interpolation=interpolation, method=method\n )\n exp = Series([pd.NaT], index=["a"], name=0.5, dtype=f"M8[{unit}]")\n tm.assert_series_equal(res, exp)\n\n res = df.quantile(\n [0.5], numeric_only=False, interpolation=interpolation, method=method\n )\n exp = DataFrame({"a": [pd.NaT]}, index=[0.5], dtype=f"M8[{unit}]")\n tm.assert_frame_equal(res, exp)\n\n # mixed non-null / full null column\n df = DataFrame(\n {\n "a": [\n Timestamp("2012-01-01"),\n Timestamp("2012-01-02"),\n Timestamp("2012-01-03"),\n ],\n "b": [pd.NaT, pd.NaT, pd.NaT],\n },\n dtype=f"M8[{unit}]",\n )\n\n res = df.quantile(\n 0.5, numeric_only=False, interpolation=interpolation, method=method\n )\n exp = Series(\n [Timestamp("2012-01-02"), pd.NaT],\n index=["a", "b"],\n name=0.5,\n dtype=f"M8[{unit}]",\n )\n tm.assert_series_equal(res, exp)\n\n res = df.quantile(\n [0.5], numeric_only=False, interpolation=interpolation, method=method\n )\n exp = DataFrame(\n [[Timestamp("2012-01-02"), pd.NaT]],\n index=[0.5],\n columns=["a", "b"],\n dtype=f"M8[{unit}]",\n )\n tm.assert_frame_equal(res, exp)\n\n def test_quantile_empty_no_rows_floats(self, interp_method):\n interpolation, method = interp_method\n\n df = DataFrame(columns=["a", "b"], dtype="float64")\n\n res = df.quantile(0.5, interpolation=interpolation, method=method)\n exp = Series([np.nan, np.nan], index=["a", "b"], name=0.5)\n tm.assert_series_equal(res, exp)\n\n res = df.quantile([0.5], interpolation=interpolation, method=method)\n exp = DataFrame([[np.nan, np.nan]], columns=["a", "b"], index=[0.5])\n tm.assert_frame_equal(res, exp)\n\n res = df.quantile(0.5, axis=1, interpolation=interpolation, method=method)\n exp = Series([], index=[], dtype="float64", name=0.5)\n tm.assert_series_equal(res, exp)\n\n res = df.quantile([0.5], axis=1, interpolation=interpolation, method=method)\n exp = DataFrame(columns=[], index=[0.5])\n tm.assert_frame_equal(res, exp)\n\n def test_quantile_empty_no_rows_ints(self, interp_method):\n interpolation, method = interp_method\n df = DataFrame(columns=["a", "b"], dtype="int64")\n\n res = df.quantile(0.5, interpolation=interpolation, method=method)\n exp = Series([np.nan, np.nan], index=["a", "b"], name=0.5)\n tm.assert_series_equal(res, exp)\n\n def test_quantile_empty_no_rows_dt64(self, interp_method):\n interpolation, method = interp_method\n # datetimes\n df = DataFrame(columns=["a", "b"], dtype="datetime64[ns]")\n\n res = df.quantile(\n 0.5, numeric_only=False, interpolation=interpolation, method=method\n )\n exp = Series(\n [pd.NaT, pd.NaT], index=["a", "b"], dtype="datetime64[ns]", name=0.5\n )\n tm.assert_series_equal(res, exp)\n\n # Mixed dt64/dt64tz\n df["a"] = df["a"].dt.tz_localize("US/Central")\n res = df.quantile(\n 0.5, numeric_only=False, interpolation=interpolation, method=method\n )\n exp = exp.astype(object)\n if interpolation == "nearest":\n # GH#18463 TODO: would we prefer NaTs here?\n msg = "The 'downcast' keyword in fillna is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n exp = exp.fillna(np.nan, downcast=False)\n tm.assert_series_equal(res, exp)\n\n # both dt64tz\n df["b"] = df["b"].dt.tz_localize("US/Central")\n res = df.quantile(\n 0.5, numeric_only=False, interpolation=interpolation, method=method\n )\n exp = exp.astype(df["b"].dtype)\n tm.assert_series_equal(res, exp)\n\n def test_quantile_empty_no_columns(self, interp_method):\n # GH#23925 _get_numeric_data may drop all columns\n interpolation, method = interp_method\n df = DataFrame(pd.date_range("1/1/18", periods=5))\n df.columns.name = "captain tightpants"\n result = df.quantile(\n 0.5, numeric_only=True, interpolation=interpolation, method=method\n )\n expected = Series([], index=[], name=0.5, dtype=np.float64)\n expected.index.name = "captain tightpants"\n tm.assert_series_equal(result, expected)\n\n result = df.quantile(\n [0.5], numeric_only=True, interpolation=interpolation, method=method\n )\n expected = DataFrame([], index=[0.5], columns=[])\n expected.columns.name = "captain tightpants"\n tm.assert_frame_equal(result, expected)\n\n def test_quantile_item_cache(\n self, using_array_manager, interp_method, using_copy_on_write\n ):\n # previous behavior incorrect retained an invalid _item_cache entry\n interpolation, method = interp_method\n df = DataFrame(\n np.random.default_rng(2).standard_normal((4, 3)), columns=["A", "B", "C"]\n )\n df["D"] = df["A"] * 2\n ser = df["A"]\n if not using_array_manager:\n assert len(df._mgr.blocks) == 2\n\n df.quantile(numeric_only=False, interpolation=interpolation, method=method)\n\n if using_copy_on_write:\n ser.iloc[0] = 99\n assert df.iloc[0, 0] == df["A"][0]\n assert df.iloc[0, 0] != 99\n else:\n ser.values[0] = 99\n assert df.iloc[0, 0] == df["A"][0]\n assert df.iloc[0, 0] == 99\n\n def test_invalid_method(self):\n with pytest.raises(ValueError, match="Invalid method: foo"):\n DataFrame(range(1)).quantile(0.5, method="foo")\n\n def test_table_invalid_interpolation(self):\n with pytest.raises(ValueError, match="Invalid interpolation: foo"):\n DataFrame(range(1)).quantile(0.5, method="table", interpolation="foo")\n\n\nclass TestQuantileExtensionDtype:\n # TODO: tests for axis=1?\n # TODO: empty case?\n\n @pytest.fixture(\n params=[\n pytest.param(\n pd.IntervalIndex.from_breaks(range(10)),\n marks=pytest.mark.xfail(reason="raises when trying to add Intervals"),\n ),\n pd.period_range("2016-01-01", periods=9, freq="D"),\n pd.date_range("2016-01-01", periods=9, tz="US/Pacific"),\n pd.timedelta_range("1 Day", periods=9),\n pd.array(np.arange(9), dtype="Int64"),\n pd.array(np.arange(9), dtype="Float64"),\n ],\n ids=lambda x: str(x.dtype),\n )\n def index(self, request):\n # NB: not actually an Index object\n idx = request.param\n idx.name = "A"\n return idx\n\n @pytest.fixture\n def obj(self, index, frame_or_series):\n # bc index is not always an Index (yet), we need to re-patch .name\n obj = frame_or_series(index).copy()\n\n if frame_or_series is Series:\n obj.name = "A"\n else:\n obj.columns = ["A"]\n return obj\n\n def compute_quantile(self, obj, qs):\n if isinstance(obj, Series):\n result = obj.quantile(qs)\n else:\n result = obj.quantile(qs, numeric_only=False)\n return result\n\n def test_quantile_ea(self, request, obj, index):\n # result should be invariant to shuffling\n indexer = np.arange(len(index), dtype=np.intp)\n np.random.default_rng(2).shuffle(indexer)\n obj = obj.iloc[indexer]\n\n qs = [0.5, 0, 1]\n result = self.compute_quantile(obj, qs)\n\n exp_dtype = index.dtype\n if index.dtype == "Int64":\n # match non-nullable casting behavior\n exp_dtype = "Float64"\n\n # expected here assumes len(index) == 9\n expected = Series(\n [index[4], index[0], index[-1]], dtype=exp_dtype, index=qs, name="A"\n )\n expected = type(obj)(expected)\n\n tm.assert_equal(result, expected)\n\n def test_quantile_ea_with_na(self, obj, index):\n obj.iloc[0] = index._na_value\n obj.iloc[-1] = index._na_value\n\n # result should be invariant to shuffling\n indexer = np.arange(len(index), dtype=np.intp)\n np.random.default_rng(2).shuffle(indexer)\n obj = obj.iloc[indexer]\n\n qs = [0.5, 0, 1]\n result = self.compute_quantile(obj, qs)\n\n # expected here assumes len(index) == 9\n expected = Series(\n [index[4], index[1], index[-2]], dtype=index.dtype, index=qs, name="A"\n )\n expected = type(obj)(expected)\n tm.assert_equal(result, expected)\n\n def test_quantile_ea_all_na(self, request, obj, index):\n obj.iloc[:] = index._na_value\n # Check dtypes were preserved; this was once a problem see GH#39763\n assert np.all(obj.dtypes == index.dtype)\n\n # result should be invariant to shuffling\n indexer = np.arange(len(index), dtype=np.intp)\n np.random.default_rng(2).shuffle(indexer)\n obj = obj.iloc[indexer]\n\n qs = [0.5, 0, 1]\n result = self.compute_quantile(obj, qs)\n\n expected = index.take([-1, -1, -1], allow_fill=True, fill_value=index._na_value)\n expected = Series(expected, index=qs, name="A")\n expected = type(obj)(expected)\n tm.assert_equal(result, expected)\n\n def test_quantile_ea_scalar(self, request, obj, index):\n # scalar qs\n\n # result should be invariant to shuffling\n indexer = np.arange(len(index), dtype=np.intp)\n np.random.default_rng(2).shuffle(indexer)\n obj = obj.iloc[indexer]\n\n qs = 0.5\n result = self.compute_quantile(obj, qs)\n\n exp_dtype = index.dtype\n if index.dtype == "Int64":\n exp_dtype = "Float64"\n\n expected = Series({"A": index[4]}, dtype=exp_dtype, name=0.5)\n if isinstance(obj, Series):\n expected = expected["A"]\n assert result == expected\n else:\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)", strict=False)\n @pytest.mark.parametrize(\n "dtype, expected_data, expected_index, axis",\n [\n ["float64", [], [], 1],\n ["int64", [], [], 1],\n ["float64", [np.nan, np.nan], ["a", "b"], 0],\n ["int64", [np.nan, np.nan], ["a", "b"], 0],\n ],\n )\n def test_empty_numeric(self, dtype, expected_data, expected_index, axis):\n # GH 14564\n df = DataFrame(columns=["a", "b"], dtype=dtype)\n result = df.quantile(0.5, axis=axis)\n expected = Series(\n expected_data, name=0.5, index=Index(expected_index), dtype="float64"\n )\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)", strict=False)\n @pytest.mark.parametrize(\n "dtype, expected_data, expected_index, axis, expected_dtype",\n [\n ["datetime64[ns]", [], [], 1, "datetime64[ns]"],\n ["datetime64[ns]", [pd.NaT, pd.NaT], ["a", "b"], 0, "datetime64[ns]"],\n ],\n )\n def test_empty_datelike(\n self, dtype, expected_data, expected_index, axis, expected_dtype\n ):\n # GH 14564\n df = DataFrame(columns=["a", "b"], dtype=dtype)\n result = df.quantile(0.5, axis=axis, numeric_only=False)\n expected = Series(\n expected_data, name=0.5, index=Index(expected_index), dtype=expected_dtype\n )\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)", strict=False)\n @pytest.mark.parametrize(\n "expected_data, expected_index, axis",\n [\n [[np.nan, np.nan], range(2), 1],\n [[], [], 0],\n ],\n )\n def test_datelike_numeric_only(self, expected_data, expected_index, axis):\n # GH 14564\n df = DataFrame(\n {\n "a": pd.to_datetime(["2010", "2011"]),\n "b": [0, 5],\n "c": pd.to_datetime(["2011", "2012"]),\n }\n )\n result = df[["a", "c"]].quantile(0.5, axis=axis, numeric_only=True)\n expected = Series(\n expected_data, name=0.5, index=Index(expected_index), dtype=np.float64\n )\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_quantile.py
test_quantile.py
Python
36,591
0.95
0.085977
0.068925
vue-tools
24
2024-08-09T07:26:31.812173
Apache-2.0
true
98f646ab39de98059303a52947a7cd1f
from datetime import (\n datetime,\n timedelta,\n)\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.algos import (\n Infinity,\n NegInfinity,\n)\n\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestRank:\n s = Series([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3])\n df = DataFrame({"A": s, "B": s})\n\n results = {\n "average": np.array([1.5, 5.5, 7.0, 3.5, np.nan, 3.5, 1.5, 8.0, np.nan, 5.5]),\n "min": np.array([1, 5, 7, 3, np.nan, 3, 1, 8, np.nan, 5]),\n "max": np.array([2, 6, 7, 4, np.nan, 4, 2, 8, np.nan, 6]),\n "first": np.array([1, 5, 7, 3, np.nan, 4, 2, 8, np.nan, 6]),\n "dense": np.array([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3]),\n }\n\n @pytest.fixture(params=["average", "min", "max", "first", "dense"])\n def method(self, request):\n """\n Fixture for trying all rank methods\n """\n return request.param\n\n def test_rank(self, float_frame):\n sp_stats = pytest.importorskip("scipy.stats")\n\n float_frame.loc[::2, "A"] = np.nan\n float_frame.loc[::3, "B"] = np.nan\n float_frame.loc[::4, "C"] = np.nan\n float_frame.loc[::5, "D"] = np.nan\n\n ranks0 = float_frame.rank()\n ranks1 = float_frame.rank(1)\n mask = np.isnan(float_frame.values)\n\n fvals = float_frame.fillna(np.inf).values\n\n exp0 = np.apply_along_axis(sp_stats.rankdata, 0, fvals)\n exp0[mask] = np.nan\n\n exp1 = np.apply_along_axis(sp_stats.rankdata, 1, fvals)\n exp1[mask] = np.nan\n\n tm.assert_almost_equal(ranks0.values, exp0)\n tm.assert_almost_equal(ranks1.values, exp1)\n\n # integers\n df = DataFrame(\n np.random.default_rng(2).integers(0, 5, size=40).reshape((10, 4))\n )\n\n result = df.rank()\n exp = df.astype(float).rank()\n tm.assert_frame_equal(result, exp)\n\n result = df.rank(1)\n exp = df.astype(float).rank(1)\n tm.assert_frame_equal(result, exp)\n\n def test_rank2(self):\n df = DataFrame([[1, 3, 2], [1, 2, 3]])\n expected = DataFrame([[1.0, 3.0, 2.0], [1, 2, 3]]) / 3.0\n result = df.rank(1, pct=True)\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame([[1, 3, 2], [1, 2, 3]])\n expected = df.rank(0) / 2.0\n result = df.rank(0, pct=True)\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame([["b", "c", "a"], ["a", "c", "b"]])\n expected = DataFrame([[2.0, 3.0, 1.0], [1, 3, 2]])\n result = df.rank(1, numeric_only=False)\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame([[2.0, 1.5, 1.0], [1, 1.5, 2]])\n result = df.rank(0, numeric_only=False)\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame([["b", np.nan, "a"], ["a", "c", "b"]])\n expected = DataFrame([[2.0, np.nan, 1.0], [1.0, 3.0, 2.0]])\n result = df.rank(1, numeric_only=False)\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame([[2.0, np.nan, 1.0], [1.0, 1.0, 2.0]])\n result = df.rank(0, numeric_only=False)\n tm.assert_frame_equal(result, expected)\n\n # f7u12, this does not work without extensive workaround\n data = [\n [datetime(2001, 1, 5), np.nan, datetime(2001, 1, 2)],\n [datetime(2000, 1, 2), datetime(2000, 1, 3), datetime(2000, 1, 1)],\n ]\n df = DataFrame(data)\n\n # check the rank\n expected = DataFrame([[2.0, np.nan, 1.0], [2.0, 3.0, 1.0]])\n result = df.rank(1, numeric_only=False, ascending=True)\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame([[1.0, np.nan, 2.0], [2.0, 1.0, 3.0]])\n result = df.rank(1, numeric_only=False, ascending=False)\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame({"a": [1e-20, -5, 1e-20 + 1e-40, 10, 1e60, 1e80, 1e-30]})\n exp = DataFrame({"a": [3.5, 1.0, 3.5, 5.0, 6.0, 7.0, 2.0]})\n tm.assert_frame_equal(df.rank(), exp)\n\n def test_rank_does_not_mutate(self):\n # GH#18521\n # Check rank does not mutate DataFrame\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 3)), dtype="float64"\n )\n expected = df.copy()\n df.rank()\n result = df\n tm.assert_frame_equal(result, expected)\n\n def test_rank_mixed_frame(self, float_string_frame):\n float_string_frame["datetime"] = datetime.now()\n float_string_frame["timedelta"] = timedelta(days=1, seconds=1)\n\n float_string_frame.rank(numeric_only=False)\n with pytest.raises(TypeError, match="not supported between instances of"):\n float_string_frame.rank(axis=1)\n\n def test_rank_na_option(self, float_frame):\n sp_stats = pytest.importorskip("scipy.stats")\n\n float_frame.loc[::2, "A"] = np.nan\n float_frame.loc[::3, "B"] = np.nan\n float_frame.loc[::4, "C"] = np.nan\n float_frame.loc[::5, "D"] = np.nan\n\n # bottom\n ranks0 = float_frame.rank(na_option="bottom")\n ranks1 = float_frame.rank(1, na_option="bottom")\n\n fvals = float_frame.fillna(np.inf).values\n\n exp0 = np.apply_along_axis(sp_stats.rankdata, 0, fvals)\n exp1 = np.apply_along_axis(sp_stats.rankdata, 1, fvals)\n\n tm.assert_almost_equal(ranks0.values, exp0)\n tm.assert_almost_equal(ranks1.values, exp1)\n\n # top\n ranks0 = float_frame.rank(na_option="top")\n ranks1 = float_frame.rank(1, na_option="top")\n\n fval0 = float_frame.fillna((float_frame.min() - 1).to_dict()).values\n fval1 = float_frame.T\n fval1 = fval1.fillna((fval1.min() - 1).to_dict()).T\n fval1 = fval1.fillna(np.inf).values\n\n exp0 = np.apply_along_axis(sp_stats.rankdata, 0, fval0)\n exp1 = np.apply_along_axis(sp_stats.rankdata, 1, fval1)\n\n tm.assert_almost_equal(ranks0.values, exp0)\n tm.assert_almost_equal(ranks1.values, exp1)\n\n # descending\n\n # bottom\n ranks0 = float_frame.rank(na_option="top", ascending=False)\n ranks1 = float_frame.rank(1, na_option="top", ascending=False)\n\n fvals = float_frame.fillna(np.inf).values\n\n exp0 = np.apply_along_axis(sp_stats.rankdata, 0, -fvals)\n exp1 = np.apply_along_axis(sp_stats.rankdata, 1, -fvals)\n\n tm.assert_almost_equal(ranks0.values, exp0)\n tm.assert_almost_equal(ranks1.values, exp1)\n\n # descending\n\n # top\n ranks0 = float_frame.rank(na_option="bottom", ascending=False)\n ranks1 = float_frame.rank(1, na_option="bottom", ascending=False)\n\n fval0 = float_frame.fillna((float_frame.min() - 1).to_dict()).values\n fval1 = float_frame.T\n fval1 = fval1.fillna((fval1.min() - 1).to_dict()).T\n fval1 = fval1.fillna(np.inf).values\n\n exp0 = np.apply_along_axis(sp_stats.rankdata, 0, -fval0)\n exp1 = np.apply_along_axis(sp_stats.rankdata, 1, -fval1)\n\n tm.assert_numpy_array_equal(ranks0.values, exp0)\n tm.assert_numpy_array_equal(ranks1.values, exp1)\n\n # bad values throw error\n msg = "na_option must be one of 'keep', 'top', or 'bottom'"\n\n with pytest.raises(ValueError, match=msg):\n float_frame.rank(na_option="bad", ascending=False)\n\n # invalid type\n with pytest.raises(ValueError, match=msg):\n float_frame.rank(na_option=True, ascending=False)\n\n def test_rank_axis(self):\n # check if using axes' names gives the same result\n df = DataFrame([[2, 1], [4, 3]])\n tm.assert_frame_equal(df.rank(axis=0), df.rank(axis="index"))\n tm.assert_frame_equal(df.rank(axis=1), df.rank(axis="columns"))\n\n @pytest.mark.parametrize("ax", [0, 1])\n @pytest.mark.parametrize("m", ["average", "min", "max", "first", "dense"])\n def test_rank_methods_frame(self, ax, m):\n sp_stats = pytest.importorskip("scipy.stats")\n\n xs = np.random.default_rng(2).integers(0, 21, (100, 26))\n xs = (xs - 10.0) / 10.0\n cols = [chr(ord("z") - i) for i in range(xs.shape[1])]\n\n for vals in [xs, xs + 1e6, xs * 1e-6]:\n df = DataFrame(vals, columns=cols)\n\n result = df.rank(axis=ax, method=m)\n sprank = np.apply_along_axis(\n sp_stats.rankdata, ax, vals, m if m != "first" else "ordinal"\n )\n sprank = sprank.astype(np.float64)\n expected = DataFrame(sprank, columns=cols).astype("float64")\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("dtype", ["O", "f8", "i8"])\n def test_rank_descending(self, method, dtype):\n if "i" in dtype:\n df = self.df.dropna().astype(dtype)\n else:\n df = self.df.astype(dtype)\n\n res = df.rank(ascending=False)\n expected = (df.max() - df).rank()\n tm.assert_frame_equal(res, expected)\n\n expected = (df.max() - df).rank(method=method)\n\n if dtype != "O":\n res2 = df.rank(method=method, ascending=False, numeric_only=True)\n tm.assert_frame_equal(res2, expected)\n\n res3 = df.rank(method=method, ascending=False, numeric_only=False)\n tm.assert_frame_equal(res3, expected)\n\n @pytest.mark.parametrize("axis", [0, 1])\n @pytest.mark.parametrize("dtype", [None, object])\n def test_rank_2d_tie_methods(self, method, axis, dtype):\n df = self.df\n\n def _check2d(df, expected, method="average", axis=0):\n exp_df = DataFrame({"A": expected, "B": expected})\n\n if axis == 1:\n df = df.T\n exp_df = exp_df.T\n\n result = df.rank(method=method, axis=axis)\n tm.assert_frame_equal(result, exp_df)\n\n frame = df if dtype is None else df.astype(dtype)\n _check2d(frame, self.results[method], method=method, axis=axis)\n\n @pytest.mark.parametrize(\n "method,exp",\n [\n ("dense", [[1.0, 1.0, 1.0], [1.0, 0.5, 2.0 / 3], [1.0, 0.5, 1.0 / 3]]),\n (\n "min",\n [\n [1.0 / 3, 1.0, 1.0],\n [1.0 / 3, 1.0 / 3, 2.0 / 3],\n [1.0 / 3, 1.0 / 3, 1.0 / 3],\n ],\n ),\n (\n "max",\n [[1.0, 1.0, 1.0], [1.0, 2.0 / 3, 2.0 / 3], [1.0, 2.0 / 3, 1.0 / 3]],\n ),\n (\n "average",\n [[2.0 / 3, 1.0, 1.0], [2.0 / 3, 0.5, 2.0 / 3], [2.0 / 3, 0.5, 1.0 / 3]],\n ),\n (\n "first",\n [\n [1.0 / 3, 1.0, 1.0],\n [2.0 / 3, 1.0 / 3, 2.0 / 3],\n [3.0 / 3, 2.0 / 3, 1.0 / 3],\n ],\n ),\n ],\n )\n def test_rank_pct_true(self, method, exp):\n # see gh-15630.\n\n df = DataFrame([[2012, 66, 3], [2012, 65, 2], [2012, 65, 1]])\n result = df.rank(method=method, pct=True)\n\n expected = DataFrame(exp)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.single_cpu\n def test_pct_max_many_rows(self):\n # GH 18271\n df = DataFrame(\n {"A": np.arange(2**24 + 1), "B": np.arange(2**24 + 1, 0, -1)}\n )\n result = df.rank(pct=True).max()\n assert (result == 1).all()\n\n @pytest.mark.parametrize(\n "contents,dtype",\n [\n (\n [\n -np.inf,\n -50,\n -1,\n -1e-20,\n -1e-25,\n -1e-50,\n 0,\n 1e-40,\n 1e-20,\n 1e-10,\n 2,\n 40,\n np.inf,\n ],\n "float64",\n ),\n (\n [\n -np.inf,\n -50,\n -1,\n -1e-20,\n -1e-25,\n -1e-45,\n 0,\n 1e-40,\n 1e-20,\n 1e-10,\n 2,\n 40,\n np.inf,\n ],\n "float32",\n ),\n ([np.iinfo(np.uint8).min, 1, 2, 100, np.iinfo(np.uint8).max], "uint8"),\n (\n [\n np.iinfo(np.int64).min,\n -100,\n 0,\n 1,\n 9999,\n 100000,\n 1e10,\n np.iinfo(np.int64).max,\n ],\n "int64",\n ),\n ([NegInfinity(), "1", "A", "BA", "Ba", "C", Infinity()], "object"),\n (\n [datetime(2001, 1, 1), datetime(2001, 1, 2), datetime(2001, 1, 5)],\n "datetime64",\n ),\n ],\n )\n def test_rank_inf_and_nan(self, contents, dtype, frame_or_series):\n dtype_na_map = {\n "float64": np.nan,\n "float32": np.nan,\n "object": None,\n "datetime64": np.datetime64("nat"),\n }\n # Insert nans at random positions if underlying dtype has missing\n # value. Then adjust the expected order by adding nans accordingly\n # This is for testing whether rank calculation is affected\n # when values are interwined with nan values.\n values = np.array(contents, dtype=dtype)\n exp_order = np.array(range(len(values)), dtype="float64") + 1.0\n if dtype in dtype_na_map:\n na_value = dtype_na_map[dtype]\n nan_indices = np.random.default_rng(2).choice(range(len(values)), 5)\n values = np.insert(values, nan_indices, na_value)\n exp_order = np.insert(exp_order, nan_indices, np.nan)\n\n # Shuffle the testing array and expected results in the same way\n random_order = np.random.default_rng(2).permutation(len(values))\n obj = frame_or_series(values[random_order])\n expected = frame_or_series(exp_order[random_order], dtype="float64")\n result = obj.rank()\n tm.assert_equal(result, expected)\n\n def test_df_series_inf_nan_consistency(self):\n # GH#32593\n index = [5, 4, 3, 2, 1, 6, 7, 8, 9, 10]\n col1 = [5, 4, 3, 5, 8, 5, 2, 1, 6, 6]\n col2 = [5, 4, np.nan, 5, 8, 5, np.inf, np.nan, 6, -np.inf]\n df = DataFrame(\n data={\n "col1": col1,\n "col2": col2,\n },\n index=index,\n dtype="f8",\n )\n df_result = df.rank()\n\n series_result = df.copy()\n series_result["col1"] = df["col1"].rank()\n series_result["col2"] = df["col2"].rank()\n\n tm.assert_frame_equal(df_result, series_result)\n\n def test_rank_both_inf(self):\n # GH#32593\n df = DataFrame({"a": [-np.inf, 0, np.inf]})\n expected = DataFrame({"a": [1.0, 2.0, 3.0]})\n result = df.rank()\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "na_option,ascending,expected",\n [\n ("top", True, [3.0, 1.0, 2.0]),\n ("top", False, [2.0, 1.0, 3.0]),\n ("bottom", True, [2.0, 3.0, 1.0]),\n ("bottom", False, [1.0, 3.0, 2.0]),\n ],\n )\n def test_rank_inf_nans_na_option(\n self, frame_or_series, method, na_option, ascending, expected\n ):\n obj = frame_or_series([np.inf, np.nan, -np.inf])\n result = obj.rank(method=method, na_option=na_option, ascending=ascending)\n expected = frame_or_series(expected)\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize(\n "na_option,ascending,expected",\n [\n ("bottom", True, [1.0, 2.0, 4.0, 3.0]),\n ("bottom", False, [1.0, 2.0, 4.0, 3.0]),\n ("top", True, [2.0, 3.0, 1.0, 4.0]),\n ("top", False, [2.0, 3.0, 1.0, 4.0]),\n ],\n )\n def test_rank_object_first(self, frame_or_series, na_option, ascending, expected):\n obj = frame_or_series(["foo", "foo", None, "foo"])\n result = obj.rank(method="first", na_option=na_option, ascending=ascending)\n expected = frame_or_series(expected)\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize(\n "data,expected",\n [\n (\n {"a": [1, 2, "a"], "b": [4, 5, 6]},\n DataFrame({"b": [1.0, 2.0, 3.0]}, columns=Index(["b"], dtype=object)),\n ),\n ({"a": [1, 2, "a"]}, DataFrame(index=range(3), columns=[])),\n ],\n )\n def test_rank_mixed_axis_zero(self, data, expected):\n df = DataFrame(data, columns=Index(list(data.keys()), dtype=object))\n with pytest.raises(TypeError, match="'<' not supported between instances of"):\n df.rank()\n result = df.rank(numeric_only=True)\n tm.assert_frame_equal(result, expected)\n\n def test_rank_string_dtype(self, string_dtype_no_object):\n # GH#55362\n obj = Series(["foo", "foo", None, "foo"], dtype=string_dtype_no_object)\n result = obj.rank(method="first")\n exp_dtype = (\n "Float64" if string_dtype_no_object == "string[pyarrow]" else "float64"\n )\n if string_dtype_no_object.storage == "python":\n # TODO nullable string[python] should also return nullable Int64\n exp_dtype = "float64"\n expected = Series([1, 2, None, 3], dtype=exp_dtype)\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_rank.py
test_rank.py
Python
17,548
0.95
0.069034
0.058824
vue-tools
430
2024-09-06T15:33:35.713616
GPL-3.0
true
0ac77f90a069a6b930d3a5998728ff72
from datetime import (\n datetime,\n timedelta,\n)\nimport inspect\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs.timezones import dateutil_gettz as gettz\nfrom pandas.compat import (\n IS64,\n is_platform_windows,\n)\nfrom pandas.compat.numpy import np_version_gt2\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n CategoricalIndex,\n DataFrame,\n Index,\n MultiIndex,\n Series,\n date_range,\n isna,\n)\nimport pandas._testing as tm\nfrom pandas.api.types import CategoricalDtype\n\n\nclass TestReindexSetIndex:\n # Tests that check both reindex and set_index\n\n def test_dti_set_index_reindex_datetimeindex(self):\n # GH#6631\n df = DataFrame(np.random.default_rng(2).random(6))\n idx1 = date_range("2011/01/01", periods=6, freq="ME", tz="US/Eastern")\n idx2 = date_range("2013", periods=6, freq="YE", tz="Asia/Tokyo")\n\n df = df.set_index(idx1)\n tm.assert_index_equal(df.index, idx1)\n df = df.reindex(idx2)\n tm.assert_index_equal(df.index, idx2)\n\n def test_dti_set_index_reindex_freq_with_tz(self):\n # GH#11314 with tz\n index = date_range(\n datetime(2015, 10, 1), datetime(2015, 10, 1, 23), freq="h", tz="US/Eastern"\n )\n df = DataFrame(\n np.random.default_rng(2).standard_normal((24, 1)),\n columns=["a"],\n index=index,\n )\n new_index = date_range(\n datetime(2015, 10, 2), datetime(2015, 10, 2, 23), freq="h", tz="US/Eastern"\n )\n\n result = df.set_index(new_index)\n assert result.index.freq == index.freq\n\n def test_set_reset_index_intervalindex(self):\n df = DataFrame({"A": range(10)})\n ser = pd.cut(df.A, 5)\n df["B"] = ser\n df = df.set_index("B")\n\n df = df.reset_index()\n\n def test_setitem_reset_index_dtypes(self):\n # GH 22060\n df = DataFrame(columns=["a", "b", "c"]).astype(\n {"a": "datetime64[ns]", "b": np.int64, "c": np.float64}\n )\n df1 = df.set_index(["a"])\n df1["d"] = []\n result = df1.reset_index()\n expected = DataFrame(columns=["a", "b", "c", "d"], index=range(0)).astype(\n {"a": "datetime64[ns]", "b": np.int64, "c": np.float64, "d": np.float64}\n )\n tm.assert_frame_equal(result, expected)\n\n df2 = df.set_index(["a", "b"])\n df2["d"] = []\n result = df2.reset_index()\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "timezone, year, month, day, hour",\n [["America/Chicago", 2013, 11, 3, 1], ["America/Santiago", 2021, 4, 3, 23]],\n )\n def test_reindex_timestamp_with_fold(self, timezone, year, month, day, hour):\n # see gh-40817\n test_timezone = gettz(timezone)\n transition_1 = pd.Timestamp(\n year=year,\n month=month,\n day=day,\n hour=hour,\n minute=0,\n fold=0,\n tzinfo=test_timezone,\n )\n transition_2 = pd.Timestamp(\n year=year,\n month=month,\n day=day,\n hour=hour,\n minute=0,\n fold=1,\n tzinfo=test_timezone,\n )\n df = (\n DataFrame({"index": [transition_1, transition_2], "vals": ["a", "b"]})\n .set_index("index")\n .reindex(["1", "2"])\n )\n exp = DataFrame({"index": ["1", "2"], "vals": [np.nan, np.nan]}).set_index(\n "index"\n )\n exp = exp.astype(df.vals.dtype)\n tm.assert_frame_equal(\n df,\n exp,\n )\n\n\nclass TestDataFrameSelectReindex:\n # These are specific reindex-based tests; other indexing tests should go in\n # test_indexing\n\n @pytest.mark.xfail(\n not IS64 or (is_platform_windows() and not np_version_gt2),\n reason="Passes int32 values to DatetimeArray in make_na_array on "\n "windows, 32bit linux builds",\n )\n @td.skip_array_manager_not_yet_implemented\n def test_reindex_tzaware_fill_value(self):\n # GH#52586\n df = DataFrame([[1]])\n\n ts = pd.Timestamp("2023-04-10 17:32", tz="US/Pacific")\n res = df.reindex([0, 1], axis=1, fill_value=ts)\n assert res.dtypes[1] == pd.DatetimeTZDtype(unit="s", tz="US/Pacific")\n expected = DataFrame({0: [1], 1: [ts]})\n expected[1] = expected[1].astype(res.dtypes[1])\n tm.assert_frame_equal(res, expected)\n\n per = ts.tz_localize(None).to_period("s")\n res = df.reindex([0, 1], axis=1, fill_value=per)\n assert res.dtypes[1] == pd.PeriodDtype("s")\n expected = DataFrame({0: [1], 1: [per]})\n tm.assert_frame_equal(res, expected)\n\n interval = pd.Interval(ts, ts + pd.Timedelta(seconds=1))\n res = df.reindex([0, 1], axis=1, fill_value=interval)\n assert res.dtypes[1] == pd.IntervalDtype("datetime64[s, US/Pacific]", "right")\n expected = DataFrame({0: [1], 1: [interval]})\n expected[1] = expected[1].astype(res.dtypes[1])\n tm.assert_frame_equal(res, expected)\n\n def test_reindex_copies(self):\n # based on asv time_reindex_axis1\n N = 10\n df = DataFrame(np.random.default_rng(2).standard_normal((N * 10, N)))\n cols = np.arange(N)\n np.random.default_rng(2).shuffle(cols)\n\n result = df.reindex(columns=cols, copy=True)\n assert not np.shares_memory(result[0]._values, df[0]._values)\n\n # pass both columns and index\n result2 = df.reindex(columns=cols, index=df.index, copy=True)\n assert not np.shares_memory(result2[0]._values, df[0]._values)\n\n def test_reindex_copies_ea(self, using_copy_on_write):\n # https://github.com/pandas-dev/pandas/pull/51197\n # also ensure to honor copy keyword for ExtensionDtypes\n N = 10\n df = DataFrame(\n np.random.default_rng(2).standard_normal((N * 10, N)), dtype="Float64"\n )\n cols = np.arange(N)\n np.random.default_rng(2).shuffle(cols)\n\n result = df.reindex(columns=cols, copy=True)\n if using_copy_on_write:\n assert np.shares_memory(result[0].array._data, df[0].array._data)\n else:\n assert not np.shares_memory(result[0].array._data, df[0].array._data)\n\n # pass both columns and index\n result2 = df.reindex(columns=cols, index=df.index, copy=True)\n if using_copy_on_write:\n assert np.shares_memory(result2[0].array._data, df[0].array._data)\n else:\n assert not np.shares_memory(result2[0].array._data, df[0].array._data)\n\n @td.skip_array_manager_not_yet_implemented\n def test_reindex_date_fill_value(self):\n # passing date to dt64 is deprecated; enforced in 2.0 to cast to object\n arr = date_range("2016-01-01", periods=6).values.reshape(3, 2)\n df = DataFrame(arr, columns=["A", "B"], index=range(3))\n\n ts = df.iloc[0, 0]\n fv = ts.date()\n\n res = df.reindex(index=range(4), columns=["A", "B", "C"], fill_value=fv)\n\n expected = DataFrame(\n {"A": df["A"].tolist() + [fv], "B": df["B"].tolist() + [fv], "C": [fv] * 4},\n dtype=object,\n )\n tm.assert_frame_equal(res, expected)\n\n # only reindexing rows\n res = df.reindex(index=range(4), fill_value=fv)\n tm.assert_frame_equal(res, expected[["A", "B"]])\n\n # same with a datetime-castable str\n res = df.reindex(\n index=range(4), columns=["A", "B", "C"], fill_value="2016-01-01"\n )\n expected = DataFrame(\n {"A": df["A"].tolist() + [ts], "B": df["B"].tolist() + [ts], "C": [ts] * 4},\n )\n tm.assert_frame_equal(res, expected)\n\n def test_reindex_with_multi_index(self):\n # https://github.com/pandas-dev/pandas/issues/29896\n # tests for reindexing a multi-indexed DataFrame with a new MultiIndex\n #\n # confirms that we can reindex a multi-indexed DataFrame with a new\n # MultiIndex object correctly when using no filling, backfilling, and\n # padding\n #\n # The DataFrame, `df`, used in this test is:\n # c\n # a b\n # -1 0 A\n # 1 B\n # 2 C\n # 3 D\n # 4 E\n # 5 F\n # 6 G\n # 0 0 A\n # 1 B\n # 2 C\n # 3 D\n # 4 E\n # 5 F\n # 6 G\n # 1 0 A\n # 1 B\n # 2 C\n # 3 D\n # 4 E\n # 5 F\n # 6 G\n #\n # and the other MultiIndex, `new_multi_index`, is:\n # 0: 0 0.5\n # 1: 2.0\n # 2: 5.0\n # 3: 5.8\n df = DataFrame(\n {\n "a": [-1] * 7 + [0] * 7 + [1] * 7,\n "b": list(range(7)) * 3,\n "c": ["A", "B", "C", "D", "E", "F", "G"] * 3,\n }\n ).set_index(["a", "b"])\n new_index = [0.5, 2.0, 5.0, 5.8]\n new_multi_index = MultiIndex.from_product([[0], new_index], names=["a", "b"])\n\n # reindexing w/o a `method` value\n reindexed = df.reindex(new_multi_index)\n expected = DataFrame(\n {"a": [0] * 4, "b": new_index, "c": [np.nan, "C", "F", np.nan]}\n ).set_index(["a", "b"])\n tm.assert_frame_equal(expected, reindexed)\n\n # reindexing with backfilling\n expected = DataFrame(\n {"a": [0] * 4, "b": new_index, "c": ["B", "C", "F", "G"]}\n ).set_index(["a", "b"])\n reindexed_with_backfilling = df.reindex(new_multi_index, method="bfill")\n tm.assert_frame_equal(expected, reindexed_with_backfilling)\n\n reindexed_with_backfilling = df.reindex(new_multi_index, method="backfill")\n tm.assert_frame_equal(expected, reindexed_with_backfilling)\n\n # reindexing with padding\n expected = DataFrame(\n {"a": [0] * 4, "b": new_index, "c": ["A", "C", "F", "F"]}\n ).set_index(["a", "b"])\n reindexed_with_padding = df.reindex(new_multi_index, method="pad")\n tm.assert_frame_equal(expected, reindexed_with_padding)\n\n reindexed_with_padding = df.reindex(new_multi_index, method="ffill")\n tm.assert_frame_equal(expected, reindexed_with_padding)\n\n @pytest.mark.parametrize(\n "method,expected_values",\n [\n ("nearest", [0, 1, 1, 2]),\n ("pad", [np.nan, 0, 1, 1]),\n ("backfill", [0, 1, 2, 2]),\n ],\n )\n def test_reindex_methods(self, method, expected_values):\n df = DataFrame({"x": list(range(5))})\n target = np.array([-0.1, 0.9, 1.1, 1.5])\n\n expected = DataFrame({"x": expected_values}, index=target)\n actual = df.reindex(target, method=method)\n tm.assert_frame_equal(expected, actual)\n\n actual = df.reindex(target, method=method, tolerance=1)\n tm.assert_frame_equal(expected, actual)\n actual = df.reindex(target, method=method, tolerance=[1, 1, 1, 1])\n tm.assert_frame_equal(expected, actual)\n\n e2 = expected[::-1]\n actual = df.reindex(target[::-1], method=method)\n tm.assert_frame_equal(e2, actual)\n\n new_order = [3, 0, 2, 1]\n e2 = expected.iloc[new_order]\n actual = df.reindex(target[new_order], method=method)\n tm.assert_frame_equal(e2, actual)\n\n switched_method = (\n "pad" if method == "backfill" else "backfill" if method == "pad" else method\n )\n actual = df[::-1].reindex(target, method=switched_method)\n tm.assert_frame_equal(expected, actual)\n\n def test_reindex_methods_nearest_special(self):\n df = DataFrame({"x": list(range(5))})\n target = np.array([-0.1, 0.9, 1.1, 1.5])\n\n expected = DataFrame({"x": [0, 1, 1, np.nan]}, index=target)\n actual = df.reindex(target, method="nearest", tolerance=0.2)\n tm.assert_frame_equal(expected, actual)\n\n expected = DataFrame({"x": [0, np.nan, 1, np.nan]}, index=target)\n actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1])\n tm.assert_frame_equal(expected, actual)\n\n def test_reindex_nearest_tz(self, tz_aware_fixture):\n # GH26683\n tz = tz_aware_fixture\n idx = date_range("2019-01-01", periods=5, tz=tz)\n df = DataFrame({"x": list(range(5))}, index=idx)\n\n expected = df.head(3)\n actual = df.reindex(idx[:3], method="nearest")\n tm.assert_frame_equal(expected, actual)\n\n def test_reindex_nearest_tz_empty_frame(self):\n # https://github.com/pandas-dev/pandas/issues/31964\n dti = pd.DatetimeIndex(["2016-06-26 14:27:26+00:00"])\n df = DataFrame(index=pd.DatetimeIndex(["2016-07-04 14:00:59+00:00"]))\n expected = DataFrame(index=dti)\n result = df.reindex(dti, method="nearest")\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_frame_add_nat(self):\n rng = date_range("1/1/2000 00:00:00", periods=10, freq="10s")\n df = DataFrame(\n {"A": np.random.default_rng(2).standard_normal(len(rng)), "B": rng}\n )\n\n result = df.reindex(range(15))\n assert np.issubdtype(result["B"].dtype, np.dtype("M8[ns]"))\n\n mask = isna(result)["B"]\n assert mask[-5:].all()\n assert not mask[:-5].any()\n\n @pytest.mark.parametrize(\n "method, exp_values",\n [("ffill", [0, 1, 2, 3]), ("bfill", [1.0, 2.0, 3.0, np.nan])],\n )\n def test_reindex_frame_tz_ffill_bfill(self, frame_or_series, method, exp_values):\n # GH#38566\n obj = frame_or_series(\n [0, 1, 2, 3],\n index=date_range("2020-01-01 00:00:00", periods=4, freq="h", tz="UTC"),\n )\n new_index = date_range("2020-01-01 00:01:00", periods=4, freq="h", tz="UTC")\n result = obj.reindex(new_index, method=method, tolerance=pd.Timedelta("1 hour"))\n expected = frame_or_series(exp_values, index=new_index)\n tm.assert_equal(result, expected)\n\n def test_reindex_limit(self):\n # GH 28631\n data = [["A", "A", "A"], ["B", "B", "B"], ["C", "C", "C"], ["D", "D", "D"]]\n exp_data = [\n ["A", "A", "A"],\n ["B", "B", "B"],\n ["C", "C", "C"],\n ["D", "D", "D"],\n ["D", "D", "D"],\n [np.nan, np.nan, np.nan],\n ]\n df = DataFrame(data)\n result = df.reindex([0, 1, 2, 3, 4, 5], method="ffill", limit=1)\n expected = DataFrame(exp_data)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "idx, check_index_type",\n [\n [["C", "B", "A"], True],\n [["F", "C", "A", "D"], True],\n [["A"], True],\n [["A", "B", "C"], True],\n [["C", "A", "B"], True],\n [["C", "B"], True],\n [["C", "A"], True],\n [["A", "B"], True],\n [["B", "A", "C"], True],\n # reindex by these causes different MultiIndex levels\n [["D", "F"], False],\n [["A", "C", "B"], False],\n ],\n )\n def test_reindex_level_verify_first_level(self, idx, check_index_type):\n df = DataFrame(\n {\n "jim": list("B" * 4 + "A" * 2 + "C" * 3),\n "joe": list("abcdeabcd")[::-1],\n "jolie": [10, 20, 30] * 3,\n "joline": np.random.default_rng(2).integers(0, 1000, 9),\n }\n )\n icol = ["jim", "joe", "jolie"]\n\n def f(val):\n return np.nonzero((df["jim"] == val).to_numpy())[0]\n\n i = np.concatenate(list(map(f, idx)))\n left = df.set_index(icol).reindex(idx, level="jim")\n right = df.iloc[i].set_index(icol)\n tm.assert_frame_equal(left, right, check_index_type=check_index_type)\n\n @pytest.mark.parametrize(\n "idx",\n [\n ("mid",),\n ("mid", "btm"),\n ("mid", "btm", "top"),\n ("mid",),\n ("mid", "top"),\n ("mid", "top", "btm"),\n ("btm",),\n ("btm", "mid"),\n ("btm", "mid", "top"),\n ("btm",),\n ("btm", "top"),\n ("btm", "top", "mid"),\n ("top",),\n ("top", "mid"),\n ("top", "mid", "btm"),\n ("top",),\n ("top", "btm"),\n ("top", "btm", "mid"),\n ],\n )\n def test_reindex_level_verify_first_level_repeats(self, idx):\n df = DataFrame(\n {\n "jim": ["mid"] * 5 + ["btm"] * 8 + ["top"] * 7,\n "joe": ["3rd"] * 2\n + ["1st"] * 3\n + ["2nd"] * 3\n + ["1st"] * 2\n + ["3rd"] * 3\n + ["1st"] * 2\n + ["3rd"] * 3\n + ["2nd"] * 2,\n # this needs to be jointly unique with jim and joe or\n # reindexing will fail ~1.5% of the time, this works\n # out to needing unique groups of same size as joe\n "jolie": np.concatenate(\n [\n np.random.default_rng(2).choice(1000, x, replace=False)\n for x in [2, 3, 3, 2, 3, 2, 3, 2]\n ]\n ),\n "joline": np.random.default_rng(2).standard_normal(20).round(3) * 10,\n }\n )\n icol = ["jim", "joe", "jolie"]\n\n def f(val):\n return np.nonzero((df["jim"] == val).to_numpy())[0]\n\n i = np.concatenate(list(map(f, idx)))\n left = df.set_index(icol).reindex(idx, level="jim")\n right = df.iloc[i].set_index(icol)\n tm.assert_frame_equal(left, right)\n\n @pytest.mark.parametrize(\n "idx, indexer",\n [\n [\n ["1st", "2nd", "3rd"],\n [2, 3, 4, 0, 1, 8, 9, 5, 6, 7, 10, 11, 12, 13, 14, 18, 19, 15, 16, 17],\n ],\n [\n ["3rd", "2nd", "1st"],\n [0, 1, 2, 3, 4, 10, 11, 12, 5, 6, 7, 8, 9, 15, 16, 17, 18, 19, 13, 14],\n ],\n [["2nd", "3rd"], [0, 1, 5, 6, 7, 10, 11, 12, 18, 19, 15, 16, 17]],\n [["3rd", "1st"], [0, 1, 2, 3, 4, 10, 11, 12, 8, 9, 15, 16, 17, 13, 14]],\n ],\n )\n def test_reindex_level_verify_repeats(self, idx, indexer):\n df = DataFrame(\n {\n "jim": ["mid"] * 5 + ["btm"] * 8 + ["top"] * 7,\n "joe": ["3rd"] * 2\n + ["1st"] * 3\n + ["2nd"] * 3\n + ["1st"] * 2\n + ["3rd"] * 3\n + ["1st"] * 2\n + ["3rd"] * 3\n + ["2nd"] * 2,\n # this needs to be jointly unique with jim and joe or\n # reindexing will fail ~1.5% of the time, this works\n # out to needing unique groups of same size as joe\n "jolie": np.concatenate(\n [\n np.random.default_rng(2).choice(1000, x, replace=False)\n for x in [2, 3, 3, 2, 3, 2, 3, 2]\n ]\n ),\n "joline": np.random.default_rng(2).standard_normal(20).round(3) * 10,\n }\n )\n icol = ["jim", "joe", "jolie"]\n left = df.set_index(icol).reindex(idx, level="joe")\n right = df.iloc[indexer].set_index(icol)\n tm.assert_frame_equal(left, right)\n\n @pytest.mark.parametrize(\n "idx, indexer, check_index_type",\n [\n [list("abcde"), [3, 2, 1, 0, 5, 4, 8, 7, 6], True],\n [list("abcd"), [3, 2, 1, 0, 5, 8, 7, 6], True],\n [list("abc"), [3, 2, 1, 8, 7, 6], True],\n [list("eca"), [1, 3, 4, 6, 8], True],\n [list("edc"), [0, 1, 4, 5, 6], True],\n [list("eadbc"), [3, 0, 2, 1, 4, 5, 8, 7, 6], True],\n [list("edwq"), [0, 4, 5], True],\n [list("wq"), [], False],\n ],\n )\n def test_reindex_level_verify(self, idx, indexer, check_index_type):\n df = DataFrame(\n {\n "jim": list("B" * 4 + "A" * 2 + "C" * 3),\n "joe": list("abcdeabcd")[::-1],\n "jolie": [10, 20, 30] * 3,\n "joline": np.random.default_rng(2).integers(0, 1000, 9),\n }\n )\n icol = ["jim", "joe", "jolie"]\n left = df.set_index(icol).reindex(idx, level="joe")\n right = df.iloc[indexer].set_index(icol)\n tm.assert_frame_equal(left, right, check_index_type=check_index_type)\n\n def test_non_monotonic_reindex_methods(self):\n dr = date_range("2013-08-01", periods=6, freq="B")\n data = np.random.default_rng(2).standard_normal((6, 1))\n df = DataFrame(data, index=dr, columns=list("A"))\n df_rev = DataFrame(data, index=dr[[3, 4, 5] + [0, 1, 2]], columns=list("A"))\n # index is not monotonic increasing or decreasing\n msg = "index must be monotonic increasing or decreasing"\n with pytest.raises(ValueError, match=msg):\n df_rev.reindex(df.index, method="pad")\n with pytest.raises(ValueError, match=msg):\n df_rev.reindex(df.index, method="ffill")\n with pytest.raises(ValueError, match=msg):\n df_rev.reindex(df.index, method="bfill")\n with pytest.raises(ValueError, match=msg):\n df_rev.reindex(df.index, method="nearest")\n\n def test_reindex_sparse(self):\n # https://github.com/pandas-dev/pandas/issues/35286\n df = DataFrame(\n {"A": [0, 1], "B": pd.array([0, 1], dtype=pd.SparseDtype("int64", 0))}\n )\n result = df.reindex([0, 2])\n expected = DataFrame(\n {\n "A": [0.0, np.nan],\n "B": pd.array([0.0, np.nan], dtype=pd.SparseDtype("float64", 0.0)),\n },\n index=[0, 2],\n )\n tm.assert_frame_equal(result, expected)\n\n def test_reindex(self, float_frame, using_copy_on_write):\n datetime_series = Series(\n np.arange(30, dtype=np.float64), index=date_range("2020-01-01", periods=30)\n )\n\n newFrame = float_frame.reindex(datetime_series.index)\n\n for col in newFrame.columns:\n for idx, val in newFrame[col].items():\n if idx in float_frame.index:\n if np.isnan(val):\n assert np.isnan(float_frame[col][idx])\n else:\n assert val == float_frame[col][idx]\n else:\n assert np.isnan(val)\n\n for col, series in newFrame.items():\n tm.assert_index_equal(series.index, newFrame.index)\n emptyFrame = float_frame.reindex(Index([]))\n assert len(emptyFrame.index) == 0\n\n # Cython code should be unit-tested directly\n nonContigFrame = float_frame.reindex(datetime_series.index[::2])\n\n for col in nonContigFrame.columns:\n for idx, val in nonContigFrame[col].items():\n if idx in float_frame.index:\n if np.isnan(val):\n assert np.isnan(float_frame[col][idx])\n else:\n assert val == float_frame[col][idx]\n else:\n assert np.isnan(val)\n\n for col, series in nonContigFrame.items():\n tm.assert_index_equal(series.index, nonContigFrame.index)\n\n # corner cases\n\n # Same index, copies values but not index if copy=False\n newFrame = float_frame.reindex(float_frame.index, copy=False)\n if using_copy_on_write:\n assert newFrame.index.is_(float_frame.index)\n else:\n assert newFrame.index is float_frame.index\n\n # length zero\n newFrame = float_frame.reindex([])\n assert newFrame.empty\n assert len(newFrame.columns) == len(float_frame.columns)\n\n # length zero with columns reindexed with non-empty index\n newFrame = float_frame.reindex([])\n newFrame = newFrame.reindex(float_frame.index)\n assert len(newFrame.index) == len(float_frame.index)\n assert len(newFrame.columns) == len(float_frame.columns)\n\n # pass non-Index\n newFrame = float_frame.reindex(list(datetime_series.index))\n expected = datetime_series.index._with_freq(None)\n tm.assert_index_equal(newFrame.index, expected)\n\n # copy with no axes\n result = float_frame.reindex()\n tm.assert_frame_equal(result, float_frame)\n assert result is not float_frame\n\n def test_reindex_nan(self):\n df = DataFrame(\n [[1, 2], [3, 5], [7, 11], [9, 23]],\n index=[2, np.nan, 1, 5],\n columns=["joe", "jim"],\n )\n\n i, j = [np.nan, 5, 5, np.nan, 1, 2, np.nan], [1, 3, 3, 1, 2, 0, 1]\n tm.assert_frame_equal(df.reindex(i), df.iloc[j])\n\n df.index = df.index.astype("object")\n tm.assert_frame_equal(df.reindex(i), df.iloc[j], check_index_type=False)\n\n # GH10388\n df = DataFrame(\n {\n "other": ["a", "b", np.nan, "c"],\n "date": ["2015-03-22", np.nan, "2012-01-08", np.nan],\n "amount": [2, 3, 4, 5],\n }\n )\n\n df["date"] = pd.to_datetime(df.date)\n df["delta"] = (pd.to_datetime("2015-06-18") - df["date"]).shift(1)\n\n left = df.set_index(["delta", "other", "date"]).reset_index()\n right = df.reindex(columns=["delta", "other", "date", "amount"])\n tm.assert_frame_equal(left, right)\n\n def test_reindex_name_remains(self):\n s = Series(np.random.default_rng(2).random(10))\n df = DataFrame(s, index=np.arange(len(s)))\n i = Series(np.arange(10), name="iname")\n\n df = df.reindex(i)\n assert df.index.name == "iname"\n\n df = df.reindex(Index(np.arange(10), name="tmpname"))\n assert df.index.name == "tmpname"\n\n s = Series(np.random.default_rng(2).random(10))\n df = DataFrame(s.T, index=np.arange(len(s)))\n i = Series(np.arange(10), name="iname")\n df = df.reindex(columns=i)\n assert df.columns.name == "iname"\n\n def test_reindex_int(self, int_frame):\n smaller = int_frame.reindex(int_frame.index[::2])\n\n assert smaller["A"].dtype == np.int64\n\n bigger = smaller.reindex(int_frame.index)\n assert bigger["A"].dtype == np.float64\n\n smaller = int_frame.reindex(columns=["A", "B"])\n assert smaller["A"].dtype == np.int64\n\n def test_reindex_columns(self, float_frame):\n new_frame = float_frame.reindex(columns=["A", "B", "E"])\n\n tm.assert_series_equal(new_frame["B"], float_frame["B"])\n assert np.isnan(new_frame["E"]).all()\n assert "C" not in new_frame\n\n # Length zero\n new_frame = float_frame.reindex(columns=[])\n assert new_frame.empty\n\n def test_reindex_columns_method(self):\n # GH 14992, reindexing over columns ignored method\n df = DataFrame(\n data=[[11, 12, 13], [21, 22, 23], [31, 32, 33]],\n index=[1, 2, 4],\n columns=[1, 2, 4],\n dtype=float,\n )\n\n # default method\n result = df.reindex(columns=range(6))\n expected = DataFrame(\n data=[\n [np.nan, 11, 12, np.nan, 13, np.nan],\n [np.nan, 21, 22, np.nan, 23, np.nan],\n [np.nan, 31, 32, np.nan, 33, np.nan],\n ],\n index=[1, 2, 4],\n columns=range(6),\n dtype=float,\n )\n tm.assert_frame_equal(result, expected)\n\n # method='ffill'\n result = df.reindex(columns=range(6), method="ffill")\n expected = DataFrame(\n data=[\n [np.nan, 11, 12, 12, 13, 13],\n [np.nan, 21, 22, 22, 23, 23],\n [np.nan, 31, 32, 32, 33, 33],\n ],\n index=[1, 2, 4],\n columns=range(6),\n dtype=float,\n )\n tm.assert_frame_equal(result, expected)\n\n # method='bfill'\n result = df.reindex(columns=range(6), method="bfill")\n expected = DataFrame(\n data=[\n [11, 11, 12, 13, 13, np.nan],\n [21, 21, 22, 23, 23, np.nan],\n [31, 31, 32, 33, 33, np.nan],\n ],\n index=[1, 2, 4],\n columns=range(6),\n dtype=float,\n )\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_axes(self):\n # GH 3317, reindexing by both axes loses freq of the index\n df = DataFrame(\n np.ones((3, 3)),\n index=[datetime(2012, 1, 1), datetime(2012, 1, 2), datetime(2012, 1, 3)],\n columns=["a", "b", "c"],\n )\n time_freq = date_range("2012-01-01", "2012-01-03", freq="d")\n some_cols = ["a", "b"]\n\n index_freq = df.reindex(index=time_freq).index.freq\n both_freq = df.reindex(index=time_freq, columns=some_cols).index.freq\n seq_freq = df.reindex(index=time_freq).reindex(columns=some_cols).index.freq\n assert index_freq == both_freq\n assert index_freq == seq_freq\n\n def test_reindex_fill_value(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))\n\n # axis=0\n result = df.reindex(list(range(15)))\n assert np.isnan(result.values[-5:]).all()\n\n result = df.reindex(range(15), fill_value=0)\n expected = df.reindex(range(15)).fillna(0)\n tm.assert_frame_equal(result, expected)\n\n # axis=1\n result = df.reindex(columns=range(5), fill_value=0.0)\n expected = df.copy()\n expected[4] = 0.0\n tm.assert_frame_equal(result, expected)\n\n result = df.reindex(columns=range(5), fill_value=0)\n expected = df.copy()\n expected[4] = 0\n tm.assert_frame_equal(result, expected)\n\n result = df.reindex(columns=range(5), fill_value="foo")\n expected = df.copy()\n expected[4] = "foo"\n tm.assert_frame_equal(result, expected)\n\n # other dtypes\n df["foo"] = "foo"\n result = df.reindex(range(15), fill_value="0")\n expected = df.reindex(range(15)).fillna("0")\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_uint_dtypes_fill_value(self, any_unsigned_int_numpy_dtype):\n # GH#48184\n df = DataFrame({"a": [1, 2], "b": [1, 2]}, dtype=any_unsigned_int_numpy_dtype)\n result = df.reindex(columns=list("abcd"), index=[0, 1, 2, 3], fill_value=10)\n expected = DataFrame(\n {"a": [1, 2, 10, 10], "b": [1, 2, 10, 10], "c": 10, "d": 10},\n dtype=any_unsigned_int_numpy_dtype,\n )\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_single_column_ea_index_and_columns(self, any_numeric_ea_dtype):\n # GH#48190\n df = DataFrame({"a": [1, 2]}, dtype=any_numeric_ea_dtype)\n result = df.reindex(columns=list("ab"), index=[0, 1, 2], fill_value=10)\n expected = DataFrame(\n {"a": Series([1, 2, 10], dtype=any_numeric_ea_dtype), "b": 10}\n )\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_dups(self):\n # GH4746, reindex on duplicate index error messages\n arr = np.random.default_rng(2).standard_normal(10)\n df = DataFrame(arr, index=[1, 2, 3, 4, 5, 1, 2, 3, 4, 5])\n\n # set index is ok\n result = df.copy()\n result.index = list(range(len(df)))\n expected = DataFrame(arr, index=list(range(len(df))))\n tm.assert_frame_equal(result, expected)\n\n # reindex fails\n msg = "cannot reindex on an axis with duplicate labels"\n with pytest.raises(ValueError, match=msg):\n df.reindex(index=list(range(len(df))))\n\n def test_reindex_with_duplicate_columns(self):\n # reindex is invalid!\n df = DataFrame(\n [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"]\n )\n msg = "cannot reindex on an axis with duplicate labels"\n with pytest.raises(ValueError, match=msg):\n df.reindex(columns=["bar"])\n with pytest.raises(ValueError, match=msg):\n df.reindex(columns=["bar", "foo"])\n\n def test_reindex_axis_style(self):\n # https://github.com/pandas-dev/pandas/issues/12392\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})\n expected = DataFrame(\n {"A": [1, 2, np.nan], "B": [4, 5, np.nan]}, index=[0, 1, 3]\n )\n result = df.reindex([0, 1, 3])\n tm.assert_frame_equal(result, expected)\n\n result = df.reindex([0, 1, 3], axis=0)\n tm.assert_frame_equal(result, expected)\n\n result = df.reindex([0, 1, 3], axis="index")\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_positional_raises(self):\n # https://github.com/pandas-dev/pandas/issues/12392\n # Enforced in 2.0\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})\n msg = r"reindex\(\) takes from 1 to 2 positional arguments but 3 were given"\n with pytest.raises(TypeError, match=msg):\n df.reindex([0, 1], ["A", "B", "C"])\n\n def test_reindex_axis_style_raises(self):\n # https://github.com/pandas-dev/pandas/issues/12392\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})\n with pytest.raises(TypeError, match="Cannot specify both 'axis'"):\n df.reindex([0, 1], columns=["A"], axis=1)\n\n with pytest.raises(TypeError, match="Cannot specify both 'axis'"):\n df.reindex([0, 1], columns=["A"], axis="index")\n\n with pytest.raises(TypeError, match="Cannot specify both 'axis'"):\n df.reindex(index=[0, 1], axis="index")\n\n with pytest.raises(TypeError, match="Cannot specify both 'axis'"):\n df.reindex(index=[0, 1], axis="columns")\n\n with pytest.raises(TypeError, match="Cannot specify both 'axis'"):\n df.reindex(columns=[0, 1], axis="columns")\n\n with pytest.raises(TypeError, match="Cannot specify both 'axis'"):\n df.reindex(index=[0, 1], columns=[0, 1], axis="columns")\n\n with pytest.raises(TypeError, match="Cannot specify all"):\n df.reindex(labels=[0, 1], index=[0], columns=["A"])\n\n # Mixing styles\n with pytest.raises(TypeError, match="Cannot specify both 'axis'"):\n df.reindex(index=[0, 1], axis="index")\n\n with pytest.raises(TypeError, match="Cannot specify both 'axis'"):\n df.reindex(index=[0, 1], axis="columns")\n\n # Duplicates\n with pytest.raises(TypeError, match="multiple values"):\n df.reindex([0, 1], labels=[0, 1])\n\n def test_reindex_single_named_indexer(self):\n # https://github.com/pandas-dev/pandas/issues/12392\n df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]})\n result = df.reindex([0, 1], columns=["A"])\n expected = DataFrame({"A": [1, 2]})\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_api_equivalence(self):\n # https://github.com/pandas-dev/pandas/issues/12392\n # equivalence of the labels/axis and index/columns API's\n df = DataFrame(\n [[1, 2, 3], [3, 4, 5], [5, 6, 7]],\n index=["a", "b", "c"],\n columns=["d", "e", "f"],\n )\n\n res1 = df.reindex(["b", "a"])\n res2 = df.reindex(index=["b", "a"])\n res3 = df.reindex(labels=["b", "a"])\n res4 = df.reindex(labels=["b", "a"], axis=0)\n res5 = df.reindex(["b", "a"], axis=0)\n for res in [res2, res3, res4, res5]:\n tm.assert_frame_equal(res1, res)\n\n res1 = df.reindex(columns=["e", "d"])\n res2 = df.reindex(["e", "d"], axis=1)\n res3 = df.reindex(labels=["e", "d"], axis=1)\n for res in [res2, res3]:\n tm.assert_frame_equal(res1, res)\n\n res1 = df.reindex(index=["b", "a"], columns=["e", "d"])\n res2 = df.reindex(columns=["e", "d"], index=["b", "a"])\n res3 = df.reindex(labels=["b", "a"], axis=0).reindex(labels=["e", "d"], axis=1)\n for res in [res2, res3]:\n tm.assert_frame_equal(res1, res)\n\n def test_reindex_boolean(self):\n frame = DataFrame(\n np.ones((10, 2), dtype=bool), index=np.arange(0, 20, 2), columns=[0, 2]\n )\n\n reindexed = frame.reindex(np.arange(10))\n assert reindexed.values.dtype == np.object_\n assert isna(reindexed[0][1])\n\n reindexed = frame.reindex(columns=range(3))\n assert reindexed.values.dtype == np.object_\n assert isna(reindexed[1]).all()\n\n def test_reindex_objects(self, float_string_frame):\n reindexed = float_string_frame.reindex(columns=["foo", "A", "B"])\n assert "foo" in reindexed\n\n reindexed = float_string_frame.reindex(columns=["A", "B"])\n assert "foo" not in reindexed\n\n def test_reindex_corner(self, int_frame):\n index = Index(["a", "b", "c"])\n dm = DataFrame({}).reindex(index=[1, 2, 3])\n reindexed = dm.reindex(columns=index)\n tm.assert_index_equal(reindexed.columns, index)\n\n # ints are weird\n smaller = int_frame.reindex(columns=["A", "B", "E"])\n assert smaller["E"].dtype == np.float64\n\n def test_reindex_with_nans(self):\n df = DataFrame(\n [[1, 2], [3, 4], [np.nan, np.nan], [7, 8], [9, 10]],\n columns=["a", "b"],\n index=[100.0, 101.0, np.nan, 102.0, 103.0],\n )\n\n result = df.reindex(index=[101.0, 102.0, 103.0])\n expected = df.iloc[[1, 3, 4]]\n tm.assert_frame_equal(result, expected)\n\n result = df.reindex(index=[103.0])\n expected = df.iloc[[4]]\n tm.assert_frame_equal(result, expected)\n\n result = df.reindex(index=[101.0])\n expected = df.iloc[[1]]\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_multi(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)))\n\n result = df.reindex(index=range(4), columns=range(4))\n expected = df.reindex(list(range(4))).reindex(columns=range(4))\n\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame(np.random.default_rng(2).integers(0, 10, (3, 3)))\n\n result = df.reindex(index=range(4), columns=range(4))\n expected = df.reindex(list(range(4))).reindex(columns=range(4))\n\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame(np.random.default_rng(2).integers(0, 10, (3, 3)))\n\n result = df.reindex(index=range(2), columns=range(2))\n expected = df.reindex(range(2)).reindex(columns=range(2))\n\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)) + 1j,\n columns=["a", "b", "c"],\n )\n\n result = df.reindex(index=[0, 1], columns=["a", "b"])\n expected = df.reindex([0, 1]).reindex(columns=["a", "b"])\n\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_multi_categorical_time(self):\n # https://github.com/pandas-dev/pandas/issues/21390\n midx = MultiIndex.from_product(\n [\n Categorical(["a", "b", "c"]),\n Categorical(date_range("2012-01-01", periods=3, freq="h")),\n ]\n )\n df = DataFrame({"a": range(len(midx))}, index=midx)\n df2 = df.iloc[[0, 1, 2, 3, 4, 5, 6, 8]]\n\n result = df2.reindex(midx)\n expected = DataFrame({"a": [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx)\n tm.assert_frame_equal(result, expected)\n\n def test_reindex_with_categoricalindex(self):\n df = DataFrame(\n {\n "A": np.arange(3, dtype="int64"),\n },\n index=CategoricalIndex(\n list("abc"), dtype=CategoricalDtype(list("cabe")), name="B"\n ),\n )\n\n # reindexing\n # convert to a regular index\n result = df.reindex(["a", "b", "e"])\n expected = DataFrame({"A": [0, 1, np.nan], "B": Series(list("abe"))}).set_index(\n "B"\n )\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n result = df.reindex(["a", "b"])\n expected = DataFrame({"A": [0, 1], "B": Series(list("ab"))}).set_index("B")\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n result = df.reindex(["e"])\n expected = DataFrame({"A": [np.nan], "B": Series(["e"])}).set_index("B")\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n result = df.reindex(["d"])\n expected = DataFrame({"A": [np.nan], "B": Series(["d"])}).set_index("B")\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n # since we are actually reindexing with a Categorical\n # then return a Categorical\n cats = list("cabe")\n\n result = df.reindex(Categorical(["a", "e"], categories=cats))\n expected = DataFrame(\n {"A": [0, np.nan], "B": Series(list("ae")).astype(CategoricalDtype(cats))}\n ).set_index("B")\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n result = df.reindex(Categorical(["a"], categories=cats))\n expected = DataFrame(\n {"A": [0], "B": Series(list("a")).astype(CategoricalDtype(cats))}\n ).set_index("B")\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n result = df.reindex(["a", "b", "e"])\n expected = DataFrame({"A": [0, 1, np.nan], "B": Series(list("abe"))}).set_index(\n "B"\n )\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n result = df.reindex(["a", "b"])\n expected = DataFrame({"A": [0, 1], "B": Series(list("ab"))}).set_index("B")\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n result = df.reindex(["e"])\n expected = DataFrame({"A": [np.nan], "B": Series(["e"])}).set_index("B")\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n # give back the type of categorical that we received\n result = df.reindex(Categorical(["a", "e"], categories=cats, ordered=True))\n expected = DataFrame(\n {\n "A": [0, np.nan],\n "B": Series(list("ae")).astype(CategoricalDtype(cats, ordered=True)),\n }\n ).set_index("B")\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n result = df.reindex(Categorical(["a", "d"], categories=["a", "d"]))\n expected = DataFrame(\n {\n "A": [0, np.nan],\n "B": Series(list("ad")).astype(CategoricalDtype(["a", "d"])),\n }\n ).set_index("B")\n tm.assert_frame_equal(result, expected, check_index_type=True)\n\n df2 = DataFrame(\n {\n "A": np.arange(6, dtype="int64"),\n },\n index=CategoricalIndex(\n list("aabbca"), dtype=CategoricalDtype(list("cabe")), name="B"\n ),\n )\n # passed duplicate indexers are not allowed\n msg = "cannot reindex on an axis with duplicate labels"\n with pytest.raises(ValueError, match=msg):\n df2.reindex(["a", "b"])\n\n # args NotImplemented ATM\n msg = r"argument {} is not implemented for CategoricalIndex\.reindex"\n with pytest.raises(NotImplementedError, match=msg.format("method")):\n df.reindex(["a"], method="ffill")\n with pytest.raises(NotImplementedError, match=msg.format("level")):\n df.reindex(["a"], level=1)\n with pytest.raises(NotImplementedError, match=msg.format("limit")):\n df.reindex(["a"], limit=2)\n\n def test_reindex_signature(self):\n sig = inspect.signature(DataFrame.reindex)\n parameters = set(sig.parameters)\n assert parameters == {\n "self",\n "labels",\n "index",\n "columns",\n "axis",\n "limit",\n "copy",\n "level",\n "method",\n "fill_value",\n "tolerance",\n }\n\n def test_reindex_multiindex_ffill_added_rows(self):\n # GH#23693\n # reindex added rows with nan values even when fill method was specified\n mi = MultiIndex.from_tuples([("a", "b"), ("d", "e")])\n df = DataFrame([[0, 7], [3, 4]], index=mi, columns=["x", "y"])\n mi2 = MultiIndex.from_tuples([("a", "b"), ("d", "e"), ("h", "i")])\n result = df.reindex(mi2, axis=0, method="ffill")\n expected = DataFrame([[0, 7], [3, 4], [3, 4]], index=mi2, columns=["x", "y"])\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "kwargs",\n [\n {"method": "pad", "tolerance": timedelta(seconds=9)},\n {"method": "backfill", "tolerance": timedelta(seconds=9)},\n {"method": "nearest"},\n {"method": None},\n ],\n )\n def test_reindex_empty_frame(self, kwargs):\n # GH#27315\n idx = date_range(start="2020", freq="30s", periods=3)\n df = DataFrame([], index=Index([], name="time"), columns=["a"])\n result = df.reindex(idx, **kwargs)\n expected = DataFrame({"a": [np.nan] * 3}, index=idx, dtype=object)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "src_idx",\n [\n Index([]),\n CategoricalIndex([]),\n ],\n )\n @pytest.mark.parametrize(\n "cat_idx",\n [\n # No duplicates\n Index([]),\n CategoricalIndex([]),\n Index(["A", "B"]),\n CategoricalIndex(["A", "B"]),\n # Duplicates: GH#38906\n Index(["A", "A"]),\n CategoricalIndex(["A", "A"]),\n ],\n )\n def test_reindex_empty(self, src_idx, cat_idx):\n df = DataFrame(columns=src_idx, index=["K"], dtype="f8")\n\n result = df.reindex(columns=cat_idx)\n expected = DataFrame(index=["K"], columns=cat_idx, dtype="f8")\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]"])\n def test_reindex_datetimelike_to_object(self, dtype):\n # GH#39755 dont cast dt64/td64 to ints\n mi = MultiIndex.from_product([list("ABCDE"), range(2)])\n\n dti = date_range("2016-01-01", periods=10)\n fv = np.timedelta64("NaT", "ns")\n if dtype == "m8[ns]":\n dti = dti - dti[0]\n fv = np.datetime64("NaT", "ns")\n\n ser = Series(dti, index=mi)\n ser[::3] = pd.NaT\n\n df = ser.unstack()\n\n index = df.index.append(Index([1]))\n columns = df.columns.append(Index(["foo"]))\n\n res = df.reindex(index=index, columns=columns, fill_value=fv)\n\n expected = DataFrame(\n {\n 0: df[0].tolist() + [fv],\n 1: df[1].tolist() + [fv],\n "foo": np.array(["NaT"] * 6, dtype=fv.dtype),\n },\n index=index,\n )\n assert (res.dtypes[[0, 1]] == object).all()\n assert res.iloc[0, 0] is pd.NaT\n assert res.iloc[-1, 0] is fv\n assert res.iloc[-1, 1] is fv\n tm.assert_frame_equal(res, expected)\n\n @pytest.mark.parametrize(\n "index_df,index_res,index_exp",\n [\n (\n CategoricalIndex([], categories=["A"]),\n Index(["A"]),\n Index(["A"]),\n ),\n (\n CategoricalIndex([], categories=["A"]),\n Index(["B"]),\n Index(["B"]),\n ),\n (\n CategoricalIndex([], categories=["A"]),\n CategoricalIndex(["A"]),\n CategoricalIndex(["A"]),\n ),\n (\n CategoricalIndex([], categories=["A"]),\n CategoricalIndex(["B"]),\n CategoricalIndex(["B"]),\n ),\n ],\n )\n def test_reindex_not_category(self, index_df, index_res, index_exp):\n # GH#28690\n df = DataFrame(index=index_df)\n result = df.reindex(index=index_res)\n expected = DataFrame(index=index_exp)\n tm.assert_frame_equal(result, expected)\n\n def test_invalid_method(self):\n df = DataFrame({"A": [1, np.nan, 2]})\n\n msg = "Invalid fill method"\n with pytest.raises(ValueError, match=msg):\n df.reindex([1, 0, 2], method="asfreq")\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_reindex.py
test_reindex.py
Python
48,343
0.95
0.062547
0.102722
react-lib
29
2024-06-07T08:34:52.359316
MIT
true
42da99029726ef58c9986c4b70092d80
import numpy as np\nimport pytest\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\nclass TestDataFrameReindexLike:\n def test_reindex_like(self, float_frame):\n other = float_frame.reindex(index=float_frame.index[:10], columns=["C", "B"])\n\n tm.assert_frame_equal(other, float_frame.reindex_like(other))\n\n @pytest.mark.parametrize(\n "method,expected_values",\n [\n ("nearest", [0, 1, 1, 2]),\n ("pad", [np.nan, 0, 1, 1]),\n ("backfill", [0, 1, 2, 2]),\n ],\n )\n def test_reindex_like_methods(self, method, expected_values):\n df = DataFrame({"x": list(range(5))})\n\n result = df.reindex_like(df, method=method, tolerance=0)\n tm.assert_frame_equal(df, result)\n result = df.reindex_like(df, method=method, tolerance=[0, 0, 0, 0])\n tm.assert_frame_equal(df, result)\n\n def test_reindex_like_subclass(self):\n # https://github.com/pandas-dev/pandas/issues/31925\n class MyDataFrame(DataFrame):\n pass\n\n expected = DataFrame()\n df = MyDataFrame()\n result = df.reindex_like(expected)\n\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_reindex_like.py
test_reindex_like.py
Python
1,187
0.95
0.128205
0.033333
react-lib
799
2024-11-01T11:22:40.407536
Apache-2.0
true
d27fea27cca7ea17e3b79fb37a6ae33f
from collections import ChainMap\nimport inspect\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n merge,\n)\nimport pandas._testing as tm\n\n\nclass TestRename:\n def test_rename_signature(self):\n sig = inspect.signature(DataFrame.rename)\n parameters = set(sig.parameters)\n assert parameters == {\n "self",\n "mapper",\n "index",\n "columns",\n "axis",\n "inplace",\n "copy",\n "level",\n "errors",\n }\n\n def test_rename_mi(self, frame_or_series):\n obj = frame_or_series(\n [11, 21, 31],\n index=MultiIndex.from_tuples([("A", x) for x in ["a", "B", "c"]]),\n )\n obj.rename(str.lower)\n\n def test_rename(self, float_frame):\n mapping = {"A": "a", "B": "b", "C": "c", "D": "d"}\n\n renamed = float_frame.rename(columns=mapping)\n renamed2 = float_frame.rename(columns=str.lower)\n\n tm.assert_frame_equal(renamed, renamed2)\n tm.assert_frame_equal(\n renamed2.rename(columns=str.upper), float_frame, check_names=False\n )\n\n # index\n data = {"A": {"foo": 0, "bar": 1}}\n\n df = DataFrame(data)\n renamed = df.rename(index={"foo": "bar", "bar": "foo"})\n tm.assert_index_equal(renamed.index, Index(["bar", "foo"]))\n\n renamed = df.rename(index=str.upper)\n tm.assert_index_equal(renamed.index, Index(["FOO", "BAR"]))\n\n # have to pass something\n with pytest.raises(TypeError, match="must pass an index to rename"):\n float_frame.rename()\n\n # partial columns\n renamed = float_frame.rename(columns={"C": "foo", "D": "bar"})\n tm.assert_index_equal(renamed.columns, Index(["A", "B", "foo", "bar"]))\n\n # other axis\n renamed = float_frame.T.rename(index={"C": "foo", "D": "bar"})\n tm.assert_index_equal(renamed.index, Index(["A", "B", "foo", "bar"]))\n\n # index with name\n index = Index(["foo", "bar"], name="name")\n renamer = DataFrame(data, index=index)\n renamed = renamer.rename(index={"foo": "bar", "bar": "foo"})\n tm.assert_index_equal(renamed.index, Index(["bar", "foo"], name="name"))\n assert renamed.index.name == renamer.index.name\n\n @pytest.mark.parametrize(\n "args,kwargs",\n [\n ((ChainMap({"A": "a"}, {"B": "b"}),), {"axis": "columns"}),\n ((), {"columns": ChainMap({"A": "a"}, {"B": "b"})}),\n ],\n )\n def test_rename_chainmap(self, args, kwargs):\n # see gh-23859\n colAData = range(1, 11)\n colBdata = np.random.default_rng(2).standard_normal(10)\n\n df = DataFrame({"A": colAData, "B": colBdata})\n result = df.rename(*args, **kwargs)\n\n expected = DataFrame({"a": colAData, "b": colBdata})\n tm.assert_frame_equal(result, expected)\n\n def test_rename_multiindex(self):\n tuples_index = [("foo1", "bar1"), ("foo2", "bar2")]\n tuples_columns = [("fizz1", "buzz1"), ("fizz2", "buzz2")]\n index = MultiIndex.from_tuples(tuples_index, names=["foo", "bar"])\n columns = MultiIndex.from_tuples(tuples_columns, names=["fizz", "buzz"])\n df = DataFrame([(0, 0), (1, 1)], index=index, columns=columns)\n\n #\n # without specifying level -> across all levels\n\n renamed = df.rename(\n index={"foo1": "foo3", "bar2": "bar3"},\n columns={"fizz1": "fizz3", "buzz2": "buzz3"},\n )\n new_index = MultiIndex.from_tuples(\n [("foo3", "bar1"), ("foo2", "bar3")], names=["foo", "bar"]\n )\n new_columns = MultiIndex.from_tuples(\n [("fizz3", "buzz1"), ("fizz2", "buzz3")], names=["fizz", "buzz"]\n )\n tm.assert_index_equal(renamed.index, new_index)\n tm.assert_index_equal(renamed.columns, new_columns)\n assert renamed.index.names == df.index.names\n assert renamed.columns.names == df.columns.names\n\n #\n # with specifying a level (GH13766)\n\n # dict\n new_columns = MultiIndex.from_tuples(\n [("fizz3", "buzz1"), ("fizz2", "buzz2")], names=["fizz", "buzz"]\n )\n renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level=0)\n tm.assert_index_equal(renamed.columns, new_columns)\n renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level="fizz")\n tm.assert_index_equal(renamed.columns, new_columns)\n\n new_columns = MultiIndex.from_tuples(\n [("fizz1", "buzz1"), ("fizz2", "buzz3")], names=["fizz", "buzz"]\n )\n renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level=1)\n tm.assert_index_equal(renamed.columns, new_columns)\n renamed = df.rename(columns={"fizz1": "fizz3", "buzz2": "buzz3"}, level="buzz")\n tm.assert_index_equal(renamed.columns, new_columns)\n\n # function\n func = str.upper\n new_columns = MultiIndex.from_tuples(\n [("FIZZ1", "buzz1"), ("FIZZ2", "buzz2")], names=["fizz", "buzz"]\n )\n renamed = df.rename(columns=func, level=0)\n tm.assert_index_equal(renamed.columns, new_columns)\n renamed = df.rename(columns=func, level="fizz")\n tm.assert_index_equal(renamed.columns, new_columns)\n\n new_columns = MultiIndex.from_tuples(\n [("fizz1", "BUZZ1"), ("fizz2", "BUZZ2")], names=["fizz", "buzz"]\n )\n renamed = df.rename(columns=func, level=1)\n tm.assert_index_equal(renamed.columns, new_columns)\n renamed = df.rename(columns=func, level="buzz")\n tm.assert_index_equal(renamed.columns, new_columns)\n\n # index\n new_index = MultiIndex.from_tuples(\n [("foo3", "bar1"), ("foo2", "bar2")], names=["foo", "bar"]\n )\n renamed = df.rename(index={"foo1": "foo3", "bar2": "bar3"}, level=0)\n tm.assert_index_equal(renamed.index, new_index)\n\n def test_rename_nocopy(self, float_frame, using_copy_on_write, warn_copy_on_write):\n renamed = float_frame.rename(columns={"C": "foo"}, copy=False)\n\n assert np.shares_memory(renamed["foo"]._values, float_frame["C"]._values)\n\n with tm.assert_cow_warning(warn_copy_on_write):\n renamed.loc[:, "foo"] = 1.0\n if using_copy_on_write:\n assert not (float_frame["C"] == 1.0).all()\n else:\n assert (float_frame["C"] == 1.0).all()\n\n def test_rename_inplace(self, float_frame):\n float_frame.rename(columns={"C": "foo"})\n assert "C" in float_frame\n assert "foo" not in float_frame\n\n c_values = float_frame["C"]\n float_frame = float_frame.copy()\n return_value = float_frame.rename(columns={"C": "foo"}, inplace=True)\n assert return_value is None\n\n assert "C" not in float_frame\n assert "foo" in float_frame\n # GH 44153\n # Used to be id(float_frame["foo"]) != c_id, but flaky in the CI\n assert float_frame["foo"] is not c_values\n\n def test_rename_bug(self):\n # GH 5344\n # rename set ref_locs, and set_index was not resetting\n df = DataFrame({0: ["foo", "bar"], 1: ["bah", "bas"], 2: [1, 2]})\n df = df.rename(columns={0: "a"})\n df = df.rename(columns={1: "b"})\n df = df.set_index(["a", "b"])\n df.columns = ["2001-01-01"]\n expected = DataFrame(\n [[1], [2]],\n index=MultiIndex.from_tuples(\n [("foo", "bah"), ("bar", "bas")], names=["a", "b"]\n ),\n columns=["2001-01-01"],\n )\n tm.assert_frame_equal(df, expected)\n\n def test_rename_bug2(self):\n # GH 19497\n # rename was changing Index to MultiIndex if Index contained tuples\n\n df = DataFrame(data=np.arange(3), index=[(0, 0), (1, 1), (2, 2)], columns=["a"])\n df = df.rename({(1, 1): (5, 4)}, axis="index")\n expected = DataFrame(\n data=np.arange(3), index=[(0, 0), (5, 4), (2, 2)], columns=["a"]\n )\n tm.assert_frame_equal(df, expected)\n\n def test_rename_errors_raises(self):\n df = DataFrame(columns=["A", "B", "C", "D"])\n with pytest.raises(KeyError, match="'E'] not found in axis"):\n df.rename(columns={"A": "a", "E": "e"}, errors="raise")\n\n @pytest.mark.parametrize(\n "mapper, errors, expected_columns",\n [\n ({"A": "a", "E": "e"}, "ignore", ["a", "B", "C", "D"]),\n ({"A": "a"}, "raise", ["a", "B", "C", "D"]),\n (str.lower, "raise", ["a", "b", "c", "d"]),\n ],\n )\n def test_rename_errors(self, mapper, errors, expected_columns):\n # GH 13473\n # rename now works with errors parameter\n df = DataFrame(columns=["A", "B", "C", "D"])\n result = df.rename(columns=mapper, errors=errors)\n expected = DataFrame(columns=expected_columns)\n tm.assert_frame_equal(result, expected)\n\n def test_rename_objects(self, float_string_frame):\n renamed = float_string_frame.rename(columns=str.upper)\n\n assert "FOO" in renamed\n assert "foo" not in renamed\n\n def test_rename_axis_style(self):\n # https://github.com/pandas-dev/pandas/issues/12392\n df = DataFrame({"A": [1, 2], "B": [1, 2]}, index=["X", "Y"])\n expected = DataFrame({"a": [1, 2], "b": [1, 2]}, index=["X", "Y"])\n\n result = df.rename(str.lower, axis=1)\n tm.assert_frame_equal(result, expected)\n\n result = df.rename(str.lower, axis="columns")\n tm.assert_frame_equal(result, expected)\n\n result = df.rename({"A": "a", "B": "b"}, axis=1)\n tm.assert_frame_equal(result, expected)\n\n result = df.rename({"A": "a", "B": "b"}, axis="columns")\n tm.assert_frame_equal(result, expected)\n\n # Index\n expected = DataFrame({"A": [1, 2], "B": [1, 2]}, index=["x", "y"])\n result = df.rename(str.lower, axis=0)\n tm.assert_frame_equal(result, expected)\n\n result = df.rename(str.lower, axis="index")\n tm.assert_frame_equal(result, expected)\n\n result = df.rename({"X": "x", "Y": "y"}, axis=0)\n tm.assert_frame_equal(result, expected)\n\n result = df.rename({"X": "x", "Y": "y"}, axis="index")\n tm.assert_frame_equal(result, expected)\n\n result = df.rename(mapper=str.lower, axis="index")\n tm.assert_frame_equal(result, expected)\n\n def test_rename_mapper_multi(self):\n df = DataFrame({"A": ["a", "b"], "B": ["c", "d"], "C": [1, 2]}).set_index(\n ["A", "B"]\n )\n result = df.rename(str.upper)\n expected = df.rename(index=str.upper)\n tm.assert_frame_equal(result, expected)\n\n def test_rename_positional_named(self):\n # https://github.com/pandas-dev/pandas/issues/12392\n df = DataFrame({"a": [1, 2], "b": [1, 2]}, index=["X", "Y"])\n result = df.rename(index=str.lower, columns=str.upper)\n expected = DataFrame({"A": [1, 2], "B": [1, 2]}, index=["x", "y"])\n tm.assert_frame_equal(result, expected)\n\n def test_rename_axis_style_raises(self):\n # see gh-12392\n df = DataFrame({"A": [1, 2], "B": [1, 2]}, index=["0", "1"])\n\n # Named target and axis\n over_spec_msg = "Cannot specify both 'axis' and any of 'index' or 'columns'"\n with pytest.raises(TypeError, match=over_spec_msg):\n df.rename(index=str.lower, axis=1)\n\n with pytest.raises(TypeError, match=over_spec_msg):\n df.rename(index=str.lower, axis="columns")\n\n with pytest.raises(TypeError, match=over_spec_msg):\n df.rename(columns=str.lower, axis="columns")\n\n with pytest.raises(TypeError, match=over_spec_msg):\n df.rename(index=str.lower, axis=0)\n\n # Multiple targets and axis\n with pytest.raises(TypeError, match=over_spec_msg):\n df.rename(str.lower, index=str.lower, axis="columns")\n\n # Too many targets\n over_spec_msg = "Cannot specify both 'mapper' and any of 'index' or 'columns'"\n with pytest.raises(TypeError, match=over_spec_msg):\n df.rename(str.lower, index=str.lower, columns=str.lower)\n\n # Duplicates\n with pytest.raises(TypeError, match="multiple values"):\n df.rename(id, mapper=id)\n\n def test_rename_positional_raises(self):\n # GH 29136\n df = DataFrame(columns=["A", "B"])\n msg = r"rename\(\) takes from 1 to 2 positional arguments"\n\n with pytest.raises(TypeError, match=msg):\n df.rename(None, str.lower)\n\n def test_rename_no_mappings_raises(self):\n # GH 29136\n df = DataFrame([[1]])\n msg = "must pass an index to rename"\n with pytest.raises(TypeError, match=msg):\n df.rename()\n\n with pytest.raises(TypeError, match=msg):\n df.rename(None, index=None)\n\n with pytest.raises(TypeError, match=msg):\n df.rename(None, columns=None)\n\n with pytest.raises(TypeError, match=msg):\n df.rename(None, columns=None, index=None)\n\n def test_rename_mapper_and_positional_arguments_raises(self):\n # GH 29136\n df = DataFrame([[1]])\n msg = "Cannot specify both 'mapper' and any of 'index' or 'columns'"\n with pytest.raises(TypeError, match=msg):\n df.rename({}, index={})\n\n with pytest.raises(TypeError, match=msg):\n df.rename({}, columns={})\n\n with pytest.raises(TypeError, match=msg):\n df.rename({}, columns={}, index={})\n\n def test_rename_with_duplicate_columns(self):\n # GH#4403\n df4 = DataFrame(\n {"RT": [0.0454], "TClose": [22.02], "TExg": [0.0422]},\n index=MultiIndex.from_tuples(\n [(600809, 20130331)], names=["STK_ID", "RPT_Date"]\n ),\n )\n\n df5 = DataFrame(\n {\n "RPT_Date": [20120930, 20121231, 20130331],\n "STK_ID": [600809] * 3,\n "STK_Name": ["饡驦", "饡驦", "饡驦"],\n "TClose": [38.05, 41.66, 30.01],\n },\n index=MultiIndex.from_tuples(\n [(600809, 20120930), (600809, 20121231), (600809, 20130331)],\n names=["STK_ID", "RPT_Date"],\n ),\n )\n # TODO: can we construct this without merge?\n k = merge(df4, df5, how="inner", left_index=True, right_index=True)\n result = k.rename(columns={"TClose_x": "TClose", "TClose_y": "QT_Close"})\n\n expected = DataFrame(\n [[0.0454, 22.02, 0.0422, 20130331, 600809, "饡驦", 30.01]],\n columns=[\n "RT",\n "TClose",\n "TExg",\n "RPT_Date",\n "STK_ID",\n "STK_Name",\n "QT_Close",\n ],\n ).set_index(["STK_ID", "RPT_Date"], drop=False)\n tm.assert_frame_equal(result, expected)\n\n def test_rename_boolean_index(self):\n df = DataFrame(np.arange(15).reshape(3, 5), columns=[False, True, 2, 3, 4])\n mapper = {0: "foo", 1: "bar", 2: "bah"}\n res = df.rename(index=mapper)\n exp = DataFrame(\n np.arange(15).reshape(3, 5),\n columns=[False, True, 2, 3, 4],\n index=["foo", "bar", "bah"],\n )\n tm.assert_frame_equal(res, exp)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_rename.py
test_rename.py
Python
15,354
0.95
0.062651
0.099415
vue-tools
316
2024-06-24T16:03:54.615324
Apache-2.0
true
7dd4e6744a6143a6765f83d11c736c55
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameRenameAxis:\n def test_rename_axis_inplace(self, float_frame):\n # GH#15704\n expected = float_frame.rename_axis("foo")\n result = float_frame.copy()\n return_value = no_return = result.rename_axis("foo", inplace=True)\n assert return_value is None\n\n assert no_return is None\n tm.assert_frame_equal(result, expected)\n\n expected = float_frame.rename_axis("bar", axis=1)\n result = float_frame.copy()\n return_value = no_return = result.rename_axis("bar", axis=1, inplace=True)\n assert return_value is None\n\n assert no_return is None\n tm.assert_frame_equal(result, expected)\n\n def test_rename_axis_raises(self):\n # GH#17833\n df = DataFrame({"A": [1, 2], "B": [1, 2]})\n with pytest.raises(ValueError, match="Use `.rename`"):\n df.rename_axis(id, axis=0)\n\n with pytest.raises(ValueError, match="Use `.rename`"):\n df.rename_axis({0: 10, 1: 20}, axis=0)\n\n with pytest.raises(ValueError, match="Use `.rename`"):\n df.rename_axis(id, axis=1)\n\n with pytest.raises(ValueError, match="Use `.rename`"):\n df["A"].rename_axis(id)\n\n def test_rename_axis_mapper(self):\n # GH#19978\n mi = MultiIndex.from_product([["a", "b", "c"], [1, 2]], names=["ll", "nn"])\n df = DataFrame(\n {"x": list(range(len(mi))), "y": [i * 10 for i in range(len(mi))]}, index=mi\n )\n\n # Test for rename of the Index object of columns\n result = df.rename_axis("cols", axis=1)\n tm.assert_index_equal(result.columns, Index(["x", "y"], name="cols"))\n\n # Test for rename of the Index object of columns using dict\n result = result.rename_axis(columns={"cols": "new"}, axis=1)\n tm.assert_index_equal(result.columns, Index(["x", "y"], name="new"))\n\n # Test for renaming index using dict\n result = df.rename_axis(index={"ll": "foo"})\n assert result.index.names == ["foo", "nn"]\n\n # Test for renaming index using a function\n result = df.rename_axis(index=str.upper, axis=0)\n assert result.index.names == ["LL", "NN"]\n\n # Test for renaming index providing complete list\n result = df.rename_axis(index=["foo", "goo"])\n assert result.index.names == ["foo", "goo"]\n\n # Test for changing index and columns at same time\n sdf = df.reset_index().set_index("nn").drop(columns=["ll", "y"])\n result = sdf.rename_axis(index="foo", columns="meh")\n assert result.index.name == "foo"\n assert result.columns.name == "meh"\n\n # Test different error cases\n with pytest.raises(TypeError, match="Must pass"):\n df.rename_axis(index="wrong")\n\n with pytest.raises(ValueError, match="Length of names"):\n df.rename_axis(index=["wrong"])\n\n with pytest.raises(TypeError, match="bogus"):\n df.rename_axis(bogus=None)\n\n @pytest.mark.parametrize(\n "kwargs, rename_index, rename_columns",\n [\n ({"mapper": None, "axis": 0}, True, False),\n ({"mapper": None, "axis": 1}, False, True),\n ({"index": None}, True, False),\n ({"columns": None}, False, True),\n ({"index": None, "columns": None}, True, True),\n ({}, False, False),\n ],\n )\n def test_rename_axis_none(self, kwargs, rename_index, rename_columns):\n # GH 25034\n index = Index(list("abc"), name="foo")\n columns = Index(["col1", "col2"], name="bar")\n data = np.arange(6).reshape(3, 2)\n df = DataFrame(data, index, columns)\n\n result = df.rename_axis(**kwargs)\n expected_index = index.rename(None) if rename_index else index\n expected_columns = columns.rename(None) if rename_columns else columns\n expected = DataFrame(data, expected_index, expected_columns)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_rename_axis.py
test_rename_axis.py
Python
4,091
0.95
0.135135
0.123596
node-utils
180
2025-01-09T00:04:11.079219
MIT
true
e58b5b5d05e8975dd09b995da2209b22
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n MultiIndex,\n)\nimport pandas._testing as tm\n\n\nclass TestReorderLevels:\n def test_reorder_levels(self, frame_or_series):\n index = MultiIndex(\n levels=[["bar"], ["one", "two", "three"], [0, 1]],\n codes=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]],\n names=["L0", "L1", "L2"],\n )\n df = DataFrame({"A": np.arange(6), "B": np.arange(6)}, index=index)\n obj = tm.get_obj(df, frame_or_series)\n\n # no change, position\n result = obj.reorder_levels([0, 1, 2])\n tm.assert_equal(obj, result)\n\n # no change, labels\n result = obj.reorder_levels(["L0", "L1", "L2"])\n tm.assert_equal(obj, result)\n\n # rotate, position\n result = obj.reorder_levels([1, 2, 0])\n e_idx = MultiIndex(\n levels=[["one", "two", "three"], [0, 1], ["bar"]],\n codes=[[0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0]],\n names=["L1", "L2", "L0"],\n )\n expected = DataFrame({"A": np.arange(6), "B": np.arange(6)}, index=e_idx)\n expected = tm.get_obj(expected, frame_or_series)\n tm.assert_equal(result, expected)\n\n result = obj.reorder_levels([0, 0, 0])\n e_idx = MultiIndex(\n levels=[["bar"], ["bar"], ["bar"]],\n codes=[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]],\n names=["L0", "L0", "L0"],\n )\n expected = DataFrame({"A": np.arange(6), "B": np.arange(6)}, index=e_idx)\n expected = tm.get_obj(expected, frame_or_series)\n tm.assert_equal(result, expected)\n\n result = obj.reorder_levels(["L0", "L0", "L0"])\n tm.assert_equal(result, expected)\n\n def test_reorder_levels_swaplevel_equivalence(\n self, multiindex_year_month_day_dataframe_random_data\n ):\n ymd = multiindex_year_month_day_dataframe_random_data\n\n result = ymd.reorder_levels(["month", "day", "year"])\n expected = ymd.swaplevel(0, 1).swaplevel(1, 2)\n tm.assert_frame_equal(result, expected)\n\n result = ymd["A"].reorder_levels(["month", "day", "year"])\n expected = ymd["A"].swaplevel(0, 1).swaplevel(1, 2)\n tm.assert_series_equal(result, expected)\n\n result = ymd.T.reorder_levels(["month", "day", "year"], axis=1)\n expected = ymd.T.swaplevel(0, 1, axis=1).swaplevel(1, 2, axis=1)\n tm.assert_frame_equal(result, expected)\n\n with pytest.raises(TypeError, match="hierarchical axis"):\n ymd.reorder_levels([1, 2], axis=1)\n\n with pytest.raises(IndexError, match="Too many levels"):\n ymd.index.reorder_levels([1, 2, 3])\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_reorder_levels.py
test_reorder_levels.py
Python
2,729
0.95
0.040541
0.05
react-lib
519
2023-10-06T01:34:10.692332
Apache-2.0
true
5ec4e273978f2b51b633e5787d811fd5
from __future__ import annotations\n\nfrom datetime import datetime\nimport re\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture\ndef mix_ab() -> dict[str, list[int | str]]:\n return {"a": list(range(4)), "b": list("ab..")}\n\n\n@pytest.fixture\ndef mix_abc() -> dict[str, list[float | str]]:\n return {"a": list(range(4)), "b": list("ab.."), "c": ["a", "b", np.nan, "d"]}\n\n\nclass TestDataFrameReplace:\n def test_replace_inplace(self, datetime_frame, float_string_frame):\n datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan\n datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan\n\n tsframe = datetime_frame.copy()\n return_value = tsframe.replace(np.nan, 0, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(tsframe, datetime_frame.fillna(0))\n\n # mixed type\n mf = float_string_frame\n mf.iloc[5:20, mf.columns.get_loc("foo")] = np.nan\n mf.iloc[-10:, mf.columns.get_loc("A")] = np.nan\n\n result = float_string_frame.replace(np.nan, 0)\n expected = float_string_frame.copy()\n expected["foo"] = expected["foo"].astype(object)\n expected = expected.fillna(value=0)\n tm.assert_frame_equal(result, expected)\n\n tsframe = datetime_frame.copy()\n return_value = tsframe.replace([np.nan], [0], inplace=True)\n assert return_value is None\n tm.assert_frame_equal(tsframe, datetime_frame.fillna(0))\n\n @pytest.mark.parametrize(\n "to_replace,values,expected",\n [\n # lists of regexes and values\n # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN]\n (\n [r"\s*\.\s*", r"e|f|g"],\n [np.nan, "crap"],\n {\n "a": ["a", "b", np.nan, np.nan],\n "b": ["crap"] * 3 + ["h"],\n "c": ["h", "crap", "l", "o"],\n },\n ),\n # list of [re1, re2, ..., reN] -> [re1, re2, .., reN]\n (\n [r"\s*(\.)\s*", r"(e|f|g)"],\n [r"\1\1", r"\1_crap"],\n {\n "a": ["a", "b", "..", ".."],\n "b": ["e_crap", "f_crap", "g_crap", "h"],\n "c": ["h", "e_crap", "l", "o"],\n },\n ),\n # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN\n # or vN)]\n (\n [r"\s*(\.)\s*", r"e"],\n [r"\1\1", r"crap"],\n {\n "a": ["a", "b", "..", ".."],\n "b": ["crap", "f", "g", "h"],\n "c": ["h", "crap", "l", "o"],\n },\n ),\n ],\n )\n @pytest.mark.parametrize("inplace", [True, False])\n @pytest.mark.parametrize("use_value_regex_args", [True, False])\n def test_regex_replace_list_obj(\n self, to_replace, values, expected, inplace, use_value_regex_args\n ):\n df = DataFrame({"a": list("ab.."), "b": list("efgh"), "c": list("helo")})\n\n if use_value_regex_args:\n result = df.replace(value=values, regex=to_replace, inplace=inplace)\n else:\n result = df.replace(to_replace, values, regex=True, inplace=inplace)\n\n if inplace:\n assert result is None\n result = df\n\n expected = DataFrame(expected)\n tm.assert_frame_equal(result, expected)\n\n def test_regex_replace_list_mixed(self, mix_ab):\n # mixed frame to make sure this doesn't break things\n dfmix = DataFrame(mix_ab)\n\n # lists of regexes and values\n # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN]\n to_replace_res = [r"\s*\.\s*", r"a"]\n values = [np.nan, "crap"]\n mix2 = {"a": list(range(4)), "b": list("ab.."), "c": list("halo")}\n dfmix2 = DataFrame(mix2)\n res = dfmix2.replace(to_replace_res, values, regex=True)\n expec = DataFrame(\n {\n "a": mix2["a"],\n "b": ["crap", "b", np.nan, np.nan],\n "c": ["h", "crap", "l", "o"],\n }\n )\n tm.assert_frame_equal(res, expec)\n\n # list of [re1, re2, ..., reN] -> [re1, re2, .., reN]\n to_replace_res = [r"\s*(\.)\s*", r"(a|b)"]\n values = [r"\1\1", r"\1_crap"]\n res = dfmix.replace(to_replace_res, values, regex=True)\n expec = DataFrame({"a": mix_ab["a"], "b": ["a_crap", "b_crap", "..", ".."]})\n tm.assert_frame_equal(res, expec)\n\n # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN\n # or vN)]\n to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"]\n values = [r"\1\1", r"crap", r"\1_crap"]\n res = dfmix.replace(to_replace_res, values, regex=True)\n expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]})\n tm.assert_frame_equal(res, expec)\n\n to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"]\n values = [r"\1\1", r"crap", r"\1_crap"]\n res = dfmix.replace(regex=to_replace_res, value=values)\n expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]})\n tm.assert_frame_equal(res, expec)\n\n def test_regex_replace_list_mixed_inplace(self, mix_ab):\n dfmix = DataFrame(mix_ab)\n # the same inplace\n # lists of regexes and values\n # list of [re1, re2, ..., reN] -> [v1, v2, ..., vN]\n to_replace_res = [r"\s*\.\s*", r"a"]\n values = [np.nan, "crap"]\n res = dfmix.copy()\n return_value = res.replace(to_replace_res, values, inplace=True, regex=True)\n assert return_value is None\n expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b", np.nan, np.nan]})\n tm.assert_frame_equal(res, expec)\n\n # list of [re1, re2, ..., reN] -> [re1, re2, .., reN]\n to_replace_res = [r"\s*(\.)\s*", r"(a|b)"]\n values = [r"\1\1", r"\1_crap"]\n res = dfmix.copy()\n return_value = res.replace(to_replace_res, values, inplace=True, regex=True)\n assert return_value is None\n expec = DataFrame({"a": mix_ab["a"], "b": ["a_crap", "b_crap", "..", ".."]})\n tm.assert_frame_equal(res, expec)\n\n # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN\n # or vN)]\n to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"]\n values = [r"\1\1", r"crap", r"\1_crap"]\n res = dfmix.copy()\n return_value = res.replace(to_replace_res, values, inplace=True, regex=True)\n assert return_value is None\n expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]})\n tm.assert_frame_equal(res, expec)\n\n to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"]\n values = [r"\1\1", r"crap", r"\1_crap"]\n res = dfmix.copy()\n return_value = res.replace(regex=to_replace_res, value=values, inplace=True)\n assert return_value is None\n expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]})\n tm.assert_frame_equal(res, expec)\n\n def test_regex_replace_dict_mixed(self, mix_abc):\n dfmix = DataFrame(mix_abc)\n\n # dicts\n # single dict {re1: v1}, search the whole frame\n # need test for this...\n\n # list of dicts {re1: v1, re2: v2, ..., re3: v3}, search the whole\n # frame\n res = dfmix.replace({"b": r"\s*\.\s*"}, {"b": np.nan}, regex=True)\n res2 = dfmix.copy()\n return_value = res2.replace(\n {"b": r"\s*\.\s*"}, {"b": np.nan}, inplace=True, regex=True\n )\n assert return_value is None\n expec = DataFrame(\n {"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]}\n )\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n\n # list of dicts {re1: re11, re2: re12, ..., reN: re1N}, search the\n # whole frame\n res = dfmix.replace({"b": r"\s*(\.)\s*"}, {"b": r"\1ty"}, regex=True)\n res2 = dfmix.copy()\n return_value = res2.replace(\n {"b": r"\s*(\.)\s*"}, {"b": r"\1ty"}, inplace=True, regex=True\n )\n assert return_value is None\n expec = DataFrame(\n {"a": mix_abc["a"], "b": ["a", "b", ".ty", ".ty"], "c": mix_abc["c"]}\n )\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n\n res = dfmix.replace(regex={"b": r"\s*(\.)\s*"}, value={"b": r"\1ty"})\n res2 = dfmix.copy()\n return_value = res2.replace(\n regex={"b": r"\s*(\.)\s*"}, value={"b": r"\1ty"}, inplace=True\n )\n assert return_value is None\n expec = DataFrame(\n {"a": mix_abc["a"], "b": ["a", "b", ".ty", ".ty"], "c": mix_abc["c"]}\n )\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n\n # scalar -> dict\n # to_replace regex, {value: value}\n expec = DataFrame(\n {"a": mix_abc["a"], "b": [np.nan, "b", ".", "."], "c": mix_abc["c"]}\n )\n res = dfmix.replace("a", {"b": np.nan}, regex=True)\n res2 = dfmix.copy()\n return_value = res2.replace("a", {"b": np.nan}, regex=True, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n\n res = dfmix.replace("a", {"b": np.nan}, regex=True)\n res2 = dfmix.copy()\n return_value = res2.replace(regex="a", value={"b": np.nan}, inplace=True)\n assert return_value is None\n expec = DataFrame(\n {"a": mix_abc["a"], "b": [np.nan, "b", ".", "."], "c": mix_abc["c"]}\n )\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n\n def test_regex_replace_dict_nested(self, mix_abc):\n # nested dicts will not work until this is implemented for Series\n dfmix = DataFrame(mix_abc)\n res = dfmix.replace({"b": {r"\s*\.\s*": np.nan}}, regex=True)\n res2 = dfmix.copy()\n res4 = dfmix.copy()\n return_value = res2.replace(\n {"b": {r"\s*\.\s*": np.nan}}, inplace=True, regex=True\n )\n assert return_value is None\n res3 = dfmix.replace(regex={"b": {r"\s*\.\s*": np.nan}})\n return_value = res4.replace(regex={"b": {r"\s*\.\s*": np.nan}}, inplace=True)\n assert return_value is None\n expec = DataFrame(\n {"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]}\n )\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n tm.assert_frame_equal(res3, expec)\n tm.assert_frame_equal(res4, expec)\n\n def test_regex_replace_dict_nested_non_first_character(self, any_string_dtype):\n # GH 25259\n dtype = any_string_dtype\n df = DataFrame({"first": ["abc", "bca", "cab"]}, dtype=dtype)\n result = df.replace({"a": "."}, regex=True)\n expected = DataFrame({"first": [".bc", "bc.", "c.b"]}, dtype=dtype)\n tm.assert_frame_equal(result, expected)\n\n def test_regex_replace_dict_nested_gh4115(self):\n df = DataFrame(\n {"Type": Series(["Q", "T", "Q", "Q", "T"], dtype=object), "tmp": 2}\n )\n expected = DataFrame({"Type": [0, 1, 0, 0, 1], "tmp": 2})\n msg = "Downcasting behavior in `replace`"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.replace({"Type": {"Q": 0, "T": 1}})\n\n tm.assert_frame_equal(result, expected)\n\n def test_regex_replace_list_to_scalar(self, mix_abc, using_infer_string):\n df = DataFrame(mix_abc)\n expec = DataFrame(\n {\n "a": mix_abc["a"],\n "b": [np.nan] * 4,\n "c": [np.nan, np.nan, np.nan, "d"],\n }\n )\n if using_infer_string:\n expec["b"] = expec["b"].astype("str")\n msg = "Downcasting behavior in `replace`"\n warn = None if using_infer_string else FutureWarning\n with tm.assert_produces_warning(warn, match=msg):\n res = df.replace([r"\s*\.\s*", "a|b"], np.nan, regex=True)\n res2 = df.copy()\n res3 = df.copy()\n with tm.assert_produces_warning(warn, match=msg):\n return_value = res2.replace(\n [r"\s*\.\s*", "a|b"], np.nan, regex=True, inplace=True\n )\n assert return_value is None\n with tm.assert_produces_warning(warn, match=msg):\n return_value = res3.replace(\n regex=[r"\s*\.\s*", "a|b"], value=np.nan, inplace=True\n )\n assert return_value is None\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n tm.assert_frame_equal(res3, expec)\n\n def test_regex_replace_str_to_numeric(self, mix_abc):\n # what happens when you try to replace a numeric value with a regex?\n df = DataFrame(mix_abc)\n res = df.replace(r"\s*\.\s*", 0, regex=True)\n res2 = df.copy()\n return_value = res2.replace(r"\s*\.\s*", 0, inplace=True, regex=True)\n assert return_value is None\n res3 = df.copy()\n return_value = res3.replace(regex=r"\s*\.\s*", value=0, inplace=True)\n assert return_value is None\n expec = DataFrame({"a": mix_abc["a"], "b": ["a", "b", 0, 0], "c": mix_abc["c"]})\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n tm.assert_frame_equal(res3, expec)\n\n def test_regex_replace_regex_list_to_numeric(self, mix_abc):\n df = DataFrame(mix_abc)\n res = df.replace([r"\s*\.\s*", "b"], 0, regex=True)\n res2 = df.copy()\n return_value = res2.replace([r"\s*\.\s*", "b"], 0, regex=True, inplace=True)\n assert return_value is None\n res3 = df.copy()\n return_value = res3.replace(regex=[r"\s*\.\s*", "b"], value=0, inplace=True)\n assert return_value is None\n expec = DataFrame(\n {"a": mix_abc["a"], "b": ["a", 0, 0, 0], "c": ["a", 0, np.nan, "d"]}\n )\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n tm.assert_frame_equal(res3, expec)\n\n def test_regex_replace_series_of_regexes(self, mix_abc):\n df = DataFrame(mix_abc)\n s1 = Series({"b": r"\s*\.\s*"})\n s2 = Series({"b": np.nan})\n res = df.replace(s1, s2, regex=True)\n res2 = df.copy()\n return_value = res2.replace(s1, s2, inplace=True, regex=True)\n assert return_value is None\n res3 = df.copy()\n return_value = res3.replace(regex=s1, value=s2, inplace=True)\n assert return_value is None\n expec = DataFrame(\n {"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]}\n )\n tm.assert_frame_equal(res, expec)\n tm.assert_frame_equal(res2, expec)\n tm.assert_frame_equal(res3, expec)\n\n def test_regex_replace_numeric_to_object_conversion(self, mix_abc):\n df = DataFrame(mix_abc)\n expec = DataFrame({"a": ["a", 1, 2, 3], "b": mix_abc["b"], "c": mix_abc["c"]})\n res = df.replace(0, "a")\n tm.assert_frame_equal(res, expec)\n assert res.a.dtype == np.object_\n\n @pytest.mark.parametrize(\n "to_replace", [{"": np.nan, ",": ""}, {",": "", "": np.nan}]\n )\n def test_joint_simple_replace_and_regex_replace(self, to_replace):\n # GH-39338\n df = DataFrame(\n {\n "col1": ["1,000", "a", "3"],\n "col2": ["a", "", "b"],\n "col3": ["a", "b", "c"],\n }\n )\n result = df.replace(regex=to_replace)\n expected = DataFrame(\n {\n "col1": ["1000", "a", "3"],\n "col2": ["a", np.nan, "b"],\n "col3": ["a", "b", "c"],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("metachar", ["[]", "()", r"\d", r"\w", r"\s"])\n def test_replace_regex_metachar(self, metachar):\n df = DataFrame({"a": [metachar, "else"]})\n result = df.replace({"a": {metachar: "paren"}})\n expected = DataFrame({"a": ["paren", "else"]})\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "data,to_replace,expected",\n [\n (["xax", "xbx"], {"a": "c", "b": "d"}, ["xcx", "xdx"]),\n (["d", "", ""], {r"^\s*$": pd.NA}, ["d", pd.NA, pd.NA]),\n ],\n )\n def test_regex_replace_string_types(\n self, data, to_replace, expected, frame_or_series, any_string_dtype\n ):\n # GH-41333, GH-35977\n dtype = any_string_dtype\n obj = frame_or_series(data, dtype=dtype)\n result = obj.replace(to_replace, regex=True)\n expected = frame_or_series(expected, dtype=dtype)\n\n tm.assert_equal(result, expected)\n\n def test_replace(self, datetime_frame):\n datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan\n datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan\n\n zero_filled = datetime_frame.replace(np.nan, -1e8)\n tm.assert_frame_equal(zero_filled, datetime_frame.fillna(-1e8))\n tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), datetime_frame)\n\n datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan\n datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan\n datetime_frame.loc[datetime_frame.index[:5], "B"] = -1e8\n\n # empty\n df = DataFrame(index=["a", "b"])\n tm.assert_frame_equal(df, df.replace(5, 7))\n\n # GH 11698\n # test for mixed data types.\n df = DataFrame(\n [("-", pd.to_datetime("20150101")), ("a", pd.to_datetime("20150102"))]\n )\n df1 = df.replace("-", np.nan)\n expected_df = DataFrame(\n [(np.nan, pd.to_datetime("20150101")), ("a", pd.to_datetime("20150102"))]\n )\n tm.assert_frame_equal(df1, expected_df)\n\n def test_replace_list(self):\n obj = {"a": list("ab.."), "b": list("efgh"), "c": list("helo")}\n dfobj = DataFrame(obj)\n\n # lists of regexes and values\n # list of [v1, v2, ..., vN] -> [v1, v2, ..., vN]\n to_replace_res = [r".", r"e"]\n values = [np.nan, "crap"]\n res = dfobj.replace(to_replace_res, values)\n expec = DataFrame(\n {\n "a": ["a", "b", np.nan, np.nan],\n "b": ["crap", "f", "g", "h"],\n "c": ["h", "crap", "l", "o"],\n }\n )\n tm.assert_frame_equal(res, expec)\n\n # list of [v1, v2, ..., vN] -> [v1, v2, .., vN]\n to_replace_res = [r".", r"f"]\n values = [r"..", r"crap"]\n res = dfobj.replace(to_replace_res, values)\n expec = DataFrame(\n {\n "a": ["a", "b", "..", ".."],\n "b": ["e", "crap", "g", "h"],\n "c": ["h", "e", "l", "o"],\n }\n )\n tm.assert_frame_equal(res, expec)\n\n def test_replace_with_empty_list(self, frame_or_series):\n # GH 21977\n ser = Series([["a", "b"], [], np.nan, [1]])\n obj = DataFrame({"col": ser})\n obj = tm.get_obj(obj, frame_or_series)\n expected = obj\n result = obj.replace([], np.nan)\n tm.assert_equal(result, expected)\n\n # GH 19266\n msg = (\n "NumPy boolean array indexing assignment cannot assign {size} "\n "input values to the 1 output values where the mask is true"\n )\n with pytest.raises(ValueError, match=msg.format(size=0)):\n obj.replace({np.nan: []})\n with pytest.raises(ValueError, match=msg.format(size=2)):\n obj.replace({np.nan: ["dummy", "alt"]})\n\n def test_replace_series_dict(self):\n # from GH 3064\n df = DataFrame({"zero": {"a": 0.0, "b": 1}, "one": {"a": 2.0, "b": 0}})\n result = df.replace(0, {"zero": 0.5, "one": 1.0})\n expected = DataFrame({"zero": {"a": 0.5, "b": 1}, "one": {"a": 2.0, "b": 1.0}})\n tm.assert_frame_equal(result, expected)\n\n result = df.replace(0, df.mean())\n tm.assert_frame_equal(result, expected)\n\n # series to series/dict\n df = DataFrame({"zero": {"a": 0.0, "b": 1}, "one": {"a": 2.0, "b": 0}})\n s = Series({"zero": 0.0, "one": 2.0})\n result = df.replace(s, {"zero": 0.5, "one": 1.0})\n expected = DataFrame({"zero": {"a": 0.5, "b": 1}, "one": {"a": 1.0, "b": 0.0}})\n tm.assert_frame_equal(result, expected)\n\n result = df.replace(s, df.mean())\n tm.assert_frame_equal(result, expected)\n\n def test_replace_convert(self):\n # gh 3907\n df = DataFrame([["foo", "bar", "bah"], ["bar", "foo", "bah"]])\n m = {"foo": 1, "bar": 2, "bah": 3}\n msg = "Downcasting behavior in `replace` "\n with tm.assert_produces_warning(FutureWarning, match=msg):\n rep = df.replace(m)\n expec = Series([np.int64] * 3)\n res = rep.dtypes\n tm.assert_series_equal(expec, res)\n\n def test_replace_mixed(self, float_string_frame):\n mf = float_string_frame\n mf.iloc[5:20, mf.columns.get_loc("foo")] = np.nan\n mf.iloc[-10:, mf.columns.get_loc("A")] = np.nan\n\n result = float_string_frame.replace(np.nan, -18)\n expected = float_string_frame.copy()\n expected["foo"] = expected["foo"].astype(object)\n expected = expected.fillna(value=-18)\n tm.assert_frame_equal(result, expected)\n expected2 = float_string_frame.copy()\n expected2["foo"] = expected2["foo"].astype(object)\n tm.assert_frame_equal(result.replace(-18, np.nan), expected2)\n\n result = float_string_frame.replace(np.nan, -1e8)\n expected = float_string_frame.copy()\n expected["foo"] = expected["foo"].astype(object)\n expected = expected.fillna(value=-1e8)\n tm.assert_frame_equal(result, expected)\n expected2 = float_string_frame.copy()\n expected2["foo"] = expected2["foo"].astype(object)\n tm.assert_frame_equal(result.replace(-1e8, np.nan), expected2)\n\n def test_replace_mixed_int_block_upcasting(self):\n # int block upcasting\n df = DataFrame(\n {\n "A": Series([1.0, 2.0], dtype="float64"),\n "B": Series([0, 1], dtype="int64"),\n }\n )\n expected = DataFrame(\n {\n "A": Series([1.0, 2.0], dtype="float64"),\n "B": Series([0.5, 1], dtype="float64"),\n }\n )\n result = df.replace(0, 0.5)\n tm.assert_frame_equal(result, expected)\n\n return_value = df.replace(0, 0.5, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(df, expected)\n\n def test_replace_mixed_int_block_splitting(self):\n # int block splitting\n df = DataFrame(\n {\n "A": Series([1.0, 2.0], dtype="float64"),\n "B": Series([0, 1], dtype="int64"),\n "C": Series([1, 2], dtype="int64"),\n }\n )\n expected = DataFrame(\n {\n "A": Series([1.0, 2.0], dtype="float64"),\n "B": Series([0.5, 1], dtype="float64"),\n "C": Series([1, 2], dtype="int64"),\n }\n )\n result = df.replace(0, 0.5)\n tm.assert_frame_equal(result, expected)\n\n def test_replace_mixed2(self, using_infer_string):\n # to object block upcasting\n df = DataFrame(\n {\n "A": Series([1.0, 2.0], dtype="float64"),\n "B": Series([0, 1], dtype="int64"),\n }\n )\n expected = DataFrame(\n {\n "A": Series([1, "foo"], dtype="object"),\n "B": Series([0, 1], dtype="int64"),\n }\n )\n result = df.replace(2, "foo")\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame(\n {\n "A": Series(["foo", "bar"], dtype="object"),\n "B": Series([0, "foo"], dtype="object"),\n }\n )\n result = df.replace([1, 2], ["foo", "bar"])\n tm.assert_frame_equal(result, expected)\n\n def test_replace_mixed3(self):\n # test case from\n df = DataFrame(\n {"A": Series([3, 0], dtype="int64"), "B": Series([0, 3], dtype="int64")}\n )\n result = df.replace(3, df.mean().to_dict())\n expected = df.copy().astype("float64")\n m = df.mean()\n expected.iloc[0, 0] = m.iloc[0]\n expected.iloc[1, 1] = m.iloc[1]\n tm.assert_frame_equal(result, expected)\n\n def test_replace_nullable_int_with_string_doesnt_cast(self):\n # GH#25438 don't cast df['a'] to float64\n df = DataFrame({"a": [1, 2, 3, np.nan], "b": ["some", "strings", "here", "he"]})\n df["a"] = df["a"].astype("Int64")\n\n res = df.replace("", np.nan)\n tm.assert_series_equal(res["a"], df["a"])\n\n @pytest.mark.parametrize("dtype", ["boolean", "Int64", "Float64"])\n def test_replace_with_nullable_column(self, dtype):\n # GH-44499\n nullable_ser = Series([1, 0, 1], dtype=dtype)\n df = DataFrame({"A": ["A", "B", "x"], "B": nullable_ser})\n result = df.replace("x", "X")\n expected = DataFrame({"A": ["A", "B", "X"], "B": nullable_ser})\n tm.assert_frame_equal(result, expected)\n\n def test_replace_simple_nested_dict(self):\n df = DataFrame({"col": range(1, 5)})\n expected = DataFrame({"col": ["a", 2, 3, "b"]})\n\n result = df.replace({"col": {1: "a", 4: "b"}})\n tm.assert_frame_equal(expected, result)\n\n # in this case, should be the same as the not nested version\n result = df.replace({1: "a", 4: "b"})\n tm.assert_frame_equal(expected, result)\n\n def test_replace_simple_nested_dict_with_nonexistent_value(self):\n df = DataFrame({"col": range(1, 5)})\n expected = DataFrame({"col": ["a", 2, 3, "b"]})\n\n result = df.replace({-1: "-", 1: "a", 4: "b"})\n tm.assert_frame_equal(expected, result)\n\n result = df.replace({"col": {-1: "-", 1: "a", 4: "b"}})\n tm.assert_frame_equal(expected, result)\n\n def test_replace_NA_with_None(self):\n # gh-45601\n df = DataFrame({"value": [42, None]}).astype({"value": "Int64"})\n result = df.replace({pd.NA: None})\n expected = DataFrame({"value": [42, None]}, dtype=object)\n tm.assert_frame_equal(result, expected)\n\n def test_replace_NAT_with_None(self):\n # gh-45836\n df = DataFrame([pd.NaT, pd.NaT])\n result = df.replace({pd.NaT: None, np.nan: None})\n expected = DataFrame([None, None])\n tm.assert_frame_equal(result, expected)\n\n def test_replace_with_None_keeps_categorical(self):\n # gh-46634\n cat_series = Series(["b", "b", "b", "d"], dtype="category")\n df = DataFrame(\n {\n "id": Series([5, 4, 3, 2], dtype="float64"),\n "col": cat_series,\n }\n )\n result = df.replace({3: None})\n\n expected = DataFrame(\n {\n "id": Series([5.0, 4.0, None, 2.0], dtype="object"),\n "col": cat_series,\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_replace_value_is_none(self, datetime_frame):\n orig_value = datetime_frame.iloc[0, 0]\n orig2 = datetime_frame.iloc[1, 0]\n\n datetime_frame.iloc[0, 0] = np.nan\n datetime_frame.iloc[1, 0] = 1\n\n result = datetime_frame.replace(to_replace={np.nan: 0})\n expected = datetime_frame.T.replace(to_replace={np.nan: 0}).T\n tm.assert_frame_equal(result, expected)\n\n result = datetime_frame.replace(to_replace={np.nan: 0, 1: -1e8})\n tsframe = datetime_frame.copy()\n tsframe.iloc[0, 0] = 0\n tsframe.iloc[1, 0] = -1e8\n expected = tsframe\n tm.assert_frame_equal(expected, result)\n datetime_frame.iloc[0, 0] = orig_value\n datetime_frame.iloc[1, 0] = orig2\n\n def test_replace_for_new_dtypes(self, datetime_frame):\n # dtypes\n tsframe = datetime_frame.copy().astype(np.float32)\n tsframe.loc[tsframe.index[:5], "A"] = np.nan\n tsframe.loc[tsframe.index[-5:], "A"] = np.nan\n\n zero_filled = tsframe.replace(np.nan, -1e8)\n tm.assert_frame_equal(zero_filled, tsframe.fillna(-1e8))\n tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), tsframe)\n\n tsframe.loc[tsframe.index[:5], "A"] = np.nan\n tsframe.loc[tsframe.index[-5:], "A"] = np.nan\n tsframe.loc[tsframe.index[:5], "B"] = np.nan\n msg = "DataFrame.fillna with 'method' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n # TODO: what is this even testing?\n result = tsframe.fillna(method="bfill")\n tm.assert_frame_equal(result, tsframe.fillna(method="bfill"))\n\n @pytest.mark.parametrize(\n "frame, to_replace, value, expected",\n [\n (DataFrame({"ints": [1, 2, 3]}), 1, 0, DataFrame({"ints": [0, 2, 3]})),\n (\n DataFrame({"ints": [1, 2, 3]}, dtype=np.int32),\n 1,\n 0,\n DataFrame({"ints": [0, 2, 3]}, dtype=np.int32),\n ),\n (\n DataFrame({"ints": [1, 2, 3]}, dtype=np.int16),\n 1,\n 0,\n DataFrame({"ints": [0, 2, 3]}, dtype=np.int16),\n ),\n (\n DataFrame({"bools": [True, False, True]}),\n False,\n True,\n DataFrame({"bools": [True, True, True]}),\n ),\n (\n DataFrame({"complex": [1j, 2j, 3j]}),\n 1j,\n 0,\n DataFrame({"complex": [0j, 2j, 3j]}),\n ),\n (\n DataFrame(\n {\n "datetime64": Index(\n [\n datetime(2018, 5, 28),\n datetime(2018, 7, 28),\n datetime(2018, 5, 28),\n ]\n )\n }\n ),\n datetime(2018, 5, 28),\n datetime(2018, 7, 28),\n DataFrame({"datetime64": Index([datetime(2018, 7, 28)] * 3)}),\n ),\n # GH 20380\n (\n DataFrame({"dt": [datetime(3017, 12, 20)], "str": ["foo"]}),\n "foo",\n "bar",\n DataFrame({"dt": [datetime(3017, 12, 20)], "str": ["bar"]}),\n ),\n # GH 36782\n (\n DataFrame({"dt": [datetime(2920, 10, 1)]}),\n datetime(2920, 10, 1),\n datetime(2020, 10, 1),\n DataFrame({"dt": [datetime(2020, 10, 1)]}),\n ),\n (\n DataFrame(\n {\n "A": date_range("20130101", periods=3, tz="US/Eastern"),\n "B": [0, np.nan, 2],\n }\n ),\n Timestamp("20130102", tz="US/Eastern"),\n Timestamp("20130104", tz="US/Eastern"),\n DataFrame(\n {\n "A": pd.DatetimeIndex(\n [\n Timestamp("20130101", tz="US/Eastern"),\n Timestamp("20130104", tz="US/Eastern"),\n Timestamp("20130103", tz="US/Eastern"),\n ]\n ).as_unit("ns"),\n "B": [0, np.nan, 2],\n }\n ),\n ),\n # GH 35376\n (\n DataFrame([[1, 1.0], [2, 2.0]]),\n 1.0,\n 5,\n DataFrame([[5, 5.0], [2, 2.0]]),\n ),\n (\n DataFrame([[1, 1.0], [2, 2.0]]),\n 1,\n 5,\n DataFrame([[5, 5.0], [2, 2.0]]),\n ),\n (\n DataFrame([[1, 1.0], [2, 2.0]]),\n 1.0,\n 5.0,\n DataFrame([[5, 5.0], [2, 2.0]]),\n ),\n (\n DataFrame([[1, 1.0], [2, 2.0]]),\n 1,\n 5.0,\n DataFrame([[5, 5.0], [2, 2.0]]),\n ),\n ],\n )\n def test_replace_dtypes(self, frame, to_replace, value, expected):\n warn = None\n if isinstance(to_replace, datetime) and to_replace.year == 2920:\n warn = FutureWarning\n msg = "Downcasting behavior in `replace` "\n with tm.assert_produces_warning(warn, match=msg):\n result = frame.replace(to_replace, value)\n tm.assert_frame_equal(result, expected)\n\n def test_replace_input_formats_listlike(self):\n # both dicts\n to_rep = {"A": np.nan, "B": 0, "C": ""}\n values = {"A": 0, "B": -1, "C": "missing"}\n df = DataFrame(\n {"A": [np.nan, 0, np.inf], "B": [0, 2, 5], "C": ["", "asdf", "fd"]}\n )\n filled = df.replace(to_rep, values)\n expected = {k: v.replace(to_rep[k], values[k]) for k, v in df.items()}\n tm.assert_frame_equal(filled, DataFrame(expected))\n\n result = df.replace([0, 2, 5], [5, 2, 0])\n expected = DataFrame(\n {"A": [np.nan, 5, np.inf], "B": [5, 2, 0], "C": ["", "asdf", "fd"]}\n )\n tm.assert_frame_equal(result, expected)\n\n # scalar to dict\n values = {"A": 0, "B": -1, "C": "missing"}\n df = DataFrame(\n {"A": [np.nan, 0, np.nan], "B": [0, 2, 5], "C": ["", "asdf", "fd"]}\n )\n filled = df.replace(np.nan, values)\n expected = {k: v.replace(np.nan, values[k]) for k, v in df.items()}\n tm.assert_frame_equal(filled, DataFrame(expected))\n\n # list to list\n to_rep = [np.nan, 0, ""]\n values = [-2, -1, "missing"]\n result = df.replace(to_rep, values)\n expected = df.copy()\n for rep, value in zip(to_rep, values):\n return_value = expected.replace(rep, value, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n msg = r"Replacement lists must match in length\. Expecting 3 got 2"\n with pytest.raises(ValueError, match=msg):\n df.replace(to_rep, values[1:])\n\n def test_replace_input_formats_scalar(self):\n df = DataFrame(\n {"A": [np.nan, 0, np.inf], "B": [0, 2, 5], "C": ["", "asdf", "fd"]}\n )\n\n # dict to scalar\n to_rep = {"A": np.nan, "B": 0, "C": ""}\n filled = df.replace(to_rep, 0)\n expected = {k: v.replace(to_rep[k], 0) for k, v in df.items()}\n tm.assert_frame_equal(filled, DataFrame(expected))\n\n msg = "value argument must be scalar, dict, or Series"\n with pytest.raises(TypeError, match=msg):\n df.replace(to_rep, [np.nan, 0, ""])\n\n # list to scalar\n to_rep = [np.nan, 0, ""]\n result = df.replace(to_rep, -1)\n expected = df.copy()\n for rep in to_rep:\n return_value = expected.replace(rep, -1, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(result, expected)\n\n def test_replace_limit(self):\n # TODO\n pass\n\n def test_replace_dict_no_regex(self, any_string_dtype):\n answer = Series(\n {\n 0: "Strongly Agree",\n 1: "Agree",\n 2: "Neutral",\n 3: "Disagree",\n 4: "Strongly Disagree",\n },\n dtype=any_string_dtype,\n )\n weights = {\n "Agree": 4,\n "Disagree": 2,\n "Neutral": 3,\n "Strongly Agree": 5,\n "Strongly Disagree": 1,\n }\n expected = Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1})\n msg = "Downcasting behavior in `replace` "\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = answer.replace(weights)\n tm.assert_series_equal(result, expected)\n\n def test_replace_series_no_regex(self, any_string_dtype):\n answer = Series(\n {\n 0: "Strongly Agree",\n 1: "Agree",\n 2: "Neutral",\n 3: "Disagree",\n 4: "Strongly Disagree",\n },\n dtype=any_string_dtype,\n )\n weights = Series(\n {\n "Agree": 4,\n "Disagree": 2,\n "Neutral": 3,\n "Strongly Agree": 5,\n "Strongly Disagree": 1,\n }\n )\n expected = Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1})\n msg = "Downcasting behavior in `replace` "\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = answer.replace(weights)\n tm.assert_series_equal(result, expected)\n\n def test_replace_dict_tuple_list_ordering_remains_the_same(self):\n df = DataFrame({"A": [np.nan, 1]})\n res1 = df.replace(to_replace={np.nan: 0, 1: -1e8})\n res2 = df.replace(to_replace=(1, np.nan), value=[-1e8, 0])\n res3 = df.replace(to_replace=[1, np.nan], value=[-1e8, 0])\n\n expected = DataFrame({"A": [0, -1e8]})\n tm.assert_frame_equal(res1, res2)\n tm.assert_frame_equal(res2, res3)\n tm.assert_frame_equal(res3, expected)\n\n def test_replace_doesnt_replace_without_regex(self):\n df = DataFrame(\n {\n "fol": [1, 2, 2, 3],\n "T_opp": ["0", "vr", "0", "0"],\n "T_Dir": ["0", "0", "0", "bt"],\n "T_Enh": ["vo", "0", "0", "0"],\n }\n )\n res = df.replace({r"\D": 1})\n tm.assert_frame_equal(df, res)\n\n def test_replace_bool_with_string(self):\n df = DataFrame({"a": [True, False], "b": list("ab")})\n result = df.replace(True, "a")\n expected = DataFrame({"a": ["a", False], "b": df.b})\n tm.assert_frame_equal(result, expected)\n\n def test_replace_pure_bool_with_string_no_op(self):\n df = DataFrame(np.random.default_rng(2).random((2, 2)) > 0.5)\n result = df.replace("asdf", "fdsa")\n tm.assert_frame_equal(df, result)\n\n def test_replace_bool_with_bool(self):\n df = DataFrame(np.random.default_rng(2).random((2, 2)) > 0.5)\n result = df.replace(False, True)\n expected = DataFrame(np.ones((2, 2), dtype=bool))\n tm.assert_frame_equal(result, expected)\n\n def test_replace_with_dict_with_bool_keys(self):\n df = DataFrame({0: [True, False], 1: [False, True]})\n result = df.replace({"asdf": "asdb", True: "yes"})\n expected = DataFrame({0: ["yes", False], 1: [False, "yes"]})\n tm.assert_frame_equal(result, expected)\n\n def test_replace_dict_strings_vs_ints(self):\n # GH#34789\n df = DataFrame({"Y0": [1, 2], "Y1": [3, 4]})\n result = df.replace({"replace_string": "test"})\n\n tm.assert_frame_equal(result, df)\n\n result = df["Y0"].replace({"replace_string": "test"})\n tm.assert_series_equal(result, df["Y0"])\n\n def test_replace_truthy(self):\n df = DataFrame({"a": [True, True]})\n r = df.replace([np.inf, -np.inf], np.nan)\n e = df\n tm.assert_frame_equal(r, e)\n\n def test_nested_dict_overlapping_keys_replace_int(self):\n # GH 27660 keep behaviour consistent for simple dictionary and\n # nested dictionary replacement\n df = DataFrame({"a": list(range(1, 5))})\n\n result = df.replace({"a": dict(zip(range(1, 5), range(2, 6)))})\n expected = df.replace(dict(zip(range(1, 5), range(2, 6))))\n tm.assert_frame_equal(result, expected)\n\n def test_nested_dict_overlapping_keys_replace_str(self):\n # GH 27660\n a = np.arange(1, 5)\n astr = a.astype(str)\n bstr = np.arange(2, 6).astype(str)\n df = DataFrame({"a": astr})\n result = df.replace(dict(zip(astr, bstr)))\n expected = df.replace({"a": dict(zip(astr, bstr))})\n tm.assert_frame_equal(result, expected)\n\n def test_replace_swapping_bug(self):\n df = DataFrame({"a": [True, False, True]})\n res = df.replace({"a": {True: "Y", False: "N"}})\n expect = DataFrame({"a": ["Y", "N", "Y"]}, dtype=object)\n tm.assert_frame_equal(res, expect)\n\n df = DataFrame({"a": [0, 1, 0]})\n res = df.replace({"a": {0: "Y", 1: "N"}})\n expect = DataFrame({"a": ["Y", "N", "Y"]}, dtype=object)\n tm.assert_frame_equal(res, expect)\n\n def test_replace_period(self):\n d = {\n "fname": {\n "out_augmented_AUG_2011.json": pd.Period(year=2011, month=8, freq="M"),\n "out_augmented_JAN_2011.json": pd.Period(year=2011, month=1, freq="M"),\n "out_augmented_MAY_2012.json": pd.Period(year=2012, month=5, freq="M"),\n "out_augmented_SUBSIDY_WEEK.json": pd.Period(\n year=2011, month=4, freq="M"\n ),\n "out_augmented_AUG_2012.json": pd.Period(year=2012, month=8, freq="M"),\n "out_augmented_MAY_2011.json": pd.Period(year=2011, month=5, freq="M"),\n "out_augmented_SEP_2013.json": pd.Period(year=2013, month=9, freq="M"),\n }\n }\n\n df = DataFrame(\n [\n "out_augmented_AUG_2012.json",\n "out_augmented_SEP_2013.json",\n "out_augmented_SUBSIDY_WEEK.json",\n "out_augmented_MAY_2012.json",\n "out_augmented_MAY_2011.json",\n "out_augmented_AUG_2011.json",\n "out_augmented_JAN_2011.json",\n ],\n columns=["fname"],\n )\n assert set(df.fname.values) == set(d["fname"].keys())\n\n expected = DataFrame({"fname": [d["fname"][k] for k in df.fname.values]})\n assert expected.dtypes.iloc[0] == "Period[M]"\n msg = "Downcasting behavior in `replace` "\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.replace(d)\n tm.assert_frame_equal(result, expected)\n\n def test_replace_datetime(self):\n d = {\n "fname": {\n "out_augmented_AUG_2011.json": Timestamp("2011-08"),\n "out_augmented_JAN_2011.json": Timestamp("2011-01"),\n "out_augmented_MAY_2012.json": Timestamp("2012-05"),\n "out_augmented_SUBSIDY_WEEK.json": Timestamp("2011-04"),\n "out_augmented_AUG_2012.json": Timestamp("2012-08"),\n "out_augmented_MAY_2011.json": Timestamp("2011-05"),\n "out_augmented_SEP_2013.json": Timestamp("2013-09"),\n }\n }\n\n df = DataFrame(\n [\n "out_augmented_AUG_2012.json",\n "out_augmented_SEP_2013.json",\n "out_augmented_SUBSIDY_WEEK.json",\n "out_augmented_MAY_2012.json",\n "out_augmented_MAY_2011.json",\n "out_augmented_AUG_2011.json",\n "out_augmented_JAN_2011.json",\n ],\n columns=["fname"],\n )\n assert set(df.fname.values) == set(d["fname"].keys())\n expected = DataFrame({"fname": [d["fname"][k] for k in df.fname.values]})\n msg = "Downcasting behavior in `replace` "\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.replace(d)\n tm.assert_frame_equal(result, expected)\n\n def test_replace_datetimetz(self):\n # GH 11326\n # behaving poorly when presented with a datetime64[ns, tz]\n df = DataFrame(\n {\n "A": date_range("20130101", periods=3, tz="US/Eastern"),\n "B": [0, np.nan, 2],\n }\n )\n result = df.replace(np.nan, 1)\n expected = DataFrame(\n {\n "A": date_range("20130101", periods=3, tz="US/Eastern"),\n "B": Series([0, 1, 2], dtype="float64"),\n }\n )\n tm.assert_frame_equal(result, expected)\n\n result = df.fillna(1)\n tm.assert_frame_equal(result, expected)\n\n result = df.replace(0, np.nan)\n expected = DataFrame(\n {\n "A": date_range("20130101", periods=3, tz="US/Eastern"),\n "B": [np.nan, np.nan, 2],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n result = df.replace(\n Timestamp("20130102", tz="US/Eastern"),\n Timestamp("20130104", tz="US/Eastern"),\n )\n expected = DataFrame(\n {\n "A": [\n Timestamp("20130101", tz="US/Eastern"),\n Timestamp("20130104", tz="US/Eastern"),\n Timestamp("20130103", tz="US/Eastern"),\n ],\n "B": [0, np.nan, 2],\n }\n )\n expected["A"] = expected["A"].dt.as_unit("ns")\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n result.iloc[1, 0] = np.nan\n result = result.replace({"A": pd.NaT}, Timestamp("20130104", tz="US/Eastern"))\n tm.assert_frame_equal(result, expected)\n\n # pre-2.0 this would coerce to object with mismatched tzs\n result = df.copy()\n result.iloc[1, 0] = np.nan\n result = result.replace({"A": pd.NaT}, Timestamp("20130104", tz="US/Pacific"))\n expected = DataFrame(\n {\n "A": [\n Timestamp("20130101", tz="US/Eastern"),\n Timestamp("20130104", tz="US/Pacific").tz_convert("US/Eastern"),\n Timestamp("20130103", tz="US/Eastern"),\n ],\n "B": [0, np.nan, 2],\n }\n )\n expected["A"] = expected["A"].dt.as_unit("ns")\n tm.assert_frame_equal(result, expected)\n\n result = df.copy()\n result.iloc[1, 0] = np.nan\n result = result.replace({"A": np.nan}, Timestamp("20130104"))\n expected = DataFrame(\n {\n "A": [\n Timestamp("20130101", tz="US/Eastern"),\n Timestamp("20130104"),\n Timestamp("20130103", tz="US/Eastern"),\n ],\n "B": [0, np.nan, 2],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_replace_with_empty_dictlike(self, mix_abc):\n # GH 15289\n df = DataFrame(mix_abc)\n tm.assert_frame_equal(df, df.replace({}))\n tm.assert_frame_equal(df, df.replace(Series([], dtype=object)))\n\n tm.assert_frame_equal(df, df.replace({"b": {}}))\n tm.assert_frame_equal(df, df.replace(Series({"b": {}})))\n\n @pytest.mark.parametrize(\n "to_replace, method, expected",\n [\n (0, "bfill", {"A": [1, 1, 2], "B": [5, np.nan, 7], "C": ["a", "b", "c"]}),\n (\n np.nan,\n "bfill",\n {"A": [0, 1, 2], "B": [5.0, 7.0, 7.0], "C": ["a", "b", "c"]},\n ),\n ("d", "ffill", {"A": [0, 1, 2], "B": [5, np.nan, 7], "C": ["a", "b", "c"]}),\n (\n [0, 2],\n "bfill",\n {"A": [1, 1, 2], "B": [5, np.nan, 7], "C": ["a", "b", "c"]},\n ),\n (\n [1, 2],\n "pad",\n {"A": [0, 0, 0], "B": [5, np.nan, 7], "C": ["a", "b", "c"]},\n ),\n (\n (1, 2),\n "bfill",\n {"A": [0, 2, 2], "B": [5, np.nan, 7], "C": ["a", "b", "c"]},\n ),\n (\n ["b", "c"],\n "ffill",\n {"A": [0, 1, 2], "B": [5, np.nan, 7], "C": ["a", "a", "a"]},\n ),\n ],\n )\n def test_replace_method(self, to_replace, method, expected):\n # GH 19632\n df = DataFrame({"A": [0, 1, 2], "B": [5, np.nan, 7], "C": ["a", "b", "c"]})\n\n msg = "The 'method' keyword in DataFrame.replace is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.replace(to_replace=to_replace, value=None, method=method)\n expected = DataFrame(expected)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "replace_dict, final_data",\n [({"a": 1, "b": 1}, [[3, 3], [2, 2]]), ({"a": 1, "b": 2}, [[3, 1], [2, 3]])],\n )\n def test_categorical_replace_with_dict(self, replace_dict, final_data):\n # GH 26988\n df = DataFrame([[1, 1], [2, 2]], columns=["a", "b"], dtype="category")\n\n final_data = np.array(final_data)\n\n a = pd.Categorical(final_data[:, 0], categories=[3, 2])\n\n ex_cat = [3, 2] if replace_dict["b"] == 1 else [1, 3]\n b = pd.Categorical(final_data[:, 1], categories=ex_cat)\n\n expected = DataFrame({"a": a, "b": b})\n msg2 = "with CategoricalDtype is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg2):\n result = df.replace(replace_dict, 3)\n tm.assert_frame_equal(result, expected)\n msg = (\n r"Attributes of DataFrame.iloc\[:, 0\] \(column name=\"a\"\) are "\n "different"\n )\n with pytest.raises(AssertionError, match=msg):\n # ensure non-inplace call does not affect original\n tm.assert_frame_equal(df, expected)\n with tm.assert_produces_warning(FutureWarning, match=msg2):\n return_value = df.replace(replace_dict, 3, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize(\n "df, to_replace, exp",\n [\n (\n {"col1": [1, 2, 3], "col2": [4, 5, 6]},\n {4: 5, 5: 6, 6: 7},\n {"col1": [1, 2, 3], "col2": [5, 6, 7]},\n ),\n (\n {"col1": [1, 2, 3], "col2": ["4", "5", "6"]},\n {"4": "5", "5": "6", "6": "7"},\n {"col1": [1, 2, 3], "col2": ["5", "6", "7"]},\n ),\n ],\n )\n def test_replace_commutative(self, df, to_replace, exp):\n # GH 16051\n # DataFrame.replace() overwrites when values are non-numeric\n # also added to data frame whilst issue was for series\n\n df = DataFrame(df)\n\n expected = DataFrame(exp)\n result = df.replace(to_replace)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "replacer",\n [\n Timestamp("20170827"),\n np.int8(1),\n np.int16(1),\n np.float32(1),\n np.float64(1),\n ],\n )\n def test_replace_replacer_dtype(self, replacer):\n # GH26632\n df = DataFrame(["a"], dtype=object)\n msg = "Downcasting behavior in `replace` "\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.replace({"a": replacer, "b": replacer})\n expected = DataFrame([replacer])\n tm.assert_frame_equal(result, expected)\n\n def test_replace_after_convert_dtypes(self):\n # GH31517\n df = DataFrame({"grp": [1, 2, 3, 4, 5]}, dtype="Int64")\n result = df.replace(1, 10)\n expected = DataFrame({"grp": [10, 2, 3, 4, 5]}, dtype="Int64")\n tm.assert_frame_equal(result, expected)\n\n def test_replace_invalid_to_replace(self):\n # GH 18634\n # API: replace() should raise an exception if invalid argument is given\n df = DataFrame({"one": ["a", "b ", "c"], "two": ["d ", "e ", "f "]})\n msg = (\n r"Expecting 'to_replace' to be either a scalar, array-like, "\n r"dict or None, got invalid type.*"\n )\n msg2 = (\n "DataFrame.replace without 'value' and with non-dict-like "\n "'to_replace' is deprecated"\n )\n with pytest.raises(TypeError, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=msg2):\n df.replace(lambda x: x.strip())\n\n @pytest.mark.parametrize("dtype", ["float", "float64", "int64", "Int64", "boolean"])\n @pytest.mark.parametrize("value", [np.nan, pd.NA])\n def test_replace_no_replacement_dtypes(self, dtype, value):\n # https://github.com/pandas-dev/pandas/issues/32988\n df = DataFrame(np.eye(2), dtype=dtype)\n result = df.replace(to_replace=[None, -np.inf, np.inf], value=value)\n tm.assert_frame_equal(result, df)\n\n @pytest.mark.parametrize("replacement", [np.nan, 5])\n def test_replace_with_duplicate_columns(self, replacement):\n # GH 24798\n result = DataFrame({"A": [1, 2, 3], "A1": [4, 5, 6], "B": [7, 8, 9]})\n result.columns = list("AAB")\n\n expected = DataFrame(\n {"A": [1, 2, 3], "A1": [4, 5, 6], "B": [replacement, 8, 9]}\n )\n expected.columns = list("AAB")\n\n result["B"] = result["B"].replace(7, replacement)\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("value", [pd.Period("2020-01"), pd.Interval(0, 5)])\n def test_replace_ea_ignore_float(self, frame_or_series, value):\n # GH#34871\n obj = DataFrame({"Per": [value] * 3})\n obj = tm.get_obj(obj, frame_or_series)\n\n expected = obj.copy()\n result = obj.replace(1.0, 0.0)\n tm.assert_equal(expected, result)\n\n def test_replace_value_category_type(self):\n """\n Test for #23305: to ensure category dtypes are maintained\n after replace with direct values\n """\n\n # create input data\n input_dict = {\n "col1": [1, 2, 3, 4],\n "col2": ["a", "b", "c", "d"],\n "col3": [1.5, 2.5, 3.5, 4.5],\n "col4": ["cat1", "cat2", "cat3", "cat4"],\n "col5": ["obj1", "obj2", "obj3", "obj4"],\n }\n # explicitly cast columns as category and order them\n input_df = DataFrame(data=input_dict).astype(\n {"col2": "category", "col4": "category"}\n )\n input_df["col2"] = input_df["col2"].cat.reorder_categories(\n ["a", "b", "c", "d"], ordered=True\n )\n input_df["col4"] = input_df["col4"].cat.reorder_categories(\n ["cat1", "cat2", "cat3", "cat4"], ordered=True\n )\n\n # create expected dataframe\n expected_dict = {\n "col1": [1, 2, 3, 4],\n "col2": ["a", "b", "c", "z"],\n "col3": [1.5, 2.5, 3.5, 4.5],\n "col4": ["cat1", "catX", "cat3", "cat4"],\n "col5": ["obj9", "obj2", "obj3", "obj4"],\n }\n # explicitly cast columns as category and order them\n expected = DataFrame(data=expected_dict).astype(\n {"col2": "category", "col4": "category"}\n )\n expected["col2"] = expected["col2"].cat.reorder_categories(\n ["a", "b", "c", "z"], ordered=True\n )\n expected["col4"] = expected["col4"].cat.reorder_categories(\n ["cat1", "catX", "cat3", "cat4"], ordered=True\n )\n\n # replace values in input dataframe\n msg = (\n r"The behavior of Series\.replace \(and DataFrame.replace\) "\n "with CategoricalDtype"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n input_df = input_df.replace("d", "z")\n input_df = input_df.replace("obj1", "obj9")\n result = input_df.replace("cat2", "catX")\n\n result = result.astype({"col1": "int64", "col3": "float64", "col5": "str"})\n tm.assert_frame_equal(result, expected)\n\n def test_replace_dict_category_type(self):\n """\n Test to ensure category dtypes are maintained\n after replace with dict values\n """\n # GH#35268, GH#44940\n\n # create input dataframe\n input_dict = {"col1": ["a"], "col2": ["obj1"], "col3": ["cat1"]}\n # explicitly cast columns as category\n input_df = DataFrame(data=input_dict).astype(\n {"col1": "category", "col2": "category", "col3": "category"}\n )\n\n # create expected dataframe\n expected_dict = {"col1": ["z"], "col2": ["obj9"], "col3": ["catX"]}\n # explicitly cast columns as category\n expected = DataFrame(data=expected_dict).astype(\n {"col1": "category", "col2": "category", "col3": "category"}\n )\n\n # replace values in input dataframe using a dict\n msg = (\n r"The behavior of Series\.replace \(and DataFrame.replace\) "\n "with CategoricalDtype"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = input_df.replace({"a": "z", "obj1": "obj9", "cat1": "catX"})\n\n tm.assert_frame_equal(result, expected)\n\n def test_replace_with_compiled_regex(self):\n # https://github.com/pandas-dev/pandas/issues/35680\n df = DataFrame(["a", "b", "c"])\n regex = re.compile("^a$")\n result = df.replace({regex: "z"}, regex=True)\n expected = DataFrame(["z", "b", "c"])\n tm.assert_frame_equal(result, expected)\n\n def test_replace_intervals(self):\n # https://github.com/pandas-dev/pandas/issues/35931\n df = DataFrame({"a": [pd.Interval(0, 1), pd.Interval(0, 1)]})\n result = df.replace({"a": {pd.Interval(0, 1): "x"}})\n expected = DataFrame({"a": ["x", "x"]}, dtype=object)\n tm.assert_frame_equal(result, expected)\n\n def test_replace_unicode(self):\n # GH: 16784\n columns_values_map = {"positive": {"正面": 1, "中立": 1, "负面": 0}}\n df1 = DataFrame({"positive": np.ones(3)})\n result = df1.replace(columns_values_map)\n expected = DataFrame({"positive": np.ones(3)})\n tm.assert_frame_equal(result, expected)\n\n def test_replace_bytes(self, frame_or_series):\n # GH#38900\n obj = frame_or_series(["o"]).astype("|S")\n expected = obj.copy()\n obj = obj.replace({None: np.nan})\n tm.assert_equal(obj, expected)\n\n @pytest.mark.parametrize(\n "data, to_replace, value, expected",\n [\n ([1], [1.0], [0], [0]),\n ([1], [1], [0], [0]),\n ([1.0], [1.0], [0], [0.0]),\n ([1.0], [1], [0], [0.0]),\n ],\n )\n @pytest.mark.parametrize("box", [list, tuple, np.array])\n def test_replace_list_with_mixed_type(\n self, data, to_replace, value, expected, box, frame_or_series\n ):\n # GH#40371\n obj = frame_or_series(data)\n expected = frame_or_series(expected)\n result = obj.replace(box(to_replace), value)\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize("val", [2, np.nan, 2.0])\n def test_replace_value_none_dtype_numeric(self, val):\n # GH#48231\n df = DataFrame({"a": [1, val]})\n result = df.replace(val, None)\n expected = DataFrame({"a": [1, None]}, dtype=object)\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame({"a": [1, val]})\n result = df.replace({val: None})\n tm.assert_frame_equal(result, expected)\n\n def test_replace_with_nil_na(self):\n # GH 32075\n ser = DataFrame({"a": ["nil", pd.NA]})\n expected = DataFrame({"a": ["anything else", pd.NA]}, index=[0, 1])\n result = ser.replace("nil", "anything else")\n tm.assert_frame_equal(expected, result)\n\n\nclass TestDataFrameReplaceRegex:\n @pytest.mark.parametrize(\n "data",\n [\n {"a": list("ab.."), "b": list("efgh")},\n {"a": list("ab.."), "b": list(range(4))},\n ],\n )\n @pytest.mark.parametrize(\n "to_replace,value", [(r"\s*\.\s*", np.nan), (r"\s*(\.)\s*", r"\1\1\1")]\n )\n @pytest.mark.parametrize("compile_regex", [True, False])\n @pytest.mark.parametrize("regex_kwarg", [True, False])\n @pytest.mark.parametrize("inplace", [True, False])\n def test_regex_replace_scalar(\n self, data, to_replace, value, compile_regex, regex_kwarg, inplace\n ):\n df = DataFrame(data)\n expected = df.copy()\n\n if compile_regex:\n to_replace = re.compile(to_replace)\n\n if regex_kwarg:\n regex = to_replace\n to_replace = None\n else:\n regex = True\n\n result = df.replace(to_replace, value, inplace=inplace, regex=regex)\n\n if inplace:\n assert result is None\n result = df\n\n if value is np.nan:\n expected_replace_val = np.nan\n else:\n expected_replace_val = "..."\n\n expected.loc[expected["a"] == ".", "a"] = expected_replace_val\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("regex", [False, True])\n def test_replace_regex_dtype_frame(self, regex):\n # GH-48644\n df1 = DataFrame({"A": ["0"], "B": ["0"]})\n expected_df1 = DataFrame({"A": [1], "B": [1]})\n msg = "Downcasting behavior in `replace`"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result_df1 = df1.replace(to_replace="0", value=1, regex=regex)\n tm.assert_frame_equal(result_df1, expected_df1)\n\n df2 = DataFrame({"A": ["0"], "B": ["1"]})\n expected_df2 = DataFrame({"A": [1], "B": ["1"]})\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result_df2 = df2.replace(to_replace="0", value=1, regex=regex)\n tm.assert_frame_equal(result_df2, expected_df2)\n\n def test_replace_with_value_also_being_replaced(self):\n # GH46306\n df = DataFrame({"A": [0, 1, 2], "B": [1, 0, 2]})\n result = df.replace({0: 1, 1: np.nan})\n expected = DataFrame({"A": [1, np.nan, 2], "B": [np.nan, 1, 2]})\n tm.assert_frame_equal(result, expected)\n\n def test_replace_categorical_no_replacement(self):\n # GH#46672\n df = DataFrame(\n {\n "a": ["one", "two", None, "three"],\n "b": ["one", None, "two", "three"],\n },\n dtype="category",\n )\n expected = df.copy()\n\n result = df.replace(to_replace=[".", "def"], value=["_", None])\n tm.assert_frame_equal(result, expected)\n\n def test_replace_object_splitting(self, using_infer_string):\n # GH#53977\n df = DataFrame({"a": ["a"], "b": "b"})\n if using_infer_string:\n assert len(df._mgr.blocks) == 2\n else:\n assert len(df._mgr.blocks) == 1\n df.replace(to_replace=r"^\s*$", value="", inplace=True, regex=True)\n if using_infer_string:\n assert len(df._mgr.blocks) == 2\n else:\n assert len(df._mgr.blocks) == 1\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_replace.py
test_replace.py
Python
62,755
0.75
0.066667
0.072297
awesome-app
73
2024-03-04T14:22:18.418526
BSD-3-Clause
true
671f3189f2603b7bca04fada4bb0394d
from datetime import datetime\nfrom itertools import product\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nfrom pandas.core.dtypes.common import (\n is_float_dtype,\n is_integer_dtype,\n)\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n CategoricalIndex,\n DataFrame,\n Index,\n Interval,\n IntervalIndex,\n MultiIndex,\n RangeIndex,\n Series,\n Timestamp,\n cut,\n date_range,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture()\ndef multiindex_df():\n levels = [["A", ""], ["B", "b"]]\n return DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels))\n\n\nclass TestResetIndex:\n def test_reset_index_empty_rangeindex(self):\n # GH#45230\n df = DataFrame(\n columns=["brand"], dtype=np.int64, index=RangeIndex(0, 0, 1, name="foo")\n )\n\n df2 = df.set_index([df.index, "brand"])\n\n result = df2.reset_index([1], drop=True)\n tm.assert_frame_equal(result, df[[]], check_index_type=True)\n\n def test_set_reset(self):\n idx = Index([2**63, 2**63 + 5, 2**63 + 10], name="foo")\n\n # set/reset\n df = DataFrame({"A": [0, 1, 2]}, index=idx)\n result = df.reset_index()\n assert result["foo"].dtype == np.dtype("uint64")\n\n df = result.set_index("foo")\n tm.assert_index_equal(df.index, idx)\n\n def test_set_index_reset_index_dt64tz(self):\n idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo")\n\n # set/reset\n df = DataFrame({"A": [0, 1, 2]}, index=idx)\n result = df.reset_index()\n assert result["foo"].dtype == "datetime64[ns, US/Eastern]"\n\n df = result.set_index("foo")\n tm.assert_index_equal(df.index, idx)\n\n def test_reset_index_tz(self, tz_aware_fixture):\n # GH 3950\n # reset_index with single level\n tz = tz_aware_fixture\n idx = date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx")\n df = DataFrame({"a": range(5), "b": ["A", "B", "C", "D", "E"]}, index=idx)\n\n expected = DataFrame(\n {\n "idx": idx,\n "a": range(5),\n "b": ["A", "B", "C", "D", "E"],\n },\n columns=["idx", "a", "b"],\n )\n result = df.reset_index()\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"])\n def test_frame_reset_index_tzaware_index(self, tz):\n dr = date_range("2012-06-02", periods=10, tz=tz)\n df = DataFrame(np.random.default_rng(2).standard_normal(len(dr)), dr)\n roundtripped = df.reset_index().set_index("index")\n xp = df.index.tz\n rs = roundtripped.index.tz\n assert xp == rs\n\n def test_reset_index_with_intervals(self):\n idx = IntervalIndex.from_breaks(np.arange(11), name="x")\n original = DataFrame({"x": idx, "y": np.arange(10)})[["x", "y"]]\n\n result = original.set_index("x")\n expected = DataFrame({"y": np.arange(10)}, index=idx)\n tm.assert_frame_equal(result, expected)\n\n result2 = result.reset_index()\n tm.assert_frame_equal(result2, original)\n\n def test_reset_index(self, float_frame):\n stacked = float_frame.stack(future_stack=True)[::2]\n stacked = DataFrame({"foo": stacked, "bar": stacked})\n\n names = ["first", "second"]\n stacked.index.names = names\n deleveled = stacked.reset_index()\n for i, (lev, level_codes) in enumerate(\n zip(stacked.index.levels, stacked.index.codes)\n ):\n values = lev.take(level_codes)\n name = names[i]\n tm.assert_index_equal(values, Index(deleveled[name]))\n\n stacked.index.names = [None, None]\n deleveled2 = stacked.reset_index()\n tm.assert_series_equal(\n deleveled["first"], deleveled2["level_0"], check_names=False\n )\n tm.assert_series_equal(\n deleveled["second"], deleveled2["level_1"], check_names=False\n )\n\n # default name assigned\n rdf = float_frame.reset_index()\n exp = Series(float_frame.index.values, name="index")\n tm.assert_series_equal(rdf["index"], exp)\n\n # default name assigned, corner case\n df = float_frame.copy()\n df["index"] = "foo"\n rdf = df.reset_index()\n exp = Series(float_frame.index.values, name="level_0")\n tm.assert_series_equal(rdf["level_0"], exp)\n\n # but this is ok\n float_frame.index.name = "index"\n deleveled = float_frame.reset_index()\n tm.assert_series_equal(deleveled["index"], Series(float_frame.index))\n tm.assert_index_equal(deleveled.index, Index(range(len(deleveled))), exact=True)\n\n # preserve column names\n float_frame.columns.name = "columns"\n reset = float_frame.reset_index()\n assert reset.columns.name == "columns"\n\n # only remove certain columns\n df = float_frame.reset_index().set_index(["index", "A", "B"])\n rs = df.reset_index(["A", "B"])\n\n tm.assert_frame_equal(rs, float_frame)\n\n rs = df.reset_index(["index", "A", "B"])\n tm.assert_frame_equal(rs, float_frame.reset_index())\n\n rs = df.reset_index(["index", "A", "B"])\n tm.assert_frame_equal(rs, float_frame.reset_index())\n\n rs = df.reset_index("A")\n xp = float_frame.reset_index().set_index(["index", "B"])\n tm.assert_frame_equal(rs, xp)\n\n # test resetting in place\n df = float_frame.copy()\n reset = float_frame.reset_index()\n return_value = df.reset_index(inplace=True)\n assert return_value is None\n tm.assert_frame_equal(df, reset)\n\n df = float_frame.reset_index().set_index(["index", "A", "B"])\n rs = df.reset_index("A", drop=True)\n xp = float_frame.copy()\n del xp["A"]\n xp = xp.set_index(["B"], append=True)\n tm.assert_frame_equal(rs, xp)\n\n def test_reset_index_name(self):\n df = DataFrame(\n [[1, 2, 3, 4], [5, 6, 7, 8]],\n columns=["A", "B", "C", "D"],\n index=Index(range(2), name="x"),\n )\n assert df.reset_index().index.name is None\n assert df.reset_index(drop=True).index.name is None\n return_value = df.reset_index(inplace=True)\n assert return_value is None\n assert df.index.name is None\n\n @pytest.mark.parametrize("levels", [["A", "B"], [0, 1]])\n def test_reset_index_level(self, levels):\n df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "C", "D"])\n\n # With MultiIndex\n result = df.set_index(["A", "B"]).reset_index(level=levels[0])\n tm.assert_frame_equal(result, df.set_index("B"))\n\n result = df.set_index(["A", "B"]).reset_index(level=levels[:1])\n tm.assert_frame_equal(result, df.set_index("B"))\n\n result = df.set_index(["A", "B"]).reset_index(level=levels)\n tm.assert_frame_equal(result, df)\n\n result = df.set_index(["A", "B"]).reset_index(level=levels, drop=True)\n tm.assert_frame_equal(result, df[["C", "D"]])\n\n # With single-level Index (GH 16263)\n result = df.set_index("A").reset_index(level=levels[0])\n tm.assert_frame_equal(result, df)\n\n result = df.set_index("A").reset_index(level=levels[:1])\n tm.assert_frame_equal(result, df)\n\n result = df.set_index(["A"]).reset_index(level=levels[0], drop=True)\n tm.assert_frame_equal(result, df[["B", "C", "D"]])\n\n @pytest.mark.parametrize("idx_lev", [["A", "B"], ["A"]])\n def test_reset_index_level_missing(self, idx_lev):\n # Missing levels - for both MultiIndex and single-level Index:\n df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "C", "D"])\n\n with pytest.raises(KeyError, match=r"(L|l)evel \(?E\)?"):\n df.set_index(idx_lev).reset_index(level=["A", "E"])\n with pytest.raises(IndexError, match="Too many levels"):\n df.set_index(idx_lev).reset_index(level=[0, 1, 2])\n\n def test_reset_index_right_dtype(self):\n time = np.arange(0.0, 10, np.sqrt(2) / 2)\n s1 = Series(\n (9.81 * time**2) / 2, index=Index(time, name="time"), name="speed"\n )\n df = DataFrame(s1)\n\n reset = s1.reset_index()\n assert reset["time"].dtype == np.float64\n\n reset = df.reset_index()\n assert reset["time"].dtype == np.float64\n\n def test_reset_index_multiindex_col(self):\n vals = np.random.default_rng(2).standard_normal((3, 3)).astype(object)\n idx = ["x", "y", "z"]\n full = np.hstack(([[x] for x in idx], vals))\n df = DataFrame(\n vals,\n Index(idx, name="a"),\n columns=[["b", "b", "c"], ["mean", "median", "mean"]],\n )\n rs = df.reset_index()\n xp = DataFrame(\n full, columns=[["a", "b", "b", "c"], ["", "mean", "median", "mean"]]\n )\n tm.assert_frame_equal(rs, xp)\n\n rs = df.reset_index(col_fill=None)\n xp = DataFrame(\n full, columns=[["a", "b", "b", "c"], ["a", "mean", "median", "mean"]]\n )\n tm.assert_frame_equal(rs, xp)\n\n rs = df.reset_index(col_level=1, col_fill="blah")\n xp = DataFrame(\n full, columns=[["blah", "b", "b", "c"], ["a", "mean", "median", "mean"]]\n )\n tm.assert_frame_equal(rs, xp)\n\n df = DataFrame(\n vals,\n MultiIndex.from_arrays([[0, 1, 2], ["x", "y", "z"]], names=["d", "a"]),\n columns=[["b", "b", "c"], ["mean", "median", "mean"]],\n )\n rs = df.reset_index("a")\n xp = DataFrame(\n full,\n Index([0, 1, 2], name="d"),\n columns=[["a", "b", "b", "c"], ["", "mean", "median", "mean"]],\n )\n tm.assert_frame_equal(rs, xp)\n\n rs = df.reset_index("a", col_fill=None)\n xp = DataFrame(\n full,\n Index(range(3), name="d"),\n columns=[["a", "b", "b", "c"], ["a", "mean", "median", "mean"]],\n )\n tm.assert_frame_equal(rs, xp)\n\n rs = df.reset_index("a", col_fill="blah", col_level=1)\n xp = DataFrame(\n full,\n Index(range(3), name="d"),\n columns=[["blah", "b", "b", "c"], ["a", "mean", "median", "mean"]],\n )\n tm.assert_frame_equal(rs, xp)\n\n def test_reset_index_multiindex_nan(self):\n # GH#6322, testing reset_index on MultiIndexes\n # when we have a nan or all nan\n df = DataFrame(\n {\n "A": ["a", "b", "c"],\n "B": [0, 1, np.nan],\n "C": np.random.default_rng(2).random(3),\n }\n )\n rs = df.set_index(["A", "B"]).reset_index()\n tm.assert_frame_equal(rs, df)\n\n df = DataFrame(\n {\n "A": [np.nan, "b", "c"],\n "B": [0, 1, 2],\n "C": np.random.default_rng(2).random(3),\n }\n )\n rs = df.set_index(["A", "B"]).reset_index()\n tm.assert_frame_equal(rs, df)\n\n df = DataFrame({"A": ["a", "b", "c"], "B": [0, 1, 2], "C": [np.nan, 1.1, 2.2]})\n rs = df.set_index(["A", "B"]).reset_index()\n tm.assert_frame_equal(rs, df)\n\n df = DataFrame(\n {\n "A": ["a", "b", "c"],\n "B": [np.nan, np.nan, np.nan],\n "C": np.random.default_rng(2).random(3),\n }\n )\n rs = df.set_index(["A", "B"]).reset_index()\n tm.assert_frame_equal(rs, df)\n\n @pytest.mark.parametrize(\n "name",\n [\n None,\n "foo",\n 2,\n 3.0,\n pd.Timedelta(6),\n Timestamp("2012-12-30", tz="UTC"),\n "2012-12-31",\n ],\n )\n def test_reset_index_with_datetimeindex_cols(self, name):\n # GH#5818\n df = DataFrame(\n [[1, 2], [3, 4]],\n columns=date_range("1/1/2013", "1/2/2013"),\n index=["A", "B"],\n )\n df.index.name = name\n\n result = df.reset_index()\n\n item = name if name is not None else "index"\n columns = Index([item, datetime(2013, 1, 1), datetime(2013, 1, 2)])\n if isinstance(item, str) and item == "2012-12-31":\n columns = columns.astype("datetime64[ns]")\n else:\n assert columns.dtype == object\n\n expected = DataFrame(\n [["A", 1, 2], ["B", 3, 4]],\n columns=columns,\n )\n tm.assert_frame_equal(result, expected)\n\n def test_reset_index_range(self):\n # GH#12071\n df = DataFrame([[0, 0], [1, 1]], columns=["A", "B"], index=RangeIndex(stop=2))\n result = df.reset_index()\n assert isinstance(result.index, RangeIndex)\n expected = DataFrame(\n [[0, 0, 0], [1, 1, 1]],\n columns=["index", "A", "B"],\n index=RangeIndex(stop=2),\n )\n tm.assert_frame_equal(result, expected)\n\n def test_reset_index_multiindex_columns(self, multiindex_df):\n result = multiindex_df[["B"]].rename_axis("A").reset_index()\n tm.assert_frame_equal(result, multiindex_df)\n\n # GH#16120: already existing column\n msg = r"cannot insert \('A', ''\), already exists"\n with pytest.raises(ValueError, match=msg):\n multiindex_df.rename_axis("A").reset_index()\n\n # GH#16164: multiindex (tuple) full key\n result = multiindex_df.set_index([("A", "")]).reset_index()\n tm.assert_frame_equal(result, multiindex_df)\n\n # with additional (unnamed) index level\n idx_col = DataFrame(\n [[0], [1]], columns=MultiIndex.from_tuples([("level_0", "")])\n )\n expected = pd.concat([idx_col, multiindex_df[[("B", "b"), ("A", "")]]], axis=1)\n result = multiindex_df.set_index([("B", "b")], append=True).reset_index()\n tm.assert_frame_equal(result, expected)\n\n # with index name which is a too long tuple...\n msg = "Item must have length equal to number of levels."\n with pytest.raises(ValueError, match=msg):\n multiindex_df.rename_axis([("C", "c", "i")]).reset_index()\n\n # or too short...\n levels = [["A", "a", ""], ["B", "b", "i"]]\n df2 = DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels))\n idx_col = DataFrame(\n [[0], [1]], columns=MultiIndex.from_tuples([("C", "c", "ii")])\n )\n expected = pd.concat([idx_col, df2], axis=1)\n result = df2.rename_axis([("C", "c")]).reset_index(col_fill="ii")\n tm.assert_frame_equal(result, expected)\n\n # ... which is incompatible with col_fill=None\n with pytest.raises(\n ValueError,\n match=(\n "col_fill=None is incompatible with "\n r"incomplete column name \('C', 'c'\)"\n ),\n ):\n df2.rename_axis([("C", "c")]).reset_index(col_fill=None)\n\n # with col_level != 0\n result = df2.rename_axis([("c", "ii")]).reset_index(col_level=1, col_fill="C")\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("flag", [False, True])\n @pytest.mark.parametrize("allow_duplicates", [False, True])\n def test_reset_index_duplicate_columns_allow(\n self, multiindex_df, flag, allow_duplicates\n ):\n # GH#44755 reset_index with duplicate column labels\n df = multiindex_df.rename_axis("A")\n df = df.set_flags(allows_duplicate_labels=flag)\n\n if flag and allow_duplicates:\n result = df.reset_index(allow_duplicates=allow_duplicates)\n levels = [["A", ""], ["A", ""], ["B", "b"]]\n expected = DataFrame(\n [[0, 0, 2], [1, 1, 3]], columns=MultiIndex.from_tuples(levels)\n )\n tm.assert_frame_equal(result, expected)\n else:\n if not flag and allow_duplicates:\n msg = (\n "Cannot specify 'allow_duplicates=True' when "\n "'self.flags.allows_duplicate_labels' is False"\n )\n else:\n msg = r"cannot insert \('A', ''\), already exists"\n with pytest.raises(ValueError, match=msg):\n df.reset_index(allow_duplicates=allow_duplicates)\n\n @pytest.mark.parametrize("flag", [False, True])\n def test_reset_index_duplicate_columns_default(self, multiindex_df, flag):\n df = multiindex_df.rename_axis("A")\n df = df.set_flags(allows_duplicate_labels=flag)\n\n msg = r"cannot insert \('A', ''\), already exists"\n with pytest.raises(ValueError, match=msg):\n df.reset_index()\n\n @pytest.mark.parametrize("allow_duplicates", ["bad value"])\n def test_reset_index_allow_duplicates_check(self, multiindex_df, allow_duplicates):\n with pytest.raises(ValueError, match="expected type bool"):\n multiindex_df.reset_index(allow_duplicates=allow_duplicates)\n\n def test_reset_index_datetime(self, tz_naive_fixture):\n # GH#3950\n tz = tz_naive_fixture\n idx1 = date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx1")\n idx2 = Index(range(5), name="idx2", dtype="int64")\n idx = MultiIndex.from_arrays([idx1, idx2])\n df = DataFrame(\n {"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]},\n index=idx,\n )\n\n expected = DataFrame(\n {\n "idx1": idx1,\n "idx2": np.arange(5, dtype="int64"),\n "a": np.arange(5, dtype="int64"),\n "b": ["A", "B", "C", "D", "E"],\n },\n columns=["idx1", "idx2", "a", "b"],\n )\n\n tm.assert_frame_equal(df.reset_index(), expected)\n\n def test_reset_index_datetime2(self, tz_naive_fixture):\n tz = tz_naive_fixture\n idx1 = date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx1")\n idx2 = Index(range(5), name="idx2", dtype="int64")\n idx3 = date_range(\n "1/1/2012", periods=5, freq="MS", tz="Europe/Paris", name="idx3"\n )\n idx = MultiIndex.from_arrays([idx1, idx2, idx3])\n df = DataFrame(\n {"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]},\n index=idx,\n )\n\n expected = DataFrame(\n {\n "idx1": idx1,\n "idx2": np.arange(5, dtype="int64"),\n "idx3": idx3,\n "a": np.arange(5, dtype="int64"),\n "b": ["A", "B", "C", "D", "E"],\n },\n columns=["idx1", "idx2", "idx3", "a", "b"],\n )\n result = df.reset_index()\n tm.assert_frame_equal(result, expected)\n\n def test_reset_index_datetime3(self, tz_naive_fixture):\n # GH#7793\n tz = tz_naive_fixture\n dti = date_range("20130101", periods=3, tz=tz)\n idx = MultiIndex.from_product([["a", "b"], dti])\n df = DataFrame(\n np.arange(6, dtype="int64").reshape(6, 1), columns=["a"], index=idx\n )\n\n expected = DataFrame(\n {\n "level_0": "a a a b b b".split(),\n "level_1": dti.append(dti),\n "a": np.arange(6, dtype="int64"),\n },\n columns=["level_0", "level_1", "a"],\n )\n result = df.reset_index()\n tm.assert_frame_equal(result, expected)\n\n def test_reset_index_period(self):\n # GH#7746\n idx = MultiIndex.from_product(\n [pd.period_range("20130101", periods=3, freq="M"), list("abc")],\n names=["month", "feature"],\n )\n\n df = DataFrame(\n np.arange(9, dtype="int64").reshape(-1, 1), index=idx, columns=["a"]\n )\n expected = DataFrame(\n {\n "month": (\n [pd.Period("2013-01", freq="M")] * 3\n + [pd.Period("2013-02", freq="M")] * 3\n + [pd.Period("2013-03", freq="M")] * 3\n ),\n "feature": ["a", "b", "c"] * 3,\n "a": np.arange(9, dtype="int64"),\n },\n columns=["month", "feature", "a"],\n )\n result = df.reset_index()\n tm.assert_frame_equal(result, expected)\n\n def test_reset_index_delevel_infer_dtype(self):\n tuples = list(product(["foo", "bar"], [10, 20], [1.0, 1.1]))\n index = MultiIndex.from_tuples(tuples, names=["prm0", "prm1", "prm2"])\n df = DataFrame(\n np.random.default_rng(2).standard_normal((8, 3)),\n columns=["A", "B", "C"],\n index=index,\n )\n deleveled = df.reset_index()\n assert is_integer_dtype(deleveled["prm1"])\n assert is_float_dtype(deleveled["prm2"])\n\n def test_reset_index_with_drop(\n self, multiindex_year_month_day_dataframe_random_data\n ):\n ymd = multiindex_year_month_day_dataframe_random_data\n\n deleveled = ymd.reset_index(drop=True)\n assert len(deleveled.columns) == len(ymd.columns)\n assert deleveled.index.name == ymd.index.name\n\n @pytest.mark.parametrize(\n "ix_data, exp_data",\n [\n (\n [(pd.NaT, 1), (pd.NaT, 2)],\n {"a": [pd.NaT, pd.NaT], "b": [1, 2], "x": [11, 12]},\n ),\n (\n [(pd.NaT, 1), (Timestamp("2020-01-01"), 2)],\n {"a": [pd.NaT, Timestamp("2020-01-01")], "b": [1, 2], "x": [11, 12]},\n ),\n (\n [(pd.NaT, 1), (pd.Timedelta(123, "d"), 2)],\n {"a": [pd.NaT, pd.Timedelta(123, "d")], "b": [1, 2], "x": [11, 12]},\n ),\n ],\n )\n def test_reset_index_nat_multiindex(self, ix_data, exp_data):\n # GH#36541: that reset_index() does not raise ValueError\n ix = MultiIndex.from_tuples(ix_data, names=["a", "b"])\n result = DataFrame({"x": [11, 12]}, index=ix)\n result = result.reset_index()\n\n expected = DataFrame(exp_data)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "codes", ([[0, 0, 1, 1], [0, 1, 0, 1]], [[0, 0, -1, 1], [0, 1, 0, 1]])\n )\n def test_rest_index_multiindex_categorical_with_missing_values(self, codes):\n # GH#24206\n\n index = MultiIndex(\n [CategoricalIndex(["A", "B"]), CategoricalIndex(["a", "b"])], codes\n )\n data = {"col": range(len(index))}\n df = DataFrame(data=data, index=index)\n\n expected = DataFrame(\n {\n "level_0": Categorical.from_codes(codes[0], categories=["A", "B"]),\n "level_1": Categorical.from_codes(codes[1], categories=["a", "b"]),\n "col": range(4),\n }\n )\n\n res = df.reset_index()\n tm.assert_frame_equal(res, expected)\n\n # roundtrip\n res = expected.set_index(["level_0", "level_1"]).reset_index()\n tm.assert_frame_equal(res, expected)\n\n\n@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string) - GH#60338")\n@pytest.mark.parametrize(\n "array, dtype",\n [\n (["a", "b"], object),\n (\n pd.period_range("12-1-2000", periods=2, freq="Q-DEC"),\n pd.PeriodDtype(freq="Q-DEC"),\n ),\n ],\n)\ndef test_reset_index_dtypes_on_empty_frame_with_multiindex(\n array, dtype, using_infer_string\n):\n # GH 19602 - Preserve dtype on empty DataFrame with MultiIndex\n idx = MultiIndex.from_product([[0, 1], [0.5, 1.0], array])\n result = DataFrame(index=idx)[:0].reset_index().dtypes\n if using_infer_string and dtype == object:\n dtype = pd.StringDtype(na_value=np.nan)\n expected = Series({"level_0": np.int64, "level_1": np.float64, "level_2": dtype})\n tm.assert_series_equal(result, expected)\n\n\ndef test_reset_index_empty_frame_with_datetime64_multiindex():\n # https://github.com/pandas-dev/pandas/issues/35606\n dti = pd.DatetimeIndex(["2020-07-20 00:00:00"], dtype="M8[ns]")\n idx = MultiIndex.from_product([dti, [3, 4]], names=["a", "b"])[:0]\n df = DataFrame(index=idx, columns=["c", "d"])\n result = df.reset_index()\n expected = DataFrame(\n columns=list("abcd"), index=RangeIndex(start=0, stop=0, step=1)\n )\n expected["a"] = expected["a"].astype("datetime64[ns]")\n expected["b"] = expected["b"].astype("int64")\n tm.assert_frame_equal(result, expected)\n\n\ndef test_reset_index_empty_frame_with_datetime64_multiindex_from_groupby(\n using_infer_string,\n):\n # https://github.com/pandas-dev/pandas/issues/35657\n dti = pd.DatetimeIndex(["2020-01-01"], dtype="M8[ns]")\n df = DataFrame({"c1": [10.0], "c2": ["a"], "c3": dti})\n df = df.head(0).groupby(["c2", "c3"])[["c1"]].sum()\n result = df.reset_index()\n expected = DataFrame(\n columns=["c2", "c3", "c1"], index=RangeIndex(start=0, stop=0, step=1)\n )\n expected["c3"] = expected["c3"].astype("datetime64[ns]")\n expected["c1"] = expected["c1"].astype("float64")\n if using_infer_string:\n expected["c2"] = expected["c2"].astype("str")\n tm.assert_frame_equal(result, expected)\n\n\ndef test_reset_index_multiindex_nat():\n # GH 11479\n idx = range(3)\n tstamp = date_range("2015-07-01", freq="D", periods=3)\n df = DataFrame({"id": idx, "tstamp": tstamp, "a": list("abc")})\n df.loc[2, "tstamp"] = pd.NaT\n result = df.set_index(["id", "tstamp"]).reset_index("id")\n exp_dti = pd.DatetimeIndex(\n ["2015-07-01", "2015-07-02", "NaT"], dtype="M8[ns]", name="tstamp"\n )\n expected = DataFrame(\n {"id": range(3), "a": list("abc")},\n index=exp_dti,\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_reset_index_interval_columns_object_cast():\n # GH 19136\n df = DataFrame(\n np.eye(2), index=Index([1, 2], name="Year"), columns=cut([1, 2], [0, 1, 2])\n )\n result = df.reset_index()\n expected = DataFrame(\n [[1, 1.0, 0.0], [2, 0.0, 1.0]],\n columns=Index(["Year", Interval(0, 1), Interval(1, 2)]),\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_reset_index_rename(float_frame):\n # GH 6878\n result = float_frame.reset_index(names="new_name")\n expected = Series(float_frame.index.values, name="new_name")\n tm.assert_series_equal(result["new_name"], expected)\n\n result = float_frame.reset_index(names=123)\n expected = Series(float_frame.index.values, name=123)\n tm.assert_series_equal(result[123], expected)\n\n\ndef test_reset_index_rename_multiindex(float_frame):\n # GH 6878\n stacked_df = float_frame.stack(future_stack=True)[::2]\n stacked_df = DataFrame({"foo": stacked_df, "bar": stacked_df})\n\n names = ["first", "second"]\n stacked_df.index.names = names\n\n result = stacked_df.reset_index()\n expected = stacked_df.reset_index(names=["new_first", "new_second"])\n tm.assert_series_equal(result["first"], expected["new_first"], check_names=False)\n tm.assert_series_equal(result["second"], expected["new_second"], check_names=False)\n\n\ndef test_errorreset_index_rename(float_frame):\n # GH 6878\n stacked_df = float_frame.stack(future_stack=True)[::2]\n stacked_df = DataFrame({"first": stacked_df, "second": stacked_df})\n\n with pytest.raises(\n ValueError, match="Index names must be str or 1-dimensional list"\n ):\n stacked_df.reset_index(names={"first": "new_first", "second": "new_second"})\n\n with pytest.raises(IndexError, match="list index out of range"):\n stacked_df.reset_index(names=["new_first"])\n\n\ndef test_reset_index_false_index_name():\n result_series = Series(data=range(5, 10), index=range(5))\n result_series.index.name = False\n result_series.reset_index()\n expected_series = Series(range(5, 10), RangeIndex(range(5), name=False))\n tm.assert_series_equal(result_series, expected_series)\n\n # GH 38147\n result_frame = DataFrame(data=range(5, 10), index=range(5))\n result_frame.index.name = False\n result_frame.reset_index()\n expected_frame = DataFrame(range(5, 10), RangeIndex(range(5), name=False))\n tm.assert_frame_equal(result_frame, expected_frame)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_reset_index.py
test_reset_index.py
Python
28,064
0.95
0.059873
0.061747
node-utils
77
2024-11-15T20:19:34.606313
Apache-2.0
true
f100cc87f7b59f721b354d00eecc4ce1
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameRound:\n def test_round(self):\n # GH#2665\n\n # Test that rounding an empty DataFrame does nothing\n df = DataFrame()\n tm.assert_frame_equal(df, df.round())\n\n # Here's the test frame we'll be working with\n df = DataFrame({"col1": [1.123, 2.123, 3.123], "col2": [1.234, 2.234, 3.234]})\n\n # Default round to integer (i.e. decimals=0)\n expected_rounded = DataFrame({"col1": [1.0, 2.0, 3.0], "col2": [1.0, 2.0, 3.0]})\n tm.assert_frame_equal(df.round(), expected_rounded)\n\n # Round with an integer\n decimals = 2\n expected_rounded = DataFrame(\n {"col1": [1.12, 2.12, 3.12], "col2": [1.23, 2.23, 3.23]}\n )\n tm.assert_frame_equal(df.round(decimals), expected_rounded)\n\n # This should also work with np.round (since np.round dispatches to\n # df.round)\n tm.assert_frame_equal(np.round(df, decimals), expected_rounded)\n\n # Round with a list\n round_list = [1, 2]\n msg = "decimals must be an integer, a dict-like or a Series"\n with pytest.raises(TypeError, match=msg):\n df.round(round_list)\n\n # Round with a dictionary\n expected_rounded = DataFrame(\n {"col1": [1.1, 2.1, 3.1], "col2": [1.23, 2.23, 3.23]}\n )\n round_dict = {"col1": 1, "col2": 2}\n tm.assert_frame_equal(df.round(round_dict), expected_rounded)\n\n # Incomplete dict\n expected_partially_rounded = DataFrame(\n {"col1": [1.123, 2.123, 3.123], "col2": [1.2, 2.2, 3.2]}\n )\n partial_round_dict = {"col2": 1}\n tm.assert_frame_equal(df.round(partial_round_dict), expected_partially_rounded)\n\n # Dict with unknown elements\n wrong_round_dict = {"col3": 2, "col2": 1}\n tm.assert_frame_equal(df.round(wrong_round_dict), expected_partially_rounded)\n\n # float input to `decimals`\n non_int_round_dict = {"col1": 1, "col2": 0.5}\n msg = "Values in decimals must be integers"\n with pytest.raises(TypeError, match=msg):\n df.round(non_int_round_dict)\n\n # String input\n non_int_round_dict = {"col1": 1, "col2": "foo"}\n with pytest.raises(TypeError, match=msg):\n df.round(non_int_round_dict)\n\n non_int_round_Series = Series(non_int_round_dict)\n with pytest.raises(TypeError, match=msg):\n df.round(non_int_round_Series)\n\n # List input\n non_int_round_dict = {"col1": 1, "col2": [1, 2]}\n with pytest.raises(TypeError, match=msg):\n df.round(non_int_round_dict)\n\n non_int_round_Series = Series(non_int_round_dict)\n with pytest.raises(TypeError, match=msg):\n df.round(non_int_round_Series)\n\n # Non integer Series inputs\n non_int_round_Series = Series(non_int_round_dict)\n with pytest.raises(TypeError, match=msg):\n df.round(non_int_round_Series)\n\n non_int_round_Series = Series(non_int_round_dict)\n with pytest.raises(TypeError, match=msg):\n df.round(non_int_round_Series)\n\n # Negative numbers\n negative_round_dict = {"col1": -1, "col2": -2}\n big_df = df * 100\n expected_neg_rounded = DataFrame(\n {"col1": [110.0, 210, 310], "col2": [100.0, 200, 300]}\n )\n tm.assert_frame_equal(big_df.round(negative_round_dict), expected_neg_rounded)\n\n # nan in Series round\n nan_round_Series = Series({"col1": np.nan, "col2": 1})\n\n with pytest.raises(TypeError, match=msg):\n df.round(nan_round_Series)\n\n # Make sure this doesn't break existing Series.round\n tm.assert_series_equal(df["col1"].round(1), expected_rounded["col1"])\n\n # named columns\n # GH#11986\n decimals = 2\n expected_rounded = DataFrame(\n {"col1": [1.12, 2.12, 3.12], "col2": [1.23, 2.23, 3.23]}\n )\n df.columns.name = "cols"\n expected_rounded.columns.name = "cols"\n tm.assert_frame_equal(df.round(decimals), expected_rounded)\n\n # interaction of named columns & series\n tm.assert_series_equal(df["col1"].round(decimals), expected_rounded["col1"])\n tm.assert_series_equal(df.round(decimals)["col1"], expected_rounded["col1"])\n\n def test_round_numpy(self):\n # GH#12600\n df = DataFrame([[1.53, 1.36], [0.06, 7.01]])\n out = np.round(df, decimals=0)\n expected = DataFrame([[2.0, 1.0], [0.0, 7.0]])\n tm.assert_frame_equal(out, expected)\n\n msg = "the 'out' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.round(df, decimals=0, out=df)\n\n def test_round_numpy_with_nan(self):\n # See GH#14197\n df = Series([1.53, np.nan, 0.06]).to_frame()\n with tm.assert_produces_warning(None):\n result = df.round()\n expected = Series([2.0, np.nan, 0.0]).to_frame()\n tm.assert_frame_equal(result, expected)\n\n def test_round_mixed_type(self):\n # GH#11885\n df = DataFrame(\n {\n "col1": [1.1, 2.2, 3.3, 4.4],\n "col2": ["1", "a", "c", "f"],\n "col3": date_range("20111111", periods=4),\n }\n )\n round_0 = DataFrame(\n {\n "col1": [1.0, 2.0, 3.0, 4.0],\n "col2": ["1", "a", "c", "f"],\n "col3": date_range("20111111", periods=4),\n }\n )\n tm.assert_frame_equal(df.round(), round_0)\n tm.assert_frame_equal(df.round(1), df)\n tm.assert_frame_equal(df.round({"col1": 1}), df)\n tm.assert_frame_equal(df.round({"col1": 0}), round_0)\n tm.assert_frame_equal(df.round({"col1": 0, "col2": 1}), round_0)\n tm.assert_frame_equal(df.round({"col3": 1}), df)\n\n def test_round_with_duplicate_columns(self):\n # GH#11611\n\n df = DataFrame(\n np.random.default_rng(2).random([3, 3]),\n columns=["A", "B", "C"],\n index=["first", "second", "third"],\n )\n\n dfs = pd.concat((df, df), axis=1)\n rounded = dfs.round()\n tm.assert_index_equal(rounded.index, dfs.index)\n\n decimals = Series([1, 0, 2], index=["A", "B", "A"])\n msg = "Index of decimals must be unique"\n with pytest.raises(ValueError, match=msg):\n df.round(decimals)\n\n def test_round_builtin(self):\n # GH#11763\n # Here's the test frame we'll be working with\n df = DataFrame({"col1": [1.123, 2.123, 3.123], "col2": [1.234, 2.234, 3.234]})\n\n # Default round to integer (i.e. decimals=0)\n expected_rounded = DataFrame({"col1": [1.0, 2.0, 3.0], "col2": [1.0, 2.0, 3.0]})\n tm.assert_frame_equal(round(df), expected_rounded)\n\n def test_round_nonunique_categorical(self):\n # See GH#21809\n idx = pd.CategoricalIndex(["low"] * 3 + ["hi"] * 3)\n df = DataFrame(np.random.default_rng(2).random((6, 3)), columns=list("abc"))\n\n expected = df.round(3)\n expected.index = idx\n\n df_categorical = df.copy().set_index(idx)\n assert df_categorical.shape == (6, 3)\n result = df_categorical.round(3)\n assert result.shape == (6, 3)\n\n tm.assert_frame_equal(result, expected)\n\n def test_round_interval_category_columns(self):\n # GH#30063\n columns = pd.CategoricalIndex(pd.interval_range(0, 2))\n df = DataFrame([[0.66, 1.1], [0.3, 0.25]], columns=columns)\n\n result = df.round()\n expected = DataFrame([[1.0, 1.0], [0.0, 0.0]], columns=columns)\n tm.assert_frame_equal(result, expected)\n\n def test_round_empty_not_input(self):\n # GH#51032\n df = DataFrame()\n result = df.round()\n tm.assert_frame_equal(df, result)\n assert df is not result\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_round.py
test_round.py
Python
7,978
0.95
0.044444
0.169399
python-kit
207
2024-08-14T15:28:29.741101
MIT
true
952490a6951dfcfbba1a505d1d741b0a
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n)\nimport pandas._testing as tm\nimport pandas.core.common as com\n\n\nclass TestSample:\n @pytest.fixture\n def obj(self, frame_or_series):\n if frame_or_series is Series:\n arr = np.random.default_rng(2).standard_normal(10)\n else:\n arr = np.random.default_rng(2).standard_normal((10, 10))\n return frame_or_series(arr, dtype=None)\n\n @pytest.mark.parametrize("test", list(range(10)))\n def test_sample(self, test, obj):\n # Fixes issue: 2419\n # Check behavior of random_state argument\n # Check for stability when receives seed or random state -- run 10\n # times.\n\n seed = np.random.default_rng(2).integers(0, 100)\n tm.assert_equal(\n obj.sample(n=4, random_state=seed), obj.sample(n=4, random_state=seed)\n )\n\n tm.assert_equal(\n obj.sample(frac=0.7, random_state=seed),\n obj.sample(frac=0.7, random_state=seed),\n )\n\n tm.assert_equal(\n obj.sample(n=4, random_state=np.random.default_rng(test)),\n obj.sample(n=4, random_state=np.random.default_rng(test)),\n )\n\n tm.assert_equal(\n obj.sample(frac=0.7, random_state=np.random.default_rng(test)),\n obj.sample(frac=0.7, random_state=np.random.default_rng(test)),\n )\n\n tm.assert_equal(\n obj.sample(\n frac=2,\n replace=True,\n random_state=np.random.default_rng(test),\n ),\n obj.sample(\n frac=2,\n replace=True,\n random_state=np.random.default_rng(test),\n ),\n )\n\n os1, os2 = [], []\n for _ in range(2):\n os1.append(obj.sample(n=4, random_state=test))\n os2.append(obj.sample(frac=0.7, random_state=test))\n tm.assert_equal(*os1)\n tm.assert_equal(*os2)\n\n def test_sample_lengths(self, obj):\n # Check lengths are right\n assert len(obj.sample(n=4) == 4)\n assert len(obj.sample(frac=0.34) == 3)\n assert len(obj.sample(frac=0.36) == 4)\n\n def test_sample_invalid_random_state(self, obj):\n # Check for error when random_state argument invalid.\n msg = (\n "random_state must be an integer, array-like, a BitGenerator, Generator, "\n "a numpy RandomState, or None"\n )\n with pytest.raises(ValueError, match=msg):\n obj.sample(random_state="a_string")\n\n def test_sample_wont_accept_n_and_frac(self, obj):\n # Giving both frac and N throws error\n msg = "Please enter a value for `frac` OR `n`, not both"\n with pytest.raises(ValueError, match=msg):\n obj.sample(n=3, frac=0.3)\n\n def test_sample_requires_positive_n_frac(self, obj):\n with pytest.raises(\n ValueError,\n match="A negative number of rows requested. Please provide `n` >= 0",\n ):\n obj.sample(n=-3)\n with pytest.raises(\n ValueError,\n match="A negative number of rows requested. Please provide `frac` >= 0",\n ):\n obj.sample(frac=-0.3)\n\n def test_sample_requires_integer_n(self, obj):\n # Make sure float values of `n` give error\n with pytest.raises(ValueError, match="Only integers accepted as `n` values"):\n obj.sample(n=3.2)\n\n def test_sample_invalid_weight_lengths(self, obj):\n # Weight length must be right\n msg = "Weights and axis to be sampled must be of same length"\n with pytest.raises(ValueError, match=msg):\n obj.sample(n=3, weights=[0, 1])\n\n with pytest.raises(ValueError, match=msg):\n bad_weights = [0.5] * 11\n obj.sample(n=3, weights=bad_weights)\n\n with pytest.raises(ValueError, match="Fewer non-zero entries in p than size"):\n bad_weight_series = Series([0, 0, 0.2])\n obj.sample(n=4, weights=bad_weight_series)\n\n def test_sample_negative_weights(self, obj):\n # Check won't accept negative weights\n bad_weights = [-0.1] * 10\n msg = "weight vector many not include negative values"\n with pytest.raises(ValueError, match=msg):\n obj.sample(n=3, weights=bad_weights)\n\n def test_sample_inf_weights(self, obj):\n # Check inf and -inf throw errors:\n\n weights_with_inf = [0.1] * 10\n weights_with_inf[0] = np.inf\n msg = "weight vector may not include `inf` values"\n with pytest.raises(ValueError, match=msg):\n obj.sample(n=3, weights=weights_with_inf)\n\n weights_with_ninf = [0.1] * 10\n weights_with_ninf[0] = -np.inf\n with pytest.raises(ValueError, match=msg):\n obj.sample(n=3, weights=weights_with_ninf)\n\n def test_sample_zero_weights(self, obj):\n # All zeros raises errors\n\n zero_weights = [0] * 10\n with pytest.raises(ValueError, match="Invalid weights: weights sum to zero"):\n obj.sample(n=3, weights=zero_weights)\n\n def test_sample_missing_weights(self, obj):\n # All missing weights\n\n nan_weights = [np.nan] * 10\n with pytest.raises(ValueError, match="Invalid weights: weights sum to zero"):\n obj.sample(n=3, weights=nan_weights)\n\n def test_sample_none_weights(self, obj):\n # Check None are also replaced by zeros.\n weights_with_None = [None] * 10\n weights_with_None[5] = 0.5\n tm.assert_equal(\n obj.sample(n=1, axis=0, weights=weights_with_None), obj.iloc[5:6]\n )\n\n @pytest.mark.parametrize(\n "func_str,arg",\n [\n ("np.array", [2, 3, 1, 0]),\n ("np.random.MT19937", 3),\n ("np.random.PCG64", 11),\n ],\n )\n def test_sample_random_state(self, func_str, arg, frame_or_series):\n # GH#32503\n obj = DataFrame({"col1": range(10, 20), "col2": range(20, 30)})\n obj = tm.get_obj(obj, frame_or_series)\n result = obj.sample(n=3, random_state=eval(func_str)(arg))\n expected = obj.sample(n=3, random_state=com.random_state(eval(func_str)(arg)))\n tm.assert_equal(result, expected)\n\n def test_sample_generator(self, frame_or_series):\n # GH#38100\n obj = frame_or_series(np.arange(100))\n rng = np.random.default_rng(2)\n\n # Consecutive calls should advance the seed\n result1 = obj.sample(n=50, random_state=rng)\n result2 = obj.sample(n=50, random_state=rng)\n assert not (result1.index.values == result2.index.values).all()\n\n # Matching generator initialization must give same result\n # Consecutive calls should advance the seed\n result1 = obj.sample(n=50, random_state=np.random.default_rng(11))\n result2 = obj.sample(n=50, random_state=np.random.default_rng(11))\n tm.assert_equal(result1, result2)\n\n def test_sample_upsampling_without_replacement(self, frame_or_series):\n # GH#27451\n\n obj = DataFrame({"A": list("abc")})\n obj = tm.get_obj(obj, frame_or_series)\n\n msg = (\n "Replace has to be set to `True` when "\n "upsampling the population `frac` > 1."\n )\n with pytest.raises(ValueError, match=msg):\n obj.sample(frac=2, replace=False)\n\n\nclass TestSampleDataFrame:\n # Tests which are relevant only for DataFrame, so these are\n # as fully parametrized as they can get.\n\n def test_sample(self):\n # GH#2419\n # additional specific object based tests\n\n # A few dataframe test with degenerate weights.\n easy_weight_list = [0] * 10\n easy_weight_list[5] = 1\n\n df = DataFrame(\n {\n "col1": range(10, 20),\n "col2": range(20, 30),\n "colString": ["a"] * 10,\n "easyweights": easy_weight_list,\n }\n )\n sample1 = df.sample(n=1, weights="easyweights")\n tm.assert_frame_equal(sample1, df.iloc[5:6])\n\n # Ensure proper error if string given as weight for Series or\n # DataFrame with axis = 1.\n ser = Series(range(10))\n msg = "Strings cannot be passed as weights when sampling from a Series."\n with pytest.raises(ValueError, match=msg):\n ser.sample(n=3, weights="weight_column")\n\n msg = (\n "Strings can only be passed to weights when sampling from rows on a "\n "DataFrame"\n )\n with pytest.raises(ValueError, match=msg):\n df.sample(n=1, weights="weight_column", axis=1)\n\n # Check weighting key error\n with pytest.raises(\n KeyError, match="'String passed to weights not a valid column'"\n ):\n df.sample(n=3, weights="not_a_real_column_name")\n\n # Check that re-normalizes weights that don't sum to one.\n weights_less_than_1 = [0] * 10\n weights_less_than_1[0] = 0.5\n tm.assert_frame_equal(df.sample(n=1, weights=weights_less_than_1), df.iloc[:1])\n\n ###\n # Test axis argument\n ###\n\n # Test axis argument\n df = DataFrame({"col1": range(10), "col2": ["a"] * 10})\n second_column_weight = [0, 1]\n tm.assert_frame_equal(\n df.sample(n=1, axis=1, weights=second_column_weight), df[["col2"]]\n )\n\n # Different axis arg types\n tm.assert_frame_equal(\n df.sample(n=1, axis="columns", weights=second_column_weight), df[["col2"]]\n )\n\n weight = [0] * 10\n weight[5] = 0.5\n tm.assert_frame_equal(df.sample(n=1, axis="rows", weights=weight), df.iloc[5:6])\n tm.assert_frame_equal(\n df.sample(n=1, axis="index", weights=weight), df.iloc[5:6]\n )\n\n # Check out of range axis values\n msg = "No axis named 2 for object type DataFrame"\n with pytest.raises(ValueError, match=msg):\n df.sample(n=1, axis=2)\n\n msg = "No axis named not_a_name for object type DataFrame"\n with pytest.raises(ValueError, match=msg):\n df.sample(n=1, axis="not_a_name")\n\n ser = Series(range(10))\n with pytest.raises(ValueError, match="No axis named 1 for object type Series"):\n ser.sample(n=1, axis=1)\n\n # Test weight length compared to correct axis\n msg = "Weights and axis to be sampled must be of same length"\n with pytest.raises(ValueError, match=msg):\n df.sample(n=1, axis=1, weights=[0.5] * 10)\n\n def test_sample_axis1(self):\n # Check weights with axis = 1\n easy_weight_list = [0] * 3\n easy_weight_list[2] = 1\n\n df = DataFrame(\n {"col1": range(10, 20), "col2": range(20, 30), "colString": ["a"] * 10}\n )\n sample1 = df.sample(n=1, axis=1, weights=easy_weight_list)\n tm.assert_frame_equal(sample1, df[["colString"]])\n\n # Test default axes\n tm.assert_frame_equal(\n df.sample(n=3, random_state=42), df.sample(n=3, axis=0, random_state=42)\n )\n\n def test_sample_aligns_weights_with_frame(self):\n # Test that function aligns weights with frame\n df = DataFrame({"col1": [5, 6, 7], "col2": ["a", "b", "c"]}, index=[9, 5, 3])\n ser = Series([1, 0, 0], index=[3, 5, 9])\n tm.assert_frame_equal(df.loc[[3]], df.sample(1, weights=ser))\n\n # Weights have index values to be dropped because not in\n # sampled DataFrame\n ser2 = Series([0.001, 0, 10000], index=[3, 5, 10])\n tm.assert_frame_equal(df.loc[[3]], df.sample(1, weights=ser2))\n\n # Weights have empty values to be filed with zeros\n ser3 = Series([0.01, 0], index=[3, 5])\n tm.assert_frame_equal(df.loc[[3]], df.sample(1, weights=ser3))\n\n # No overlap in weight and sampled DataFrame indices\n ser4 = Series([1, 0], index=[1, 2])\n\n with pytest.raises(ValueError, match="Invalid weights: weights sum to zero"):\n df.sample(1, weights=ser4)\n\n def test_sample_is_copy(self):\n # GH#27357, GH#30784: ensure the result of sample is an actual copy and\n # doesn't track the parent dataframe / doesn't give SettingWithCopy warnings\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 3)), columns=["a", "b", "c"]\n )\n df2 = df.sample(3)\n\n with tm.assert_produces_warning(None):\n df2["d"] = 1\n\n def test_sample_does_not_modify_weights(self):\n # GH-42843\n result = np.array([np.nan, 1, np.nan])\n expected = result.copy()\n ser = Series([1, 2, 3])\n\n # Test numpy array weights won't be modified in place\n ser.sample(weights=result)\n tm.assert_numpy_array_equal(result, expected)\n\n # Test DataFrame column won't be modified in place\n df = DataFrame({"values": [1, 1, 1], "weights": [1, np.nan, np.nan]})\n expected = df["weights"].copy()\n\n df.sample(frac=1.0, replace=True, weights="weights")\n result = df["weights"]\n tm.assert_series_equal(result, expected)\n\n def test_sample_ignore_index(self):\n # GH 38581\n df = DataFrame(\n {"col1": range(10, 20), "col2": range(20, 30), "colString": ["a"] * 10}\n )\n result = df.sample(3, ignore_index=True)\n expected_index = Index(range(3))\n tm.assert_index_equal(result.index, expected_index, exact=True)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_sample.py
test_sample.py
Python
13,431
0.95
0.096774
0.160131
awesome-app
945
2024-12-03T10:45:17.943181
BSD-3-Clause
true
8ad8e2714b0836d56d43c1cafd862dd6
import numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import ExtensionDtype\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Timestamp,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import ExtensionArray\n\n\nclass DummyDtype(ExtensionDtype):\n type = int\n\n def __init__(self, numeric) -> None:\n self._numeric = numeric\n\n @property\n def name(self):\n return "Dummy"\n\n @property\n def _is_numeric(self):\n return self._numeric\n\n\nclass DummyArray(ExtensionArray):\n def __init__(self, data, dtype) -> None:\n self.data = data\n self._dtype = dtype\n\n def __array__(self, dtype=None, copy=None):\n return self.data\n\n @property\n def dtype(self):\n return self._dtype\n\n def __len__(self) -> int:\n return len(self.data)\n\n def __getitem__(self, item):\n pass\n\n def copy(self):\n return self\n\n\nclass TestSelectDtypes:\n def test_select_dtypes_include_using_list_like(self, using_infer_string):\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.Categorical(list("abc")),\n "g": pd.date_range("20130101", periods=3),\n "h": pd.date_range("20130101", periods=3, tz="US/Eastern"),\n "i": pd.date_range("20130101", periods=3, tz="CET"),\n "j": pd.period_range("2013-01", periods=3, freq="M"),\n "k": pd.timedelta_range("1 day", periods=3),\n }\n )\n\n ri = df.select_dtypes(include=[np.number])\n ei = df[["b", "c", "d", "k"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include=[np.number], exclude=["timedelta"])\n ei = df[["b", "c", "d"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include=[np.number, "category"], exclude=["timedelta"])\n ei = df[["b", "c", "d", "f"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include=["datetime"])\n ei = df[["g"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include=["datetime64"])\n ei = df[["g"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include=["datetimetz"])\n ei = df[["h", "i"]]\n tm.assert_frame_equal(ri, ei)\n\n with pytest.raises(NotImplementedError, match=r"^$"):\n df.select_dtypes(include=["period"])\n\n if using_infer_string:\n ri = df.select_dtypes(include=["str"])\n ei = df[["a"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include=[str])\n tm.assert_frame_equal(ri, ei)\n\n def test_select_dtypes_exclude_using_list_like(self):\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n }\n )\n re = df.select_dtypes(exclude=[np.number])\n ee = df[["a", "e"]]\n tm.assert_frame_equal(re, ee)\n\n def test_select_dtypes_exclude_include_using_list_like(self):\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6, dtype="u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.date_range("now", periods=3).values,\n }\n )\n exclude = (np.datetime64,)\n include = np.bool_, "integer"\n r = df.select_dtypes(include=include, exclude=exclude)\n e = df[["b", "c", "e"]]\n tm.assert_frame_equal(r, e)\n\n exclude = ("datetime",)\n include = "bool", "int64", "int32"\n r = df.select_dtypes(include=include, exclude=exclude)\n e = df[["b", "e"]]\n tm.assert_frame_equal(r, e)\n\n @pytest.mark.parametrize(\n "include", [(np.bool_, "int"), (np.bool_, "integer"), ("bool", int)]\n )\n def test_select_dtypes_exclude_include_int(self, include):\n # Fix select_dtypes(include='int') for Windows, FYI #36596\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6, dtype="int32"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.date_range("now", periods=3).values,\n }\n )\n exclude = (np.datetime64,)\n result = df.select_dtypes(include=include, exclude=exclude)\n expected = df[["b", "c", "e"]]\n tm.assert_frame_equal(result, expected)\n\n def test_select_dtypes_include_using_scalars(self, using_infer_string):\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.Categorical(list("abc")),\n "g": pd.date_range("20130101", periods=3),\n "h": pd.date_range("20130101", periods=3, tz="US/Eastern"),\n "i": pd.date_range("20130101", periods=3, tz="CET"),\n "j": pd.period_range("2013-01", periods=3, freq="M"),\n "k": pd.timedelta_range("1 day", periods=3),\n }\n )\n\n ri = df.select_dtypes(include=np.number)\n ei = df[["b", "c", "d", "k"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include="datetime")\n ei = df[["g"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include="datetime64")\n ei = df[["g"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include="category")\n ei = df[["f"]]\n tm.assert_frame_equal(ri, ei)\n\n with pytest.raises(NotImplementedError, match=r"^$"):\n df.select_dtypes(include="period")\n\n if using_infer_string:\n ri = df.select_dtypes(include="str")\n ei = df[["a"]]\n tm.assert_frame_equal(ri, ei)\n\n def test_select_dtypes_exclude_using_scalars(self):\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.Categorical(list("abc")),\n "g": pd.date_range("20130101", periods=3),\n "h": pd.date_range("20130101", periods=3, tz="US/Eastern"),\n "i": pd.date_range("20130101", periods=3, tz="CET"),\n "j": pd.period_range("2013-01", periods=3, freq="M"),\n "k": pd.timedelta_range("1 day", periods=3),\n }\n )\n\n ri = df.select_dtypes(exclude=np.number)\n ei = df[["a", "e", "f", "g", "h", "i", "j"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(exclude="category")\n ei = df[["a", "b", "c", "d", "e", "g", "h", "i", "j", "k"]]\n tm.assert_frame_equal(ri, ei)\n\n with pytest.raises(NotImplementedError, match=r"^$"):\n df.select_dtypes(exclude="period")\n\n def test_select_dtypes_include_exclude_using_scalars(self):\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.Categorical(list("abc")),\n "g": pd.date_range("20130101", periods=3),\n "h": pd.date_range("20130101", periods=3, tz="US/Eastern"),\n "i": pd.date_range("20130101", periods=3, tz="CET"),\n "j": pd.period_range("2013-01", periods=3, freq="M"),\n "k": pd.timedelta_range("1 day", periods=3),\n }\n )\n\n ri = df.select_dtypes(include=np.number, exclude="floating")\n ei = df[["b", "c", "k"]]\n tm.assert_frame_equal(ri, ei)\n\n def test_select_dtypes_include_exclude_mixed_scalars_lists(self):\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.Categorical(list("abc")),\n "g": pd.date_range("20130101", periods=3),\n "h": pd.date_range("20130101", periods=3, tz="US/Eastern"),\n "i": pd.date_range("20130101", periods=3, tz="CET"),\n "j": pd.period_range("2013-01", periods=3, freq="M"),\n "k": pd.timedelta_range("1 day", periods=3),\n }\n )\n\n ri = df.select_dtypes(include=np.number, exclude=["floating", "timedelta"])\n ei = df[["b", "c"]]\n tm.assert_frame_equal(ri, ei)\n\n ri = df.select_dtypes(include=[np.number, "category"], exclude="floating")\n ei = df[["b", "c", "f", "k"]]\n tm.assert_frame_equal(ri, ei)\n\n def test_select_dtypes_duplicate_columns(self):\n # GH20839\n df = DataFrame(\n {\n "a": ["a", "b", "c"],\n "b": [1, 2, 3],\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.date_range("now", periods=3).values,\n }\n )\n df.columns = ["a", "a", "b", "b", "b", "c"]\n\n expected = DataFrame(\n {"a": list(range(1, 4)), "b": np.arange(3, 6).astype("u1")}\n )\n\n result = df.select_dtypes(include=[np.number], exclude=["floating"])\n tm.assert_frame_equal(result, expected)\n\n def test_select_dtypes_not_an_attr_but_still_valid_dtype(self, using_infer_string):\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.date_range("now", periods=3).values,\n }\n )\n df["g"] = df.f.diff()\n assert not hasattr(np, "u8")\n r = df.select_dtypes(include=["i8", "O"], exclude=["timedelta"])\n if using_infer_string:\n e = df[["b"]]\n else:\n e = df[["a", "b"]]\n tm.assert_frame_equal(r, e)\n\n r = df.select_dtypes(include=["i8", "O", "timedelta64[ns]"])\n if using_infer_string:\n e = df[["b", "g"]]\n else:\n e = df[["a", "b", "g"]]\n tm.assert_frame_equal(r, e)\n\n def test_select_dtypes_empty(self):\n df = DataFrame({"a": list("abc"), "b": list(range(1, 4))})\n msg = "at least one of include or exclude must be nonempty"\n with pytest.raises(ValueError, match=msg):\n df.select_dtypes()\n\n def test_select_dtypes_bad_datetime64(self):\n df = DataFrame(\n {\n "a": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.date_range("now", periods=3).values,\n }\n )\n with pytest.raises(ValueError, match=".+ is too specific"):\n df.select_dtypes(include=["datetime64[D]"])\n\n with pytest.raises(ValueError, match=".+ is too specific"):\n df.select_dtypes(exclude=["datetime64[as]"])\n\n def test_select_dtypes_datetime_with_tz(self):\n df2 = DataFrame(\n {\n "A": Timestamp("20130102", tz="US/Eastern"),\n "B": Timestamp("20130603", tz="CET"),\n },\n index=range(5),\n )\n df3 = pd.concat([df2.A.to_frame(), df2.B.to_frame()], axis=1)\n result = df3.select_dtypes(include=["datetime64[ns]"])\n expected = df3.reindex(columns=[])\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("dtype", [str, "str", np.bytes_, "S1", np.str_, "U1"])\n @pytest.mark.parametrize("arg", ["include", "exclude"])\n def test_select_dtypes_str_raises(self, dtype, arg, using_infer_string):\n if using_infer_string and (dtype == "str" or dtype is str):\n # this is tested below\n pytest.skip("Selecting string columns works with future strings")\n df = DataFrame(\n {\n "a": list("abc"),\n "g": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.date_range("now", periods=3).values,\n }\n )\n msg = "string dtypes are not allowed"\n kwargs = {arg: [dtype]}\n\n with pytest.raises(TypeError, match=msg):\n df.select_dtypes(**kwargs)\n\n def test_select_dtypes_bad_arg_raises(self):\n df = DataFrame(\n {\n "a": list("abc"),\n "g": list("abc"),\n "b": list(range(1, 4)),\n "c": np.arange(3, 6).astype("u1"),\n "d": np.arange(4.0, 7.0, dtype="float64"),\n "e": [True, False, True],\n "f": pd.date_range("now", periods=3).values,\n }\n )\n\n msg = "data type.*not understood"\n with pytest.raises(TypeError, match=msg):\n df.select_dtypes(["blargy, blarg, blarg"])\n\n def test_select_dtypes_typecodes(self):\n # GH 11990\n df = DataFrame(np.random.default_rng(2).random((5, 3)))\n FLOAT_TYPES = list(np.typecodes["AllFloat"])\n tm.assert_frame_equal(df.select_dtypes(FLOAT_TYPES), df)\n\n @pytest.mark.parametrize(\n "arr,expected",\n (\n (np.array([1, 2], dtype=np.int32), True),\n (pd.array([1, 2], dtype="Int32"), True),\n (DummyArray([1, 2], dtype=DummyDtype(numeric=True)), True),\n (DummyArray([1, 2], dtype=DummyDtype(numeric=False)), False),\n ),\n )\n def test_select_dtypes_numeric(self, arr, expected):\n # GH 35340\n\n df = DataFrame(arr)\n is_selected = df.select_dtypes(np.number).shape == df.shape\n assert is_selected == expected\n\n def test_select_dtypes_numeric_nullable_string(self, nullable_string_dtype):\n arr = pd.array(["a", "b"], dtype=nullable_string_dtype)\n df = DataFrame(arr)\n is_selected = df.select_dtypes(np.number).shape == df.shape\n assert not is_selected\n\n @pytest.mark.parametrize(\n "expected, float_dtypes",\n [\n [\n DataFrame(\n {"A": range(3), "B": range(5, 8), "C": range(10, 7, -1)}\n ).astype(dtype={"A": float, "B": np.float64, "C": np.float32}),\n float,\n ],\n [\n DataFrame(\n {"A": range(3), "B": range(5, 8), "C": range(10, 7, -1)}\n ).astype(dtype={"A": float, "B": np.float64, "C": np.float32}),\n "float",\n ],\n [DataFrame({"C": range(10, 7, -1)}, dtype=np.float32), np.float32],\n [\n DataFrame({"A": range(3), "B": range(5, 8)}).astype(\n dtype={"A": float, "B": np.float64}\n ),\n np.float64,\n ],\n ],\n )\n def test_select_dtypes_float_dtype(self, expected, float_dtypes):\n # GH#42452\n dtype_dict = {"A": float, "B": np.float64, "C": np.float32}\n df = DataFrame(\n {"A": range(3), "B": range(5, 8), "C": range(10, 7, -1)},\n )\n df = df.astype(dtype_dict)\n result = df.select_dtypes(include=float_dtypes)\n tm.assert_frame_equal(result, expected)\n\n def test_np_bool_ea_boolean_include_number(self):\n # GH 46870\n df = DataFrame(\n {\n "a": [1, 2, 3],\n "b": pd.Series([True, False, True], dtype="boolean"),\n "c": np.array([True, False, True]),\n "d": pd.Categorical([True, False, True]),\n "e": pd.arrays.SparseArray([True, False, True]),\n }\n )\n result = df.select_dtypes(include="number")\n expected = DataFrame({"a": [1, 2, 3]})\n tm.assert_frame_equal(result, expected)\n\n def test_select_dtypes_no_view(self):\n # https://github.com/pandas-dev/pandas/issues/48090\n # result of this method is not a view on the original dataframe\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n df_orig = df.copy()\n result = df.select_dtypes(include=["number"])\n result.iloc[0, 0] = 0\n tm.assert_frame_equal(df, df_orig)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_select_dtypes.py
test_select_dtypes.py
Python
17,273
0.95
0.080412
0.021429
node-utils
42
2025-05-28T17:53:14.229025
Apache-2.0
true
c20c6e9c1d17c551b2e0bb3ae2f70ce8
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass SharedSetAxisTests:\n @pytest.fixture\n def obj(self):\n raise NotImplementedError("Implemented by subclasses")\n\n def test_set_axis(self, obj):\n # GH14636; this tests setting index for both Series and DataFrame\n new_index = list("abcd")[: len(obj)]\n expected = obj.copy()\n expected.index = new_index\n result = obj.set_axis(new_index, axis=0)\n tm.assert_equal(expected, result)\n\n def test_set_axis_copy(self, obj, using_copy_on_write):\n # Test copy keyword GH#47932\n new_index = list("abcd")[: len(obj)]\n\n orig = obj.iloc[:]\n expected = obj.copy()\n expected.index = new_index\n\n result = obj.set_axis(new_index, axis=0, copy=True)\n tm.assert_equal(expected, result)\n assert result is not obj\n # check we DID make a copy\n if not using_copy_on_write:\n if obj.ndim == 1:\n assert not tm.shares_memory(result, obj)\n else:\n assert not any(\n tm.shares_memory(result.iloc[:, i], obj.iloc[:, i])\n for i in range(obj.shape[1])\n )\n\n result = obj.set_axis(new_index, axis=0, copy=False)\n tm.assert_equal(expected, result)\n assert result is not obj\n # check we did NOT make a copy\n if obj.ndim == 1:\n assert tm.shares_memory(result, obj)\n else:\n assert all(\n tm.shares_memory(result.iloc[:, i], obj.iloc[:, i])\n for i in range(obj.shape[1])\n )\n\n # copy defaults to True\n result = obj.set_axis(new_index, axis=0)\n tm.assert_equal(expected, result)\n assert result is not obj\n if using_copy_on_write:\n # check we DID NOT make a copy\n if obj.ndim == 1:\n assert tm.shares_memory(result, obj)\n else:\n assert any(\n tm.shares_memory(result.iloc[:, i], obj.iloc[:, i])\n for i in range(obj.shape[1])\n )\n # check we DID make a copy\n elif obj.ndim == 1:\n assert not tm.shares_memory(result, obj)\n else:\n assert not any(\n tm.shares_memory(result.iloc[:, i], obj.iloc[:, i])\n for i in range(obj.shape[1])\n )\n\n res = obj.set_axis(new_index, copy=False)\n tm.assert_equal(expected, res)\n # check we did NOT make a copy\n if res.ndim == 1:\n assert tm.shares_memory(res, orig)\n else:\n assert all(\n tm.shares_memory(res.iloc[:, i], orig.iloc[:, i])\n for i in range(res.shape[1])\n )\n\n def test_set_axis_unnamed_kwarg_warns(self, obj):\n # omitting the "axis" parameter\n new_index = list("abcd")[: len(obj)]\n\n expected = obj.copy()\n expected.index = new_index\n\n result = obj.set_axis(new_index)\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize("axis", [3, "foo"])\n def test_set_axis_invalid_axis_name(self, axis, obj):\n # wrong values for the "axis" parameter\n with pytest.raises(ValueError, match="No axis named"):\n obj.set_axis(list("abc"), axis=axis)\n\n def test_set_axis_setattr_index_not_collection(self, obj):\n # wrong type\n msg = (\n r"Index\(\.\.\.\) must be called with a collection of some "\n r"kind, None was passed"\n )\n with pytest.raises(TypeError, match=msg):\n obj.index = None\n\n def test_set_axis_setattr_index_wrong_length(self, obj):\n # wrong length\n msg = (\n f"Length mismatch: Expected axis has {len(obj)} elements, "\n f"new values have {len(obj)-1} elements"\n )\n with pytest.raises(ValueError, match=msg):\n obj.index = np.arange(len(obj) - 1)\n\n if obj.ndim == 2:\n with pytest.raises(ValueError, match="Length mismatch"):\n obj.columns = obj.columns[::2]\n\n\nclass TestDataFrameSetAxis(SharedSetAxisTests):\n @pytest.fixture\n def obj(self):\n df = DataFrame(\n {"A": [1.1, 2.2, 3.3], "B": [5.0, 6.1, 7.2], "C": [4.4, 5.5, 6.6]},\n index=[2010, 2011, 2012],\n )\n return df\n\n\nclass TestSeriesSetAxis(SharedSetAxisTests):\n @pytest.fixture\n def obj(self):\n ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64")\n return ser\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_set_axis.py
test_set_axis.py
Python
4,608
0.95
0.181818
0.098361
react-lib
601
2024-08-09T04:50:39.749189
Apache-2.0
true
89669e24f617908cca2b13538e6b6898
"""\nSee also: test_reindex.py:TestReindexSetIndex\n"""\n\nfrom datetime import (\n datetime,\n timedelta,\n)\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n Categorical,\n CategoricalIndex,\n DataFrame,\n DatetimeIndex,\n Index,\n MultiIndex,\n Series,\n date_range,\n period_range,\n to_datetime,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture\ndef frame_of_index_cols():\n """\n Fixture for DataFrame of columns that can be used for indexing\n\n Columns are ['A', 'B', 'C', 'D', 'E', ('tuple', 'as', 'label')];\n 'A' & 'B' contain duplicates (but are jointly unique), the rest are unique.\n\n A B C D E (tuple, as, label)\n 0 foo one a 0.608477 -0.012500 -1.664297\n 1 foo two b -0.633460 0.249614 -0.364411\n 2 foo three c 0.615256 2.154968 -0.834666\n 3 bar one d 0.234246 1.085675 0.718445\n 4 bar two e 0.533841 -0.005702 -3.533912\n """\n df = DataFrame(\n {\n "A": ["foo", "foo", "foo", "bar", "bar"],\n "B": ["one", "two", "three", "one", "two"],\n "C": ["a", "b", "c", "d", "e"],\n "D": np.random.default_rng(2).standard_normal(5),\n "E": np.random.default_rng(2).standard_normal(5),\n ("tuple", "as", "label"): np.random.default_rng(2).standard_normal(5),\n }\n )\n return df\n\n\nclass TestSetIndex:\n def test_set_index_multiindex(self):\n # segfault in GH#3308\n d = {"t1": [2, 2.5, 3], "t2": [4, 5, 6]}\n df = DataFrame(d)\n tuples = [(0, 1), (0, 2), (1, 2)]\n df["tuples"] = tuples\n\n index = MultiIndex.from_tuples(df["tuples"])\n # it works!\n df.set_index(index)\n\n def test_set_index_empty_column(self):\n # GH#1971\n df = DataFrame(\n [\n {"a": 1, "p": 0},\n {"a": 2, "m": 10},\n {"a": 3, "m": 11, "p": 20},\n {"a": 4, "m": 12, "p": 21},\n ],\n columns=["a", "m", "p", "x"],\n )\n\n result = df.set_index(["a", "x"])\n\n expected = df[["m", "p"]]\n expected.index = MultiIndex.from_arrays([df["a"], df["x"]], names=["a", "x"])\n tm.assert_frame_equal(result, expected)\n\n def test_set_index_empty_dataframe(self):\n # GH#38419\n df1 = DataFrame(\n {"a": Series(dtype="datetime64[ns]"), "b": Series(dtype="int64"), "c": []}\n )\n\n df2 = df1.set_index(["a", "b"])\n result = df2.index.to_frame().dtypes\n expected = df1[["a", "b"]].dtypes\n tm.assert_series_equal(result, expected)\n\n def test_set_index_multiindexcolumns(self):\n columns = MultiIndex.from_tuples([("foo", 1), ("foo", 2), ("bar", 1)])\n df = DataFrame(\n np.random.default_rng(2).standard_normal((3, 3)), columns=columns\n )\n\n result = df.set_index(df.columns[0])\n\n expected = df.iloc[:, 1:]\n expected.index = df.iloc[:, 0].values\n expected.index.names = [df.columns[0]]\n tm.assert_frame_equal(result, expected)\n\n def test_set_index_timezone(self):\n # GH#12358\n # tz-aware Series should retain the tz\n idx = DatetimeIndex(["2014-01-01 10:10:10"], tz="UTC").tz_convert("Europe/Rome")\n df = DataFrame({"A": idx})\n assert df.set_index(idx).index[0].hour == 11\n assert DatetimeIndex(Series(df.A))[0].hour == 11\n assert df.set_index(df.A).index[0].hour == 11\n\n def test_set_index_cast_datetimeindex(self):\n df = DataFrame(\n {\n "A": [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)],\n "B": np.random.default_rng(2).standard_normal(1000),\n }\n )\n\n idf = df.set_index("A")\n assert isinstance(idf.index, DatetimeIndex)\n\n def test_set_index_dst(self):\n di = date_range("2006-10-29 00:00:00", periods=3, freq="h", tz="US/Pacific")\n\n df = DataFrame(data={"a": [0, 1, 2], "b": [3, 4, 5]}, index=di).reset_index()\n # single level\n res = df.set_index("index")\n exp = DataFrame(\n data={"a": [0, 1, 2], "b": [3, 4, 5]},\n index=Index(di, name="index"),\n )\n exp.index = exp.index._with_freq(None)\n tm.assert_frame_equal(res, exp)\n\n # GH#12920\n res = df.set_index(["index", "a"])\n exp_index = MultiIndex.from_arrays([di, [0, 1, 2]], names=["index", "a"])\n exp = DataFrame({"b": [3, 4, 5]}, index=exp_index)\n tm.assert_frame_equal(res, exp)\n\n def test_set_index(self, float_string_frame):\n df = float_string_frame\n idx = Index(np.arange(len(df))[::-1])\n\n df = df.set_index(idx)\n tm.assert_index_equal(df.index, idx)\n with pytest.raises(ValueError, match="Length mismatch"):\n df.set_index(idx[::2])\n\n def test_set_index_names(self):\n df = DataFrame(\n np.ones((10, 4)),\n columns=Index(list("ABCD")),\n index=Index([f"i-{i}" for i in range(10)]),\n )\n df.index.name = "name"\n\n assert df.set_index(df.index).index.names == ["name"]\n\n mi = MultiIndex.from_arrays(df[["A", "B"]].T.values, names=["A", "B"])\n mi2 = MultiIndex.from_arrays(\n df[["A", "B", "A", "B"]].T.values, names=["A", "B", "C", "D"]\n )\n\n df = df.set_index(["A", "B"])\n\n assert df.set_index(df.index).index.names == ["A", "B"]\n\n # Check that set_index isn't converting a MultiIndex into an Index\n assert isinstance(df.set_index(df.index).index, MultiIndex)\n\n # Check actual equality\n tm.assert_index_equal(df.set_index(df.index).index, mi)\n\n idx2 = df.index.rename(["C", "D"])\n\n # Check that [MultiIndex, MultiIndex] yields a MultiIndex rather\n # than a pair of tuples\n assert isinstance(df.set_index([df.index, idx2]).index, MultiIndex)\n\n # Check equality\n tm.assert_index_equal(df.set_index([df.index, idx2]).index, mi2)\n\n # A has duplicate values, C does not\n @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])\n @pytest.mark.parametrize("inplace", [True, False])\n @pytest.mark.parametrize("drop", [True, False])\n def test_set_index_drop_inplace(self, frame_of_index_cols, drop, inplace, keys):\n df = frame_of_index_cols\n\n if isinstance(keys, list):\n idx = MultiIndex.from_arrays([df[x] for x in keys], names=keys)\n else:\n idx = Index(df[keys], name=keys)\n expected = df.drop(keys, axis=1) if drop else df\n expected.index = idx\n\n if inplace:\n result = df.copy()\n return_value = result.set_index(keys, drop=drop, inplace=True)\n assert return_value is None\n else:\n result = df.set_index(keys, drop=drop)\n\n tm.assert_frame_equal(result, expected)\n\n # A has duplicate values, C does not\n @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])\n @pytest.mark.parametrize("drop", [True, False])\n def test_set_index_append(self, frame_of_index_cols, drop, keys):\n df = frame_of_index_cols\n\n keys = keys if isinstance(keys, list) else [keys]\n idx = MultiIndex.from_arrays(\n [df.index] + [df[x] for x in keys], names=[None] + keys\n )\n expected = df.drop(keys, axis=1) if drop else df.copy()\n expected.index = idx\n\n result = df.set_index(keys, drop=drop, append=True)\n\n tm.assert_frame_equal(result, expected)\n\n # A has duplicate values, C does not\n @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])\n @pytest.mark.parametrize("drop", [True, False])\n def test_set_index_append_to_multiindex(self, frame_of_index_cols, drop, keys):\n # append to existing multiindex\n df = frame_of_index_cols.set_index(["D"], drop=drop, append=True)\n\n keys = keys if isinstance(keys, list) else [keys]\n expected = frame_of_index_cols.set_index(["D"] + keys, drop=drop, append=True)\n\n result = df.set_index(keys, drop=drop, append=True)\n\n tm.assert_frame_equal(result, expected)\n\n def test_set_index_after_mutation(self):\n # GH#1590\n df = DataFrame({"val": [0, 1, 2], "key": ["a", "b", "c"]})\n expected = DataFrame({"val": [1, 2]}, Index(["b", "c"], name="key"))\n\n df2 = df.loc[df.index.map(lambda indx: indx >= 1)]\n result = df2.set_index("key")\n tm.assert_frame_equal(result, expected)\n\n # MultiIndex constructor does not work directly on Series -> lambda\n # Add list-of-list constructor because list is ambiguous -> lambda\n # also test index name if append=True (name is duplicate here for B)\n @pytest.mark.parametrize(\n "box",\n [\n Series,\n Index,\n np.array,\n list,\n lambda x: [list(x)],\n lambda x: MultiIndex.from_arrays([x]),\n ],\n )\n @pytest.mark.parametrize(\n "append, index_name", [(True, None), (True, "B"), (True, "test"), (False, None)]\n )\n @pytest.mark.parametrize("drop", [True, False])\n def test_set_index_pass_single_array(\n self, frame_of_index_cols, drop, append, index_name, box\n ):\n df = frame_of_index_cols\n df.index.name = index_name\n\n key = box(df["B"])\n if box == list:\n # list of strings gets interpreted as list of keys\n msg = "['one', 'two', 'three', 'one', 'two']"\n with pytest.raises(KeyError, match=msg):\n df.set_index(key, drop=drop, append=append)\n else:\n # np.array/list-of-list "forget" the name of B\n name_mi = getattr(key, "names", None)\n name = [getattr(key, "name", None)] if name_mi is None else name_mi\n\n result = df.set_index(key, drop=drop, append=append)\n\n # only valid column keys are dropped\n # since B is always passed as array above, nothing is dropped\n expected = df.set_index(["B"], drop=False, append=append)\n expected.index.names = [index_name] + name if append else name\n\n tm.assert_frame_equal(result, expected)\n\n # MultiIndex constructor does not work directly on Series -> lambda\n # also test index name if append=True (name is duplicate here for A & B)\n @pytest.mark.parametrize(\n "box", [Series, Index, np.array, list, lambda x: MultiIndex.from_arrays([x])]\n )\n @pytest.mark.parametrize(\n "append, index_name",\n [(True, None), (True, "A"), (True, "B"), (True, "test"), (False, None)],\n )\n @pytest.mark.parametrize("drop", [True, False])\n def test_set_index_pass_arrays(\n self, frame_of_index_cols, drop, append, index_name, box\n ):\n df = frame_of_index_cols\n df.index.name = index_name\n\n keys = ["A", box(df["B"])]\n # np.array/list "forget" the name of B\n names = ["A", None if box in [np.array, list, tuple, iter] else "B"]\n\n result = df.set_index(keys, drop=drop, append=append)\n\n # only valid column keys are dropped\n # since B is always passed as array above, only A is dropped, if at all\n expected = df.set_index(["A", "B"], drop=False, append=append)\n expected = expected.drop("A", axis=1) if drop else expected\n expected.index.names = [index_name] + names if append else names\n\n tm.assert_frame_equal(result, expected)\n\n # MultiIndex constructor does not work directly on Series -> lambda\n # We also emulate a "constructor" for the label -> lambda\n # also test index name if append=True (name is duplicate here for A)\n @pytest.mark.parametrize(\n "box2",\n [\n Series,\n Index,\n np.array,\n list,\n iter,\n lambda x: MultiIndex.from_arrays([x]),\n lambda x: x.name,\n ],\n )\n @pytest.mark.parametrize(\n "box1",\n [\n Series,\n Index,\n np.array,\n list,\n iter,\n lambda x: MultiIndex.from_arrays([x]),\n lambda x: x.name,\n ],\n )\n @pytest.mark.parametrize(\n "append, index_name", [(True, None), (True, "A"), (True, "test"), (False, None)]\n )\n @pytest.mark.parametrize("drop", [True, False])\n def test_set_index_pass_arrays_duplicate(\n self, frame_of_index_cols, drop, append, index_name, box1, box2\n ):\n df = frame_of_index_cols\n df.index.name = index_name\n\n keys = [box1(df["A"]), box2(df["A"])]\n result = df.set_index(keys, drop=drop, append=append)\n\n # if either box is iter, it has been consumed; re-read\n keys = [box1(df["A"]), box2(df["A"])]\n\n # need to adapt first drop for case that both keys are 'A' --\n # cannot drop the same column twice;\n # plain == would give ambiguous Boolean error for containers\n first_drop = (\n False\n if (\n isinstance(keys[0], str)\n and keys[0] == "A"\n and isinstance(keys[1], str)\n and keys[1] == "A"\n )\n else drop\n )\n # to test against already-tested behaviour, we add sequentially,\n # hence second append always True; must wrap keys in list, otherwise\n # box = list would be interpreted as keys\n expected = df.set_index([keys[0]], drop=first_drop, append=append)\n expected = expected.set_index([keys[1]], drop=drop, append=True)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("append", [True, False])\n @pytest.mark.parametrize("drop", [True, False])\n def test_set_index_pass_multiindex(self, frame_of_index_cols, drop, append):\n df = frame_of_index_cols\n keys = MultiIndex.from_arrays([df["A"], df["B"]], names=["A", "B"])\n\n result = df.set_index(keys, drop=drop, append=append)\n\n # setting with a MultiIndex will never drop columns\n expected = df.set_index(["A", "B"], drop=False, append=append)\n\n tm.assert_frame_equal(result, expected)\n\n def test_construction_with_categorical_index(self):\n ci = CategoricalIndex(list("ab") * 5, name="B")\n\n # with Categorical\n df = DataFrame(\n {"A": np.random.default_rng(2).standard_normal(10), "B": ci.values}\n )\n idf = df.set_index("B")\n tm.assert_index_equal(idf.index, ci)\n\n # from a CategoricalIndex\n df = DataFrame({"A": np.random.default_rng(2).standard_normal(10), "B": ci})\n idf = df.set_index("B")\n tm.assert_index_equal(idf.index, ci)\n\n # round-trip\n idf = idf.reset_index().set_index("B")\n tm.assert_index_equal(idf.index, ci)\n\n def test_set_index_preserve_categorical_dtype(self):\n # GH#13743, GH#13854\n df = DataFrame(\n {\n "A": [1, 2, 1, 1, 2],\n "B": [10, 16, 22, 28, 34],\n "C1": Categorical(list("abaab"), categories=list("bac"), ordered=False),\n "C2": Categorical(list("abaab"), categories=list("bac"), ordered=True),\n }\n )\n for cols in ["C1", "C2", ["A", "C1"], ["A", "C2"], ["C1", "C2"]]:\n result = df.set_index(cols).reset_index()\n result = result.reindex(columns=df.columns)\n tm.assert_frame_equal(result, df)\n\n def test_set_index_datetime(self):\n # GH#3950\n df = DataFrame(\n {\n "label": ["a", "a", "a", "b", "b", "b"],\n "datetime": [\n "2011-07-19 07:00:00",\n "2011-07-19 08:00:00",\n "2011-07-19 09:00:00",\n "2011-07-19 07:00:00",\n "2011-07-19 08:00:00",\n "2011-07-19 09:00:00",\n ],\n "value": range(6),\n }\n )\n df.index = to_datetime(df.pop("datetime"), utc=True)\n df.index = df.index.tz_convert("US/Pacific")\n\n expected = DatetimeIndex(\n ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"],\n name="datetime",\n )\n expected = expected.tz_localize("UTC").tz_convert("US/Pacific")\n\n df = df.set_index("label", append=True)\n tm.assert_index_equal(df.index.levels[0], expected)\n tm.assert_index_equal(df.index.levels[1], Index(["a", "b"], name="label"))\n assert df.index.names == ["datetime", "label"]\n\n df = df.swaplevel(0, 1)\n tm.assert_index_equal(df.index.levels[0], Index(["a", "b"], name="label"))\n tm.assert_index_equal(df.index.levels[1], expected)\n assert df.index.names == ["label", "datetime"]\n\n df = DataFrame(np.random.default_rng(2).random(6))\n idx1 = DatetimeIndex(\n [\n "2011-07-19 07:00:00",\n "2011-07-19 08:00:00",\n "2011-07-19 09:00:00",\n "2011-07-19 07:00:00",\n "2011-07-19 08:00:00",\n "2011-07-19 09:00:00",\n ],\n tz="US/Eastern",\n )\n idx2 = DatetimeIndex(\n [\n "2012-04-01 09:00",\n "2012-04-01 09:00",\n "2012-04-01 09:00",\n "2012-04-02 09:00",\n "2012-04-02 09:00",\n "2012-04-02 09:00",\n ],\n tz="US/Eastern",\n )\n idx3 = date_range("2011-01-01 09:00", periods=6, tz="Asia/Tokyo")\n idx3 = idx3._with_freq(None)\n\n df = df.set_index(idx1)\n df = df.set_index(idx2, append=True)\n df = df.set_index(idx3, append=True)\n\n expected1 = DatetimeIndex(\n ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"],\n tz="US/Eastern",\n )\n expected2 = DatetimeIndex(\n ["2012-04-01 09:00", "2012-04-02 09:00"], tz="US/Eastern"\n )\n\n tm.assert_index_equal(df.index.levels[0], expected1)\n tm.assert_index_equal(df.index.levels[1], expected2)\n tm.assert_index_equal(df.index.levels[2], idx3)\n\n # GH#7092\n tm.assert_index_equal(df.index.get_level_values(0), idx1)\n tm.assert_index_equal(df.index.get_level_values(1), idx2)\n tm.assert_index_equal(df.index.get_level_values(2), idx3)\n\n def test_set_index_period(self):\n # GH#6631\n df = DataFrame(np.random.default_rng(2).random(6))\n idx1 = period_range("2011-01-01", periods=3, freq="M")\n idx1 = idx1.append(idx1)\n idx2 = period_range("2013-01-01 09:00", periods=2, freq="h")\n idx2 = idx2.append(idx2).append(idx2)\n idx3 = period_range("2005", periods=6, freq="Y")\n\n df = df.set_index(idx1)\n df = df.set_index(idx2, append=True)\n df = df.set_index(idx3, append=True)\n\n expected1 = period_range("2011-01-01", periods=3, freq="M")\n expected2 = period_range("2013-01-01 09:00", periods=2, freq="h")\n\n tm.assert_index_equal(df.index.levels[0], expected1)\n tm.assert_index_equal(df.index.levels[1], expected2)\n tm.assert_index_equal(df.index.levels[2], idx3)\n\n tm.assert_index_equal(df.index.get_level_values(0), idx1)\n tm.assert_index_equal(df.index.get_level_values(1), idx2)\n tm.assert_index_equal(df.index.get_level_values(2), idx3)\n\n\nclass TestSetIndexInvalid:\n def test_set_index_verify_integrity(self, frame_of_index_cols):\n df = frame_of_index_cols\n\n with pytest.raises(ValueError, match="Index has duplicate keys"):\n df.set_index("A", verify_integrity=True)\n # with MultiIndex\n with pytest.raises(ValueError, match="Index has duplicate keys"):\n df.set_index([df["A"], df["A"]], verify_integrity=True)\n\n @pytest.mark.parametrize("append", [True, False])\n @pytest.mark.parametrize("drop", [True, False])\n def test_set_index_raise_keys(self, frame_of_index_cols, drop, append):\n df = frame_of_index_cols\n\n with pytest.raises(KeyError, match="['foo', 'bar', 'baz']"):\n # column names are A-E, as well as one tuple\n df.set_index(["foo", "bar", "baz"], drop=drop, append=append)\n\n # non-existent key in list with arrays\n with pytest.raises(KeyError, match="X"):\n df.set_index([df["A"], df["B"], "X"], drop=drop, append=append)\n\n msg = "[('foo', 'foo', 'foo', 'bar', 'bar')]"\n # tuples always raise KeyError\n with pytest.raises(KeyError, match=msg):\n df.set_index(tuple(df["A"]), drop=drop, append=append)\n\n # also within a list\n with pytest.raises(KeyError, match=msg):\n df.set_index(["A", df["A"], tuple(df["A"])], drop=drop, append=append)\n\n @pytest.mark.parametrize("append", [True, False])\n @pytest.mark.parametrize("drop", [True, False])\n @pytest.mark.parametrize("box", [set], ids=["set"])\n def test_set_index_raise_on_type(self, frame_of_index_cols, box, drop, append):\n df = frame_of_index_cols\n\n msg = 'The parameter "keys" may be a column key, .*'\n # forbidden type, e.g. set\n with pytest.raises(TypeError, match=msg):\n df.set_index(box(df["A"]), drop=drop, append=append)\n\n # forbidden type in list, e.g. set\n with pytest.raises(TypeError, match=msg):\n df.set_index(["A", df["A"], box(df["A"])], drop=drop, append=append)\n\n # MultiIndex constructor does not work directly on Series -> lambda\n @pytest.mark.parametrize(\n "box",\n [Series, Index, np.array, iter, lambda x: MultiIndex.from_arrays([x])],\n ids=["Series", "Index", "np.array", "iter", "MultiIndex"],\n )\n @pytest.mark.parametrize("length", [4, 6], ids=["too_short", "too_long"])\n @pytest.mark.parametrize("append", [True, False])\n @pytest.mark.parametrize("drop", [True, False])\n def test_set_index_raise_on_len(\n self, frame_of_index_cols, box, length, drop, append\n ):\n # GH 24984\n df = frame_of_index_cols # has length 5\n\n values = np.random.default_rng(2).integers(0, 10, (length,))\n\n msg = "Length mismatch: Expected 5 rows, received array of length.*"\n\n # wrong length directly\n with pytest.raises(ValueError, match=msg):\n df.set_index(box(values), drop=drop, append=append)\n\n # wrong length in list\n with pytest.raises(ValueError, match=msg):\n df.set_index(["A", df.A, box(values)], drop=drop, append=append)\n\n\nclass TestSetIndexCustomLabelType:\n def test_set_index_custom_label_type(self):\n # GH#24969\n\n class Thing:\n def __init__(self, name, color) -> None:\n self.name = name\n self.color = color\n\n def __str__(self) -> str:\n return f"<Thing {repr(self.name)}>"\n\n # necessary for pretty KeyError\n __repr__ = __str__\n\n thing1 = Thing("One", "red")\n thing2 = Thing("Two", "blue")\n df = DataFrame({thing1: [0, 1], thing2: [2, 3]})\n expected = DataFrame({thing1: [0, 1]}, index=Index([2, 3], name=thing2))\n\n # use custom label directly\n result = df.set_index(thing2)\n tm.assert_frame_equal(result, expected)\n\n # custom label wrapped in list\n result = df.set_index([thing2])\n tm.assert_frame_equal(result, expected)\n\n # missing key\n thing3 = Thing("Three", "pink")\n msg = "<Thing 'Three'>"\n with pytest.raises(KeyError, match=msg):\n # missing label directly\n df.set_index(thing3)\n\n with pytest.raises(KeyError, match=msg):\n # missing label in list\n df.set_index([thing3])\n\n def test_set_index_custom_label_hashable_iterable(self):\n # GH#24969\n\n # actual example discussed in GH 24984 was e.g. for shapely.geometry\n # objects (e.g. a collection of Points) that can be both hashable and\n # iterable; using frozenset as a stand-in for testing here\n\n class Thing(frozenset):\n # need to stabilize repr for KeyError (due to random order in sets)\n def __repr__(self) -> str:\n tmp = sorted(self)\n joined_reprs = ", ".join(map(repr, tmp))\n # double curly brace prints one brace in format string\n return f"frozenset({{{joined_reprs}}})"\n\n thing1 = Thing(["One", "red"])\n thing2 = Thing(["Two", "blue"])\n df = DataFrame({thing1: [0, 1], thing2: [2, 3]})\n expected = DataFrame({thing1: [0, 1]}, index=Index([2, 3], name=thing2))\n\n # use custom label directly\n result = df.set_index(thing2)\n tm.assert_frame_equal(result, expected)\n\n # custom label wrapped in list\n result = df.set_index([thing2])\n tm.assert_frame_equal(result, expected)\n\n # missing key\n thing3 = Thing(["Three", "pink"])\n msg = r"frozenset\(\{'Three', 'pink'\}\)"\n with pytest.raises(KeyError, match=msg):\n # missing label directly\n df.set_index(thing3)\n\n with pytest.raises(KeyError, match=msg):\n # missing label in list\n df.set_index([thing3])\n\n def test_set_index_custom_label_type_raises(self):\n # GH#24969\n\n # purposefully inherit from something unhashable\n class Thing(set):\n def __init__(self, name, color) -> None:\n self.name = name\n self.color = color\n\n def __str__(self) -> str:\n return f"<Thing {repr(self.name)}>"\n\n thing1 = Thing("One", "red")\n thing2 = Thing("Two", "blue")\n df = DataFrame([[0, 2], [1, 3]], columns=[thing1, thing2])\n\n msg = 'The parameter "keys" may be a column key, .*'\n\n with pytest.raises(TypeError, match=msg):\n # use custom label directly\n df.set_index(thing2)\n\n with pytest.raises(TypeError, match=msg):\n # custom label wrapped in list\n df.set_index([thing2])\n\n def test_set_index_periodindex(self):\n # GH#6631\n df = DataFrame(np.random.default_rng(2).random(6))\n idx1 = period_range("2011/01/01", periods=6, freq="M")\n idx2 = period_range("2013", periods=6, freq="Y")\n\n df = df.set_index(idx1)\n tm.assert_index_equal(df.index, idx1)\n df = df.set_index(idx2)\n tm.assert_index_equal(df.index, idx2)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_set_index.py
test_set_index.py
Python
26,570
0.95
0.103542
0.135762
awesome-app
915
2025-05-13T15:48:40.424318
MIT
true
d02c67b85ca75559a466048b5d02e611
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n CategoricalIndex,\n DataFrame,\n Index,\n NaT,\n Series,\n date_range,\n offsets,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameShift:\n def test_shift_axis1_with_valid_fill_value_one_array(self):\n # Case with axis=1 that does not go through the "len(arrays)>1" path\n # in DataFrame.shift\n data = np.random.default_rng(2).standard_normal((5, 3))\n df = DataFrame(data)\n res = df.shift(axis=1, periods=1, fill_value=12345)\n expected = df.T.shift(periods=1, fill_value=12345).T\n tm.assert_frame_equal(res, expected)\n\n # same but with an 1D ExtensionArray backing it\n df2 = df[[0]].astype("Float64")\n res2 = df2.shift(axis=1, periods=1, fill_value=12345)\n expected2 = DataFrame([12345] * 5, dtype="Float64")\n tm.assert_frame_equal(res2, expected2)\n\n def test_shift_deprecate_freq_and_fill_value(self, frame_or_series):\n # Can't pass both!\n obj = frame_or_series(\n np.random.default_rng(2).standard_normal(5),\n index=date_range("1/1/2000", periods=5, freq="h"),\n )\n\n msg = (\n "Passing a 'freq' together with a 'fill_value' silently ignores the "\n "fill_value"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n obj.shift(1, fill_value=1, freq="h")\n\n if frame_or_series is DataFrame:\n obj.columns = date_range("1/1/2000", periods=1, freq="h")\n with tm.assert_produces_warning(FutureWarning, match=msg):\n obj.shift(1, axis=1, fill_value=1, freq="h")\n\n @pytest.mark.parametrize(\n "input_data, output_data",\n [(np.empty(shape=(0,)), []), (np.ones(shape=(2,)), [np.nan, 1.0])],\n )\n def test_shift_non_writable_array(self, input_data, output_data, frame_or_series):\n # GH21049 Verify whether non writable numpy array is shiftable\n input_data.setflags(write=False)\n\n result = frame_or_series(input_data).shift(1)\n if frame_or_series is not Series:\n # need to explicitly specify columns in the empty case\n expected = frame_or_series(\n output_data,\n index=range(len(output_data)),\n columns=range(1),\n dtype="float64",\n )\n else:\n expected = frame_or_series(output_data, dtype="float64")\n\n tm.assert_equal(result, expected)\n\n def test_shift_mismatched_freq(self, frame_or_series):\n ts = frame_or_series(\n np.random.default_rng(2).standard_normal(5),\n index=date_range("1/1/2000", periods=5, freq="h"),\n )\n\n result = ts.shift(1, freq="5min")\n exp_index = ts.index.shift(1, freq="5min")\n tm.assert_index_equal(result.index, exp_index)\n\n # GH#1063, multiple of same base\n result = ts.shift(1, freq="4h")\n exp_index = ts.index + offsets.Hour(4)\n tm.assert_index_equal(result.index, exp_index)\n\n @pytest.mark.parametrize(\n "obj",\n [\n Series([np.arange(5)]),\n date_range("1/1/2011", periods=24, freq="h"),\n Series(range(5), index=date_range("2017", periods=5)),\n ],\n )\n @pytest.mark.parametrize("shift_size", [0, 1, 2])\n def test_shift_always_copy(self, obj, shift_size, frame_or_series):\n # GH#22397\n if frame_or_series is not Series:\n obj = obj.to_frame()\n assert obj.shift(shift_size) is not obj\n\n def test_shift_object_non_scalar_fill(self):\n # shift requires scalar fill_value except for object dtype\n ser = Series(range(3))\n with pytest.raises(ValueError, match="fill_value must be a scalar"):\n ser.shift(1, fill_value=[])\n\n df = ser.to_frame()\n with pytest.raises(ValueError, match="fill_value must be a scalar"):\n df.shift(1, fill_value=np.arange(3))\n\n obj_ser = ser.astype(object)\n result = obj_ser.shift(1, fill_value={})\n assert result[0] == {}\n\n obj_df = obj_ser.to_frame()\n result = obj_df.shift(1, fill_value={})\n assert result.iloc[0, 0] == {}\n\n def test_shift_int(self, datetime_frame, frame_or_series):\n ts = tm.get_obj(datetime_frame, frame_or_series).astype(int)\n shifted = ts.shift(1)\n expected = ts.astype(float).shift(1)\n tm.assert_equal(shifted, expected)\n\n @pytest.mark.parametrize("dtype", ["int32", "int64"])\n def test_shift_32bit_take(self, frame_or_series, dtype):\n # 32-bit taking\n # GH#8129\n index = date_range("2000-01-01", periods=5)\n arr = np.arange(5, dtype=dtype)\n s1 = frame_or_series(arr, index=index)\n p = arr[1]\n result = s1.shift(periods=p)\n expected = frame_or_series([np.nan, 0, 1, 2, 3], index=index)\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize("periods", [1, 2, 3, 4])\n def test_shift_preserve_freqstr(self, periods, frame_or_series):\n # GH#21275\n obj = frame_or_series(\n range(periods),\n index=date_range("2016-1-1 00:00:00", periods=periods, freq="h"),\n )\n\n result = obj.shift(1, "2h")\n\n expected = frame_or_series(\n range(periods),\n index=date_range("2016-1-1 02:00:00", periods=periods, freq="h"),\n )\n tm.assert_equal(result, expected)\n\n def test_shift_dst(self, frame_or_series):\n # GH#13926\n dates = date_range("2016-11-06", freq="h", periods=10, tz="US/Eastern")\n obj = frame_or_series(dates)\n\n res = obj.shift(0)\n tm.assert_equal(res, obj)\n assert tm.get_dtype(res) == "datetime64[ns, US/Eastern]"\n\n res = obj.shift(1)\n exp_vals = [NaT] + dates.astype(object).values.tolist()[:9]\n exp = frame_or_series(exp_vals)\n tm.assert_equal(res, exp)\n assert tm.get_dtype(res) == "datetime64[ns, US/Eastern]"\n\n res = obj.shift(-2)\n exp_vals = dates.astype(object).values.tolist()[2:] + [NaT, NaT]\n exp = frame_or_series(exp_vals)\n tm.assert_equal(res, exp)\n assert tm.get_dtype(res) == "datetime64[ns, US/Eastern]"\n\n @pytest.mark.parametrize("ex", [10, -10, 20, -20])\n def test_shift_dst_beyond(self, frame_or_series, ex):\n # GH#13926\n dates = date_range("2016-11-06", freq="h", periods=10, tz="US/Eastern")\n obj = frame_or_series(dates)\n res = obj.shift(ex)\n exp = frame_or_series([NaT] * 10, dtype="datetime64[ns, US/Eastern]")\n tm.assert_equal(res, exp)\n assert tm.get_dtype(res) == "datetime64[ns, US/Eastern]"\n\n def test_shift_by_zero(self, datetime_frame, frame_or_series):\n # shift by 0\n obj = tm.get_obj(datetime_frame, frame_or_series)\n unshifted = obj.shift(0)\n tm.assert_equal(unshifted, obj)\n\n def test_shift(self, datetime_frame):\n # naive shift\n ser = datetime_frame["A"]\n\n shifted = datetime_frame.shift(5)\n tm.assert_index_equal(shifted.index, datetime_frame.index)\n\n shifted_ser = ser.shift(5)\n tm.assert_series_equal(shifted["A"], shifted_ser)\n\n shifted = datetime_frame.shift(-5)\n tm.assert_index_equal(shifted.index, datetime_frame.index)\n\n shifted_ser = ser.shift(-5)\n tm.assert_series_equal(shifted["A"], shifted_ser)\n\n unshifted = datetime_frame.shift(5).shift(-5)\n tm.assert_numpy_array_equal(\n unshifted.dropna().values, datetime_frame.values[:-5]\n )\n\n unshifted_ser = ser.shift(5).shift(-5)\n tm.assert_numpy_array_equal(unshifted_ser.dropna().values, ser.values[:-5])\n\n def test_shift_by_offset(self, datetime_frame, frame_or_series):\n # shift by DateOffset\n obj = tm.get_obj(datetime_frame, frame_or_series)\n offset = offsets.BDay()\n\n shifted = obj.shift(5, freq=offset)\n assert len(shifted) == len(obj)\n unshifted = shifted.shift(-5, freq=offset)\n tm.assert_equal(unshifted, obj)\n\n shifted2 = obj.shift(5, freq="B")\n tm.assert_equal(shifted, shifted2)\n\n unshifted = obj.shift(0, freq=offset)\n tm.assert_equal(unshifted, obj)\n\n d = obj.index[0]\n shifted_d = d + offset * 5\n if frame_or_series is DataFrame:\n tm.assert_series_equal(obj.xs(d), shifted.xs(shifted_d), check_names=False)\n else:\n tm.assert_almost_equal(obj.at[d], shifted.at[shifted_d])\n\n def test_shift_with_periodindex(self, frame_or_series):\n # Shifting with PeriodIndex\n ps = DataFrame(\n np.arange(4, dtype=float), index=pd.period_range("2020-01-01", periods=4)\n )\n ps = tm.get_obj(ps, frame_or_series)\n\n shifted = ps.shift(1)\n unshifted = shifted.shift(-1)\n tm.assert_index_equal(shifted.index, ps.index)\n tm.assert_index_equal(unshifted.index, ps.index)\n if frame_or_series is DataFrame:\n tm.assert_numpy_array_equal(\n unshifted.iloc[:, 0].dropna().values, ps.iloc[:-1, 0].values\n )\n else:\n tm.assert_numpy_array_equal(unshifted.dropna().values, ps.values[:-1])\n\n shifted2 = ps.shift(1, "D")\n shifted3 = ps.shift(1, offsets.Day())\n tm.assert_equal(shifted2, shifted3)\n tm.assert_equal(ps, shifted2.shift(-1, "D"))\n\n msg = "does not match PeriodIndex freq"\n with pytest.raises(ValueError, match=msg):\n ps.shift(freq="W")\n\n # legacy support\n shifted4 = ps.shift(1, freq="D")\n tm.assert_equal(shifted2, shifted4)\n\n shifted5 = ps.shift(1, freq=offsets.Day())\n tm.assert_equal(shifted5, shifted4)\n\n def test_shift_other_axis(self):\n # shift other axis\n # GH#6371\n df = DataFrame(np.random.default_rng(2).random((10, 5)))\n expected = pd.concat(\n [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]],\n ignore_index=True,\n axis=1,\n )\n result = df.shift(1, axis=1)\n tm.assert_frame_equal(result, expected)\n\n def test_shift_named_axis(self):\n # shift named axis\n df = DataFrame(np.random.default_rng(2).random((10, 5)))\n expected = pd.concat(\n [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]],\n ignore_index=True,\n axis=1,\n )\n result = df.shift(1, axis="columns")\n tm.assert_frame_equal(result, expected)\n\n def test_shift_other_axis_with_freq(self, datetime_frame):\n obj = datetime_frame.T\n offset = offsets.BDay()\n\n # GH#47039\n shifted = obj.shift(5, freq=offset, axis=1)\n assert len(shifted) == len(obj)\n unshifted = shifted.shift(-5, freq=offset, axis=1)\n tm.assert_equal(unshifted, obj)\n\n def test_shift_bool(self):\n df = DataFrame({"high": [True, False], "low": [False, False]})\n rs = df.shift(1)\n xp = DataFrame(\n np.array([[np.nan, np.nan], [True, False]], dtype=object),\n columns=["high", "low"],\n )\n tm.assert_frame_equal(rs, xp)\n\n def test_shift_categorical1(self, frame_or_series):\n # GH#9416\n obj = frame_or_series(["a", "b", "c", "d"], dtype="category")\n\n rt = obj.shift(1).shift(-1)\n tm.assert_equal(obj.iloc[:-1], rt.dropna())\n\n def get_cat_values(ndframe):\n # For Series we could just do ._values; for DataFrame\n # we may be able to do this if we ever have 2D Categoricals\n return ndframe._mgr.arrays[0]\n\n cat = get_cat_values(obj)\n\n sp1 = obj.shift(1)\n tm.assert_index_equal(obj.index, sp1.index)\n assert np.all(get_cat_values(sp1).codes[:1] == -1)\n assert np.all(cat.codes[:-1] == get_cat_values(sp1).codes[1:])\n\n sn2 = obj.shift(-2)\n tm.assert_index_equal(obj.index, sn2.index)\n assert np.all(get_cat_values(sn2).codes[-2:] == -1)\n assert np.all(cat.codes[2:] == get_cat_values(sn2).codes[:-2])\n\n tm.assert_index_equal(cat.categories, get_cat_values(sp1).categories)\n tm.assert_index_equal(cat.categories, get_cat_values(sn2).categories)\n\n def test_shift_categorical(self):\n # GH#9416\n s1 = Series(["a", "b", "c"], dtype="category")\n s2 = Series(["A", "B", "C"], dtype="category")\n df = DataFrame({"one": s1, "two": s2})\n rs = df.shift(1)\n xp = DataFrame({"one": s1.shift(1), "two": s2.shift(1)})\n tm.assert_frame_equal(rs, xp)\n\n def test_shift_categorical_fill_value(self, frame_or_series):\n ts = frame_or_series(["a", "b", "c", "d"], dtype="category")\n res = ts.shift(1, fill_value="a")\n expected = frame_or_series(\n pd.Categorical(\n ["a", "a", "b", "c"], categories=["a", "b", "c", "d"], ordered=False\n )\n )\n tm.assert_equal(res, expected)\n\n # check for incorrect fill_value\n msg = r"Cannot setitem on a Categorical with a new category \(f\)"\n with pytest.raises(TypeError, match=msg):\n ts.shift(1, fill_value="f")\n\n def test_shift_fill_value(self, frame_or_series):\n # GH#24128\n dti = date_range("1/1/2000", periods=5, freq="h")\n\n ts = frame_or_series([1.0, 2.0, 3.0, 4.0, 5.0], index=dti)\n exp = frame_or_series([0.0, 1.0, 2.0, 3.0, 4.0], index=dti)\n # check that fill value works\n result = ts.shift(1, fill_value=0.0)\n tm.assert_equal(result, exp)\n\n exp = frame_or_series([0.0, 0.0, 1.0, 2.0, 3.0], index=dti)\n result = ts.shift(2, fill_value=0.0)\n tm.assert_equal(result, exp)\n\n ts = frame_or_series([1, 2, 3])\n res = ts.shift(2, fill_value=0)\n assert tm.get_dtype(res) == tm.get_dtype(ts)\n\n # retain integer dtype\n obj = frame_or_series([1, 2, 3, 4, 5], index=dti)\n exp = frame_or_series([0, 1, 2, 3, 4], index=dti)\n result = obj.shift(1, fill_value=0)\n tm.assert_equal(result, exp)\n\n exp = frame_or_series([0, 0, 1, 2, 3], index=dti)\n result = obj.shift(2, fill_value=0)\n tm.assert_equal(result, exp)\n\n def test_shift_empty(self):\n # Regression test for GH#8019\n df = DataFrame({"foo": []})\n rs = df.shift(-1)\n\n tm.assert_frame_equal(df, rs)\n\n def test_shift_duplicate_columns(self):\n # GH#9092; verify that position-based shifting works\n # in the presence of duplicate columns\n column_lists = [list(range(5)), [1] * 5, [1, 1, 2, 2, 1]]\n data = np.random.default_rng(2).standard_normal((20, 5))\n\n shifted = []\n for columns in column_lists:\n df = DataFrame(data.copy(), columns=columns)\n for s in range(5):\n df.iloc[:, s] = df.iloc[:, s].shift(s + 1)\n df.columns = range(5)\n shifted.append(df)\n\n # sanity check the base case\n nulls = shifted[0].isna().sum()\n tm.assert_series_equal(nulls, Series(range(1, 6), dtype="int64"))\n\n # check all answers are the same\n tm.assert_frame_equal(shifted[0], shifted[1])\n tm.assert_frame_equal(shifted[0], shifted[2])\n\n def test_shift_axis1_multiple_blocks(self, using_array_manager):\n # GH#35488\n df1 = DataFrame(np.random.default_rng(2).integers(1000, size=(5, 3)))\n df2 = DataFrame(np.random.default_rng(2).integers(1000, size=(5, 2)))\n df3 = pd.concat([df1, df2], axis=1)\n if not using_array_manager:\n assert len(df3._mgr.blocks) == 2\n\n result = df3.shift(2, axis=1)\n\n expected = df3.take([-1, -1, 0, 1, 2], axis=1)\n # Explicit cast to float to avoid implicit cast when setting nan.\n # Column names aren't unique, so directly calling `expected.astype` won't work.\n expected = expected.pipe(\n lambda df: df.set_axis(range(df.shape[1]), axis=1)\n .astype({0: "float", 1: "float"})\n .set_axis(df.columns, axis=1)\n )\n expected.iloc[:, :2] = np.nan\n expected.columns = df3.columns\n\n tm.assert_frame_equal(result, expected)\n\n # Case with periods < 0\n # rebuild df3 because `take` call above consolidated\n df3 = pd.concat([df1, df2], axis=1)\n if not using_array_manager:\n assert len(df3._mgr.blocks) == 2\n result = df3.shift(-2, axis=1)\n\n expected = df3.take([2, 3, 4, -1, -1], axis=1)\n # Explicit cast to float to avoid implicit cast when setting nan.\n # Column names aren't unique, so directly calling `expected.astype` won't work.\n expected = expected.pipe(\n lambda df: df.set_axis(range(df.shape[1]), axis=1)\n .astype({3: "float", 4: "float"})\n .set_axis(df.columns, axis=1)\n )\n expected.iloc[:, -2:] = np.nan\n expected.columns = df3.columns\n\n tm.assert_frame_equal(result, expected)\n\n @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) axis=1 support\n def test_shift_axis1_multiple_blocks_with_int_fill(self):\n # GH#42719\n rng = np.random.default_rng(2)\n df1 = DataFrame(rng.integers(1000, size=(5, 3), dtype=int))\n df2 = DataFrame(rng.integers(1000, size=(5, 2), dtype=int))\n df3 = pd.concat([df1.iloc[:4, 1:3], df2.iloc[:4, :]], axis=1)\n result = df3.shift(2, axis=1, fill_value=np.int_(0))\n assert len(df3._mgr.blocks) == 2\n\n expected = df3.take([-1, -1, 0, 1], axis=1)\n expected.iloc[:, :2] = np.int_(0)\n expected.columns = df3.columns\n\n tm.assert_frame_equal(result, expected)\n\n # Case with periods < 0\n df3 = pd.concat([df1.iloc[:4, 1:3], df2.iloc[:4, :]], axis=1)\n result = df3.shift(-2, axis=1, fill_value=np.int_(0))\n assert len(df3._mgr.blocks) == 2\n\n expected = df3.take([2, 3, -1, -1], axis=1)\n expected.iloc[:, -2:] = np.int_(0)\n expected.columns = df3.columns\n\n tm.assert_frame_equal(result, expected)\n\n def test_period_index_frame_shift_with_freq(self, frame_or_series):\n ps = DataFrame(range(4), index=pd.period_range("2020-01-01", periods=4))\n ps = tm.get_obj(ps, frame_or_series)\n\n shifted = ps.shift(1, freq="infer")\n unshifted = shifted.shift(-1, freq="infer")\n tm.assert_equal(unshifted, ps)\n\n shifted2 = ps.shift(freq="D")\n tm.assert_equal(shifted, shifted2)\n\n shifted3 = ps.shift(freq=offsets.Day())\n tm.assert_equal(shifted, shifted3)\n\n def test_datetime_frame_shift_with_freq(self, datetime_frame, frame_or_series):\n dtobj = tm.get_obj(datetime_frame, frame_or_series)\n shifted = dtobj.shift(1, freq="infer")\n unshifted = shifted.shift(-1, freq="infer")\n tm.assert_equal(dtobj, unshifted)\n\n shifted2 = dtobj.shift(freq=dtobj.index.freq)\n tm.assert_equal(shifted, shifted2)\n\n inferred_ts = DataFrame(\n datetime_frame.values,\n Index(np.asarray(datetime_frame.index)),\n columns=datetime_frame.columns,\n )\n inferred_ts = tm.get_obj(inferred_ts, frame_or_series)\n shifted = inferred_ts.shift(1, freq="infer")\n expected = dtobj.shift(1, freq="infer")\n expected.index = expected.index._with_freq(None)\n tm.assert_equal(shifted, expected)\n\n unshifted = shifted.shift(-1, freq="infer")\n tm.assert_equal(unshifted, inferred_ts)\n\n def test_period_index_frame_shift_with_freq_error(self, frame_or_series):\n ps = DataFrame(range(4), index=pd.period_range("2020-01-01", periods=4))\n ps = tm.get_obj(ps, frame_or_series)\n msg = "Given freq M does not match PeriodIndex freq D"\n with pytest.raises(ValueError, match=msg):\n ps.shift(freq="M")\n\n def test_datetime_frame_shift_with_freq_error(\n self, datetime_frame, frame_or_series\n ):\n dtobj = tm.get_obj(datetime_frame, frame_or_series)\n no_freq = dtobj.iloc[[0, 5, 7]]\n msg = "Freq was not set in the index hence cannot be inferred"\n with pytest.raises(ValueError, match=msg):\n no_freq.shift(freq="infer")\n\n def test_shift_dt64values_int_fill_deprecated(self):\n # GH#31971\n ser = Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")])\n\n with pytest.raises(TypeError, match="value should be a"):\n ser.shift(1, fill_value=0)\n\n df = ser.to_frame()\n with pytest.raises(TypeError, match="value should be a"):\n df.shift(1, fill_value=0)\n\n # axis = 1\n df2 = DataFrame({"A": ser, "B": ser})\n df2._consolidate_inplace()\n\n result = df2.shift(1, axis=1, fill_value=0)\n expected = DataFrame({"A": [0, 0], "B": df2["A"]})\n tm.assert_frame_equal(result, expected)\n\n # same thing but not consolidated; pre-2.0 we got different behavior\n df3 = DataFrame({"A": ser})\n df3["B"] = ser\n assert len(df3._mgr.arrays) == 2\n result = df3.shift(1, axis=1, fill_value=0)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "as_cat",\n [\n pytest.param(\n True,\n marks=pytest.mark.xfail(\n reason="_can_hold_element incorrectly always returns True"\n ),\n ),\n False,\n ],\n )\n @pytest.mark.parametrize(\n "vals",\n [\n date_range("2020-01-01", periods=2),\n date_range("2020-01-01", periods=2, tz="US/Pacific"),\n pd.period_range("2020-01-01", periods=2, freq="D"),\n pd.timedelta_range("2020 Days", periods=2, freq="D"),\n pd.interval_range(0, 3, periods=2),\n pytest.param(\n pd.array([1, 2], dtype="Int64"),\n marks=pytest.mark.xfail(\n reason="_can_hold_element incorrectly always returns True"\n ),\n ),\n pytest.param(\n pd.array([1, 2], dtype="Float32"),\n marks=pytest.mark.xfail(\n reason="_can_hold_element incorrectly always returns True"\n ),\n ),\n ],\n ids=lambda x: str(x.dtype),\n )\n def test_shift_dt64values_axis1_invalid_fill(self, vals, as_cat):\n # GH#44564\n ser = Series(vals)\n if as_cat:\n ser = ser.astype("category")\n\n df = DataFrame({"A": ser})\n result = df.shift(-1, axis=1, fill_value="foo")\n expected = DataFrame({"A": ["foo", "foo"]})\n tm.assert_frame_equal(result, expected)\n\n # same thing but multiple blocks\n df2 = DataFrame({"A": ser, "B": ser})\n df2._consolidate_inplace()\n\n result = df2.shift(-1, axis=1, fill_value="foo")\n expected = DataFrame({"A": df2["B"], "B": ["foo", "foo"]})\n tm.assert_frame_equal(result, expected)\n\n # same thing but not consolidated\n df3 = DataFrame({"A": ser})\n df3["B"] = ser\n assert len(df3._mgr.arrays) == 2\n result = df3.shift(-1, axis=1, fill_value="foo")\n tm.assert_frame_equal(result, expected)\n\n def test_shift_axis1_categorical_columns(self):\n # GH#38434\n ci = CategoricalIndex(["a", "b", "c"])\n df = DataFrame(\n {"a": [1, 3], "b": [2, 4], "c": [5, 6]}, index=ci[:-1], columns=ci\n )\n result = df.shift(axis=1)\n\n expected = DataFrame(\n {"a": [np.nan, np.nan], "b": [1, 3], "c": [2, 4]}, index=ci[:-1], columns=ci\n )\n tm.assert_frame_equal(result, expected)\n\n # periods != 1\n result = df.shift(2, axis=1)\n expected = DataFrame(\n {"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 3]},\n index=ci[:-1],\n columns=ci,\n )\n tm.assert_frame_equal(result, expected)\n\n def test_shift_axis1_many_periods(self):\n # GH#44978 periods > len(columns)\n df = DataFrame(np.random.default_rng(2).random((5, 3)))\n shifted = df.shift(6, axis=1, fill_value=None)\n\n expected = df * np.nan\n tm.assert_frame_equal(shifted, expected)\n\n shifted2 = df.shift(-6, axis=1, fill_value=None)\n tm.assert_frame_equal(shifted2, expected)\n\n def test_shift_with_offsets_freq(self):\n df = DataFrame({"x": [1, 2, 3]}, index=date_range("2000", periods=3))\n shifted = df.shift(freq="1MS")\n expected = DataFrame(\n {"x": [1, 2, 3]},\n index=date_range(start="02/01/2000", end="02/01/2000", periods=3),\n )\n tm.assert_frame_equal(shifted, expected)\n\n def test_shift_with_iterable_basic_functionality(self):\n # GH#44424\n data = {"a": [1, 2, 3], "b": [4, 5, 6]}\n shifts = [0, 1, 2]\n\n df = DataFrame(data)\n shifted = df.shift(shifts)\n\n expected = DataFrame(\n {\n "a_0": [1, 2, 3],\n "b_0": [4, 5, 6],\n "a_1": [np.nan, 1.0, 2.0],\n "b_1": [np.nan, 4.0, 5.0],\n "a_2": [np.nan, np.nan, 1.0],\n "b_2": [np.nan, np.nan, 4.0],\n }\n )\n tm.assert_frame_equal(expected, shifted)\n\n def test_shift_with_iterable_series(self):\n # GH#44424\n data = {"a": [1, 2, 3]}\n shifts = [0, 1, 2]\n\n df = DataFrame(data)\n s = df["a"]\n tm.assert_frame_equal(s.shift(shifts), df.shift(shifts))\n\n def test_shift_with_iterable_freq_and_fill_value(self):\n # GH#44424\n df = DataFrame(\n np.random.default_rng(2).standard_normal(5),\n index=date_range("1/1/2000", periods=5, freq="h"),\n )\n\n tm.assert_frame_equal(\n # rename because shift with an iterable leads to str column names\n df.shift([1], fill_value=1).rename(columns=lambda x: int(x[0])),\n df.shift(1, fill_value=1),\n )\n\n tm.assert_frame_equal(\n df.shift([1], freq="h").rename(columns=lambda x: int(x[0])),\n df.shift(1, freq="h"),\n )\n\n msg = (\n "Passing a 'freq' together with a 'fill_value' silently ignores the "\n "fill_value"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n df.shift([1, 2], fill_value=1, freq="h")\n\n def test_shift_with_iterable_check_other_arguments(self):\n # GH#44424\n data = {"a": [1, 2], "b": [4, 5]}\n shifts = [0, 1]\n df = DataFrame(data)\n\n # test suffix\n shifted = df[["a"]].shift(shifts, suffix="_suffix")\n expected = DataFrame({"a_suffix_0": [1, 2], "a_suffix_1": [np.nan, 1.0]})\n tm.assert_frame_equal(shifted, expected)\n\n # check bad inputs when doing multiple shifts\n msg = "If `periods` contains multiple shifts, `axis` cannot be 1."\n with pytest.raises(ValueError, match=msg):\n df.shift(shifts, axis=1)\n\n msg = "Periods must be integer, but s is <class 'str'>."\n with pytest.raises(TypeError, match=msg):\n df.shift(["s"])\n\n msg = "If `periods` is an iterable, it cannot be empty."\n with pytest.raises(ValueError, match=msg):\n df.shift([])\n\n msg = "Cannot specify `suffix` if `periods` is an int."\n with pytest.raises(ValueError, match=msg):\n df.shift(1, suffix="fails")\n\n def test_shift_axis_one_empty(self):\n # GH#57301\n df = DataFrame()\n result = df.shift(1, axis=1)\n tm.assert_frame_equal(result, df)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_shift.py
test_shift.py
Python
27,731
0.95
0.078534
0.098101
vue-tools
703
2024-11-22T09:52:38.189532
BSD-3-Clause
true
730ab4830e5dbed1423f095055d5fa97
import numpy as np\nimport pytest\n\nfrom pandas import DataFrame\n\n\n@pytest.mark.parametrize(\n "data, index, expected",\n [\n ({"col1": [1], "col2": [3]}, None, 2),\n ({}, None, 0),\n ({"col1": [1, np.nan], "col2": [3, 4]}, None, 4),\n ({"col1": [1, 2], "col2": [3, 4]}, [["a", "b"], [1, 2]], 4),\n ({"col1": [1, 2, 3, 4], "col2": [3, 4, 5, 6]}, ["x", "y", "a", "b"], 8),\n ],\n)\ndef test_size(data, index, expected):\n # GH#52897\n df = DataFrame(data, index=index)\n assert df.size == expected\n assert isinstance(df.size, int)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_size.py
test_size.py
Python
571
0.95
0.047619
0.055556
python-kit
362
2025-05-03T02:29:36.175605
GPL-3.0
true
4b66880cb686b390fc2b361e264d5f77
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n CategoricalDtype,\n CategoricalIndex,\n DataFrame,\n IntervalIndex,\n MultiIndex,\n RangeIndex,\n Series,\n Timestamp,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameSortIndex:\n def test_sort_index_and_reconstruction_doc_example(self):\n # doc example\n df = DataFrame(\n {"value": [1, 2, 3, 4]},\n index=MultiIndex(\n levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]\n ),\n )\n assert df.index._is_lexsorted()\n assert not df.index.is_monotonic_increasing\n\n # sort it\n expected = DataFrame(\n {"value": [2, 1, 4, 3]},\n index=MultiIndex(\n levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]\n ),\n )\n result = df.sort_index()\n assert result.index.is_monotonic_increasing\n tm.assert_frame_equal(result, expected)\n\n # reconstruct\n result = df.sort_index().copy()\n result.index = result.index._sort_levels_monotonic()\n assert result.index.is_monotonic_increasing\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index_non_existent_label_multiindex(self):\n # GH#12261\n df = DataFrame(0, columns=[], index=MultiIndex.from_product([[], []]))\n with tm.assert_produces_warning(None):\n df.loc["b", "2"] = 1\n df.loc["a", "3"] = 1\n result = df.sort_index().index.is_monotonic_increasing\n assert result is True\n\n def test_sort_index_reorder_on_ops(self):\n # GH#15687\n df = DataFrame(\n np.random.default_rng(2).standard_normal((8, 2)),\n index=MultiIndex.from_product(\n [["a", "b"], ["big", "small"], ["red", "blu"]],\n names=["letter", "size", "color"],\n ),\n columns=["near", "far"],\n )\n df = df.sort_index()\n\n def my_func(group):\n group.index = ["newz", "newa"]\n return group\n\n result = df.groupby(level=["letter", "size"]).apply(my_func).sort_index()\n expected = MultiIndex.from_product(\n [["a", "b"], ["big", "small"], ["newa", "newz"]],\n names=["letter", "size", None],\n )\n\n tm.assert_index_equal(result.index, expected)\n\n def test_sort_index_nan_multiindex(self):\n # GH#14784\n # incorrect sorting w.r.t. nans\n tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]]\n mi = MultiIndex.from_tuples(tuples)\n\n df = DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list("ABCD"))\n s = Series(np.arange(4), index=mi)\n\n df2 = DataFrame(\n {\n "date": pd.DatetimeIndex(\n [\n "20121002",\n "20121007",\n "20130130",\n "20130202",\n "20130305",\n "20121002",\n "20121207",\n "20130130",\n "20130202",\n "20130305",\n "20130202",\n "20130305",\n ]\n ),\n "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5],\n "whole_cost": [\n 1790,\n np.nan,\n 280,\n 259,\n np.nan,\n 623,\n 90,\n 312,\n np.nan,\n 301,\n 359,\n 801,\n ],\n "cost": [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12],\n }\n ).set_index(["date", "user_id"])\n\n # sorting frame, default nan position is last\n result = df.sort_index()\n expected = df.iloc[[3, 0, 2, 1], :]\n tm.assert_frame_equal(result, expected)\n\n # sorting frame, nan position last\n result = df.sort_index(na_position="last")\n expected = df.iloc[[3, 0, 2, 1], :]\n tm.assert_frame_equal(result, expected)\n\n # sorting frame, nan position first\n result = df.sort_index(na_position="first")\n expected = df.iloc[[1, 2, 3, 0], :]\n tm.assert_frame_equal(result, expected)\n\n # sorting frame with removed rows\n result = df2.dropna().sort_index()\n expected = df2.sort_index().dropna()\n tm.assert_frame_equal(result, expected)\n\n # sorting series, default nan position is last\n result = s.sort_index()\n expected = s.iloc[[3, 0, 2, 1]]\n tm.assert_series_equal(result, expected)\n\n # sorting series, nan position last\n result = s.sort_index(na_position="last")\n expected = s.iloc[[3, 0, 2, 1]]\n tm.assert_series_equal(result, expected)\n\n # sorting series, nan position first\n result = s.sort_index(na_position="first")\n expected = s.iloc[[1, 2, 3, 0]]\n tm.assert_series_equal(result, expected)\n\n def test_sort_index_nan(self):\n # GH#3917\n\n # Test DataFrame with nan label\n df = DataFrame(\n {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]},\n index=[1, 2, 3, 4, 5, 6, np.nan],\n )\n\n # NaN label, ascending=True, na_position='last'\n sorted_df = df.sort_index(kind="quicksort", ascending=True, na_position="last")\n expected = DataFrame(\n {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]},\n index=[1, 2, 3, 4, 5, 6, np.nan],\n )\n tm.assert_frame_equal(sorted_df, expected)\n\n # NaN label, ascending=True, na_position='first'\n sorted_df = df.sort_index(na_position="first")\n expected = DataFrame(\n {"A": [4, 1, 2, np.nan, 1, 6, 8], "B": [5, 9, np.nan, 5, 2, 5, 4]},\n index=[np.nan, 1, 2, 3, 4, 5, 6],\n )\n tm.assert_frame_equal(sorted_df, expected)\n\n # NaN label, ascending=False, na_position='last'\n sorted_df = df.sort_index(kind="quicksort", ascending=False)\n expected = DataFrame(\n {"A": [8, 6, 1, np.nan, 2, 1, 4], "B": [4, 5, 2, 5, np.nan, 9, 5]},\n index=[6, 5, 4, 3, 2, 1, np.nan],\n )\n tm.assert_frame_equal(sorted_df, expected)\n\n # NaN label, ascending=False, na_position='first'\n sorted_df = df.sort_index(\n kind="quicksort", ascending=False, na_position="first"\n )\n expected = DataFrame(\n {"A": [4, 8, 6, 1, np.nan, 2, 1], "B": [5, 4, 5, 2, 5, np.nan, 9]},\n index=[np.nan, 6, 5, 4, 3, 2, 1],\n )\n tm.assert_frame_equal(sorted_df, expected)\n\n def test_sort_index_multi_index(self):\n # GH#25775, testing that sorting by index works with a multi-index.\n df = DataFrame(\n {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")}\n )\n result = df.set_index(list("abc")).sort_index(level=list("ba"))\n\n expected = DataFrame(\n {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")}\n )\n expected = expected.set_index(list("abc"))\n\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index_inplace(self):\n frame = DataFrame(\n np.random.default_rng(2).standard_normal((4, 4)),\n index=[1, 2, 3, 4],\n columns=["A", "B", "C", "D"],\n )\n\n # axis=0\n unordered = frame.loc[[3, 2, 4, 1]]\n a_values = unordered["A"]\n df = unordered.copy()\n return_value = df.sort_index(inplace=True)\n assert return_value is None\n expected = frame\n tm.assert_frame_equal(df, expected)\n # GH 44153 related\n # Used to be a_id != id(df["A"]), but flaky in the CI\n assert a_values is not df["A"]\n\n df = unordered.copy()\n return_value = df.sort_index(ascending=False, inplace=True)\n assert return_value is None\n expected = frame[::-1]\n tm.assert_frame_equal(df, expected)\n\n # axis=1\n unordered = frame.loc[:, ["D", "B", "C", "A"]]\n df = unordered.copy()\n return_value = df.sort_index(axis=1, inplace=True)\n assert return_value is None\n expected = frame\n tm.assert_frame_equal(df, expected)\n\n df = unordered.copy()\n return_value = df.sort_index(axis=1, ascending=False, inplace=True)\n assert return_value is None\n expected = frame.iloc[:, ::-1]\n tm.assert_frame_equal(df, expected)\n\n def test_sort_index_different_sortorder(self):\n A = np.arange(20).repeat(5)\n B = np.tile(np.arange(5), 20)\n\n indexer = np.random.default_rng(2).permutation(100)\n A = A.take(indexer)\n B = B.take(indexer)\n\n df = DataFrame(\n {"A": A, "B": B, "C": np.random.default_rng(2).standard_normal(100)}\n )\n\n ex_indexer = np.lexsort((df.B.max() - df.B, df.A))\n expected = df.take(ex_indexer)\n\n # test with multiindex, too\n idf = df.set_index(["A", "B"])\n\n result = idf.sort_index(ascending=[1, 0])\n expected = idf.take(ex_indexer)\n tm.assert_frame_equal(result, expected)\n\n # also, Series!\n result = idf["C"].sort_index(ascending=[1, 0])\n tm.assert_series_equal(result, expected["C"])\n\n def test_sort_index_level(self):\n mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC"))\n df = DataFrame([[1, 2], [3, 4]], mi)\n\n result = df.sort_index(level="A", sort_remaining=False)\n expected = df\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_index(level=["A", "B"], sort_remaining=False)\n expected = df\n tm.assert_frame_equal(result, expected)\n\n # Error thrown by sort_index when\n # first index is sorted last (GH#26053)\n result = df.sort_index(level=["C", "B", "A"])\n expected = df.iloc[[1, 0]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_index(level=["B", "C", "A"])\n expected = df.iloc[[1, 0]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_index(level=["C", "A"])\n expected = df.iloc[[1, 0]]\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index_categorical_index(self):\n df = DataFrame(\n {\n "A": np.arange(6, dtype="int64"),\n "B": Series(list("aabbca")).astype(CategoricalDtype(list("cab"))),\n }\n ).set_index("B")\n\n result = df.sort_index()\n expected = df.iloc[[4, 0, 1, 5, 2, 3]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_index(ascending=False)\n expected = df.iloc[[2, 3, 0, 1, 5, 4]]\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index(self):\n # GH#13496\n\n frame = DataFrame(\n np.arange(16).reshape(4, 4),\n index=[1, 2, 3, 4],\n columns=["A", "B", "C", "D"],\n )\n\n # axis=0 : sort rows by index labels\n unordered = frame.loc[[3, 2, 4, 1]]\n result = unordered.sort_index(axis=0)\n expected = frame\n tm.assert_frame_equal(result, expected)\n\n result = unordered.sort_index(ascending=False)\n expected = frame[::-1]\n tm.assert_frame_equal(result, expected)\n\n # axis=1 : sort columns by column names\n unordered = frame.iloc[:, [2, 1, 3, 0]]\n result = unordered.sort_index(axis=1)\n tm.assert_frame_equal(result, frame)\n\n result = unordered.sort_index(axis=1, ascending=False)\n expected = frame.iloc[:, ::-1]\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("level", ["A", 0]) # GH#21052\n def test_sort_index_multiindex(self, level):\n # GH#13496\n\n # sort rows by specified level of multi-index\n mi = MultiIndex.from_tuples(\n [[2, 1, 3], [2, 1, 2], [1, 1, 1]], names=list("ABC")\n )\n df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mi)\n\n expected_mi = MultiIndex.from_tuples(\n [[1, 1, 1], [2, 1, 2], [2, 1, 3]], names=list("ABC")\n )\n expected = DataFrame([[5, 6], [3, 4], [1, 2]], index=expected_mi)\n result = df.sort_index(level=level)\n tm.assert_frame_equal(result, expected)\n\n # sort_remaining=False\n expected_mi = MultiIndex.from_tuples(\n [[1, 1, 1], [2, 1, 3], [2, 1, 2]], names=list("ABC")\n )\n expected = DataFrame([[5, 6], [1, 2], [3, 4]], index=expected_mi)\n result = df.sort_index(level=level, sort_remaining=False)\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index_intervalindex(self):\n # this is a de-facto sort via unstack\n # confirming that we sort in the order of the bins\n y = Series(np.random.default_rng(2).standard_normal(100))\n x1 = Series(np.sign(np.random.default_rng(2).standard_normal(100)))\n x2 = pd.cut(\n Series(np.random.default_rng(2).standard_normal(100)),\n bins=[-3, -0.5, 0, 0.5, 3],\n )\n model = pd.concat([y, x1, x2], axis=1, keys=["Y", "X1", "X2"])\n\n result = model.groupby(["X1", "X2"], observed=True).mean().unstack()\n expected = IntervalIndex.from_tuples(\n [(-3.0, -0.5), (-0.5, 0.0), (0.0, 0.5), (0.5, 3.0)], closed="right"\n )\n result = result.columns.levels[1].categories\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("inplace", [True, False])\n @pytest.mark.parametrize(\n "original_dict, sorted_dict, ascending, ignore_index, output_index",\n [\n ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, True, [0, 1, 2]),\n ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, True, [0, 1, 2]),\n ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, False, [5, 3, 2]),\n ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, False, [2, 3, 5]),\n ],\n )\n def test_sort_index_ignore_index(\n self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index\n ):\n # GH 30114\n original_index = [2, 5, 3]\n df = DataFrame(original_dict, index=original_index)\n expected_df = DataFrame(sorted_dict, index=output_index)\n kwargs = {\n "ascending": ascending,\n "ignore_index": ignore_index,\n "inplace": inplace,\n }\n\n if inplace:\n result_df = df.copy()\n result_df.sort_index(**kwargs)\n else:\n result_df = df.sort_index(**kwargs)\n\n tm.assert_frame_equal(result_df, expected_df)\n tm.assert_frame_equal(df, DataFrame(original_dict, index=original_index))\n\n @pytest.mark.parametrize("inplace", [True, False])\n @pytest.mark.parametrize("ignore_index", [True, False])\n def test_respect_ignore_index(self, inplace, ignore_index):\n # GH 43591\n df = DataFrame({"a": [1, 2, 3]}, index=RangeIndex(4, -1, -2))\n result = df.sort_index(\n ascending=False, ignore_index=ignore_index, inplace=inplace\n )\n\n if inplace:\n result = df\n if ignore_index:\n expected = DataFrame({"a": [1, 2, 3]})\n else:\n expected = DataFrame({"a": [1, 2, 3]}, index=RangeIndex(4, -1, -2))\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("inplace", [True, False])\n @pytest.mark.parametrize(\n "original_dict, sorted_dict, ascending, ignore_index, output_index",\n [\n (\n {"M1": [1, 2], "M2": [3, 4]},\n {"M1": [1, 2], "M2": [3, 4]},\n True,\n True,\n [0, 1],\n ),\n (\n {"M1": [1, 2], "M2": [3, 4]},\n {"M1": [2, 1], "M2": [4, 3]},\n False,\n True,\n [0, 1],\n ),\n (\n {"M1": [1, 2], "M2": [3, 4]},\n {"M1": [1, 2], "M2": [3, 4]},\n True,\n False,\n MultiIndex.from_tuples([(2, 1), (3, 4)], names=list("AB")),\n ),\n (\n {"M1": [1, 2], "M2": [3, 4]},\n {"M1": [2, 1], "M2": [4, 3]},\n False,\n False,\n MultiIndex.from_tuples([(3, 4), (2, 1)], names=list("AB")),\n ),\n ],\n )\n def test_sort_index_ignore_index_multi_index(\n self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index\n ):\n # GH 30114, this is to test ignore_index on MultiIndex of index\n mi = MultiIndex.from_tuples([(2, 1), (3, 4)], names=list("AB"))\n df = DataFrame(original_dict, index=mi)\n expected_df = DataFrame(sorted_dict, index=output_index)\n\n kwargs = {\n "ascending": ascending,\n "ignore_index": ignore_index,\n "inplace": inplace,\n }\n\n if inplace:\n result_df = df.copy()\n result_df.sort_index(**kwargs)\n else:\n result_df = df.sort_index(**kwargs)\n\n tm.assert_frame_equal(result_df, expected_df)\n tm.assert_frame_equal(df, DataFrame(original_dict, index=mi))\n\n def test_sort_index_categorical_multiindex(self):\n # GH#15058\n df = DataFrame(\n {\n "a": range(6),\n "l1": pd.Categorical(\n ["a", "a", "b", "b", "c", "c"],\n categories=["c", "a", "b"],\n ordered=True,\n ),\n "l2": [0, 1, 0, 1, 0, 1],\n }\n )\n result = df.set_index(["l1", "l2"]).sort_index()\n expected = DataFrame(\n [4, 5, 0, 1, 2, 3],\n columns=["a"],\n index=MultiIndex(\n levels=[\n CategoricalIndex(\n ["c", "a", "b"],\n categories=["c", "a", "b"],\n ordered=True,\n name="l1",\n dtype="category",\n ),\n [0, 1],\n ],\n codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],\n names=["l1", "l2"],\n ),\n )\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index_and_reconstruction(self):\n # GH#15622\n # lexsortedness should be identical\n # across MultiIndex construction methods\n\n df = DataFrame([[1, 1], [2, 2]], index=list("ab"))\n expected = DataFrame(\n [[1, 1], [2, 2], [1, 1], [2, 2]],\n index=MultiIndex.from_tuples(\n [(0.5, "a"), (0.5, "b"), (0.8, "a"), (0.8, "b")]\n ),\n )\n assert expected.index._is_lexsorted()\n\n result = DataFrame(\n [[1, 1], [2, 2], [1, 1], [2, 2]],\n index=MultiIndex.from_product([[0.5, 0.8], list("ab")]),\n )\n result = result.sort_index()\n assert result.index.is_monotonic_increasing\n\n tm.assert_frame_equal(result, expected)\n\n result = DataFrame(\n [[1, 1], [2, 2], [1, 1], [2, 2]],\n index=MultiIndex(\n levels=[[0.5, 0.8], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]\n ),\n )\n result = result.sort_index()\n assert result.index._is_lexsorted()\n\n tm.assert_frame_equal(result, expected)\n\n concatted = pd.concat([df, df], keys=[0.8, 0.5])\n result = concatted.sort_index()\n\n assert result.index.is_monotonic_increasing\n\n tm.assert_frame_equal(result, expected)\n\n # GH#14015\n df = DataFrame(\n [[1, 2], [6, 7]],\n columns=MultiIndex.from_tuples(\n [(0, "20160811 12:00:00"), (0, "20160809 12:00:00")],\n names=["l1", "Date"],\n ),\n )\n\n df.columns = df.columns.set_levels(\n pd.to_datetime(df.columns.levels[1]), level=1\n )\n assert not df.columns.is_monotonic_increasing\n result = df.sort_index(axis=1)\n assert result.columns.is_monotonic_increasing\n result = df.sort_index(axis=1, level=1)\n assert result.columns.is_monotonic_increasing\n\n # TODO: better name, de-duplicate with test_sort_index_level above\n def test_sort_index_level2(self, multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n\n df = frame.copy()\n df.index = np.arange(len(df))\n\n # axis=1\n\n # series\n a_sorted = frame["A"].sort_index(level=0)\n\n # preserve names\n assert a_sorted.index.names == frame.index.names\n\n # inplace\n rs = frame.copy()\n return_value = rs.sort_index(level=0, inplace=True)\n assert return_value is None\n tm.assert_frame_equal(rs, frame.sort_index(level=0))\n\n def test_sort_index_level_large_cardinality(self):\n # GH#2684 (int64)\n index = MultiIndex.from_arrays([np.arange(4000)] * 3)\n df = DataFrame(\n np.random.default_rng(2).standard_normal(4000).astype("int64"), index=index\n )\n\n # it works!\n result = df.sort_index(level=0)\n assert result.index._lexsort_depth == 3\n\n # GH#2684 (int32)\n index = MultiIndex.from_arrays([np.arange(4000)] * 3)\n df = DataFrame(\n np.random.default_rng(2).standard_normal(4000).astype("int32"), index=index\n )\n\n # it works!\n result = df.sort_index(level=0)\n assert (result.dtypes.values == df.dtypes.values).all()\n assert result.index._lexsort_depth == 3\n\n def test_sort_index_level_by_name(self, multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n\n frame.index.names = ["first", "second"]\n result = frame.sort_index(level="second")\n expected = frame.sort_index(level=1)\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index_level_mixed(self, multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n\n sorted_before = frame.sort_index(level=1)\n\n df = frame.copy()\n df["foo"] = "bar"\n sorted_after = df.sort_index(level=1)\n tm.assert_frame_equal(sorted_before, sorted_after.drop(["foo"], axis=1))\n\n dft = frame.T\n sorted_before = dft.sort_index(level=1, axis=1)\n dft["foo", "three"] = "bar"\n\n sorted_after = dft.sort_index(level=1, axis=1)\n tm.assert_frame_equal(\n sorted_before.drop([("foo", "three")], axis=1),\n sorted_after.drop([("foo", "three")], axis=1),\n )\n\n def test_sort_index_preserve_levels(self, multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n\n result = frame.sort_index()\n assert result.index.names == frame.index.names\n\n @pytest.mark.parametrize(\n "gen,extra",\n [\n ([1.0, 3.0, 2.0, 5.0], 4.0),\n ([1, 3, 2, 5], 4),\n (\n [\n Timestamp("20130101"),\n Timestamp("20130103"),\n Timestamp("20130102"),\n Timestamp("20130105"),\n ],\n Timestamp("20130104"),\n ),\n (["1one", "3one", "2one", "5one"], "4one"),\n ],\n )\n def test_sort_index_multilevel_repr_8017(self, gen, extra):\n data = np.random.default_rng(2).standard_normal((3, 4))\n\n columns = MultiIndex.from_tuples([("red", i) for i in gen])\n df = DataFrame(data, index=list("def"), columns=columns)\n df2 = pd.concat(\n [\n df,\n DataFrame(\n "world",\n index=list("def"),\n columns=MultiIndex.from_tuples([("red", extra)]),\n ),\n ],\n axis=1,\n )\n\n # check that the repr is good\n # make sure that we have a correct sparsified repr\n # e.g. only 1 header of read\n assert str(df2).splitlines()[0].split() == ["red"]\n\n # GH 8017\n # sorting fails after columns added\n\n # construct single-dtype then sort\n result = df.copy().sort_index(axis=1)\n expected = df.iloc[:, [0, 2, 1, 3]]\n tm.assert_frame_equal(result, expected)\n\n result = df2.sort_index(axis=1)\n expected = df2.iloc[:, [0, 2, 1, 4, 3]]\n tm.assert_frame_equal(result, expected)\n\n # setitem then sort\n result = df.copy()\n result[("red", extra)] = "world"\n\n result = result.sort_index(axis=1)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "categories",\n [\n pytest.param(["a", "b", "c"], id="str"),\n pytest.param(\n [pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(2, 3)],\n id="pd.Interval",\n ),\n ],\n )\n def test_sort_index_with_categories(self, categories):\n # GH#23452\n df = DataFrame(\n {"foo": range(len(categories))},\n index=CategoricalIndex(\n data=categories, categories=categories, ordered=True\n ),\n )\n df.index = df.index.reorder_categories(df.index.categories[::-1])\n result = df.sort_index()\n expected = DataFrame(\n {"foo": reversed(range(len(categories)))},\n index=CategoricalIndex(\n data=categories[::-1], categories=categories[::-1], ordered=True\n ),\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "ascending",\n [\n None,\n [True, None],\n [False, "True"],\n ],\n )\n def test_sort_index_ascending_bad_value_raises(self, ascending):\n # GH 39434\n df = DataFrame(np.arange(64))\n length = len(df.index)\n df.index = [(i - length / 2) % length for i in range(length)]\n match = 'For argument "ascending" expected type bool'\n with pytest.raises(ValueError, match=match):\n df.sort_index(axis=0, ascending=ascending, na_position="first")\n\n def test_sort_index_use_inf_as_na(self):\n # GH 29687\n expected = DataFrame(\n {"col1": [1, 2, 3], "col2": [3, 4, 5]},\n index=pd.date_range("2020", periods=3),\n )\n msg = "use_inf_as_na option is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with pd.option_context("mode.use_inf_as_na", True):\n result = expected.sort_index()\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "ascending",\n [(True, False), [True, False]],\n )\n def test_sort_index_ascending_tuple(self, ascending):\n df = DataFrame(\n {\n "legs": [4, 2, 4, 2, 2],\n },\n index=MultiIndex.from_tuples(\n [\n ("mammal", "dog"),\n ("bird", "duck"),\n ("mammal", "horse"),\n ("bird", "penguin"),\n ("mammal", "kangaroo"),\n ],\n names=["class", "animal"],\n ),\n )\n\n # parameter `ascending`` is a tuple\n result = df.sort_index(level=(0, 1), ascending=ascending)\n\n expected = DataFrame(\n {\n "legs": [2, 2, 2, 4, 4],\n },\n index=MultiIndex.from_tuples(\n [\n ("bird", "penguin"),\n ("bird", "duck"),\n ("mammal", "kangaroo"),\n ("mammal", "horse"),\n ("mammal", "dog"),\n ],\n names=["class", "animal"],\n ),\n )\n\n tm.assert_frame_equal(result, expected)\n\n\nclass TestDataFrameSortIndexKey:\n def test_sort_multi_index_key(self):\n # GH 25775, testing that sorting by index works with a multi-index.\n df = DataFrame(\n {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")}\n ).set_index(list("abc"))\n\n result = df.sort_index(level=list("ac"), key=lambda x: x)\n\n expected = DataFrame(\n {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")}\n ).set_index(list("abc"))\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_index(level=list("ac"), key=lambda x: -x)\n expected = DataFrame(\n {"a": [3, 2, 1], "b": [0, 0, 0], "c": [0, 2, 1], "d": list("acb")}\n ).set_index(list("abc"))\n\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index_key(self): # issue 27237\n df = DataFrame(np.arange(6, dtype="int64"), index=list("aaBBca"))\n\n result = df.sort_index()\n expected = df.iloc[[2, 3, 0, 1, 5, 4]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_index(key=lambda x: x.str.lower())\n expected = df.iloc[[0, 1, 5, 2, 3, 4]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_index(key=lambda x: x.str.lower(), ascending=False)\n expected = df.iloc[[4, 2, 3, 0, 1, 5]]\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index_key_int(self):\n df = DataFrame(np.arange(6, dtype="int64"), index=np.arange(6, dtype="int64"))\n\n result = df.sort_index()\n tm.assert_frame_equal(result, df)\n\n result = df.sort_index(key=lambda x: -x)\n expected = df.sort_index(ascending=False)\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_index(key=lambda x: 2 * x)\n tm.assert_frame_equal(result, df)\n\n def test_sort_multi_index_key_str(self):\n # GH 25775, testing that sorting by index works with a multi-index.\n df = DataFrame(\n {"a": ["B", "a", "C"], "b": [0, 1, 0], "c": list("abc"), "d": [0, 1, 2]}\n ).set_index(list("abc"))\n\n result = df.sort_index(level="a", key=lambda x: x.str.lower())\n\n expected = DataFrame(\n {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]}\n ).set_index(list("abc"))\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_index(\n level=list("abc"), # can refer to names\n key=lambda x: x.str.lower() if x.name in ["a", "c"] else -x,\n )\n\n expected = DataFrame(\n {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]}\n ).set_index(list("abc"))\n tm.assert_frame_equal(result, expected)\n\n def test_changes_length_raises(self):\n df = DataFrame({"A": [1, 2, 3]})\n with pytest.raises(ValueError, match="change the shape"):\n df.sort_index(key=lambda x: x[:1])\n\n def test_sort_index_multiindex_sparse_column(self):\n # GH 29735, testing that sort_index on a multiindexed frame with sparse\n # columns fills with 0.\n expected = DataFrame(\n {\n i: pd.array([0.0, 0.0, 0.0, 0.0], dtype=pd.SparseDtype("float64", 0.0))\n for i in range(4)\n },\n index=MultiIndex.from_product([[1, 2], [1, 2]]),\n )\n\n result = expected.sort_index(level=0)\n\n tm.assert_frame_equal(result, expected)\n\n def test_sort_index_na_position(self):\n # GH#51612\n df = DataFrame([1, 2], index=MultiIndex.from_tuples([(1, 1), (1, pd.NA)]))\n expected = df.copy()\n result = df.sort_index(level=[0, 1], na_position="last")\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("ascending", [True, False])\n def test_sort_index_multiindex_sort_remaining(self, ascending):\n # GH #24247\n df = DataFrame(\n {"A": [1, 2, 3, 4, 5], "B": [10, 20, 30, 40, 50]},\n index=MultiIndex.from_tuples(\n [("a", "x"), ("a", "y"), ("b", "x"), ("b", "y"), ("c", "x")]\n ),\n )\n\n result = df.sort_index(level=1, sort_remaining=False, ascending=ascending)\n\n if ascending:\n expected = DataFrame(\n {"A": [1, 3, 5, 2, 4], "B": [10, 30, 50, 20, 40]},\n index=MultiIndex.from_tuples(\n [("a", "x"), ("b", "x"), ("c", "x"), ("a", "y"), ("b", "y")]\n ),\n )\n else:\n expected = DataFrame(\n {"A": [2, 4, 1, 3, 5], "B": [20, 40, 10, 30, 50]},\n index=MultiIndex.from_tuples(\n [("a", "y"), ("b", "y"), ("a", "x"), ("b", "x"), ("c", "x")]\n ),\n )\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_sort_index_with_sliced_multiindex():\n # GH 55379\n mi = MultiIndex.from_tuples(\n [\n ("a", "10"),\n ("a", "18"),\n ("a", "25"),\n ("b", "16"),\n ("b", "26"),\n ("a", "45"),\n ("b", "28"),\n ("a", "5"),\n ("a", "50"),\n ("a", "51"),\n ("b", "4"),\n ],\n names=["group", "str"],\n )\n\n df = DataFrame({"x": range(len(mi))}, index=mi)\n result = df.iloc[0:6].sort_index()\n\n expected = DataFrame(\n {"x": [0, 1, 2, 5, 3, 4]},\n index=MultiIndex.from_tuples(\n [\n ("a", "10"),\n ("a", "18"),\n ("a", "25"),\n ("a", "45"),\n ("b", "16"),\n ("b", "26"),\n ],\n names=["group", "str"],\n ),\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_axis_columns_ignore_index():\n # GH 56478\n df = DataFrame([[1, 2]], columns=["d", "c"])\n result = df.sort_index(axis="columns", ignore_index=True)\n expected = DataFrame([[2, 1]])\n tm.assert_frame_equal(result, expected)\n\n\ndef test_sort_index_stable_sort():\n # GH 57151\n df = DataFrame(\n data=[\n (Timestamp("2024-01-30 13:00:00"), 13.0),\n (Timestamp("2024-01-30 13:00:00"), 13.1),\n (Timestamp("2024-01-30 12:00:00"), 12.0),\n (Timestamp("2024-01-30 12:00:00"), 12.1),\n ],\n columns=["dt", "value"],\n ).set_index(["dt"])\n result = df.sort_index(level="dt", kind="stable")\n expected = DataFrame(\n data=[\n (Timestamp("2024-01-30 12:00:00"), 12.0),\n (Timestamp("2024-01-30 12:00:00"), 12.1),\n (Timestamp("2024-01-30 13:00:00"), 13.0),\n (Timestamp("2024-01-30 13:00:00"), 13.1),\n ],\n columns=["dt", "value"],\n ).set_index(["dt"])\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_sort_index.py
test_sort_index.py
Python
34,826
0.95
0.053502
0.084668
react-lib
604
2023-11-23T12:00:01.600021
Apache-2.0
true
e57d9629229d5feb71f9f837f5ec9f93
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n NaT,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\nfrom pandas.util.version import Version\n\n\nclass TestDataFrameSortValues:\n @pytest.mark.parametrize("dtype", [np.uint8, bool])\n def test_sort_values_sparse_no_warning(self, dtype):\n # GH#45618\n ser = pd.Series(Categorical(["a", "b", "a"], categories=["a", "b", "c"]))\n df = pd.get_dummies(ser, dtype=dtype, sparse=True)\n\n with tm.assert_produces_warning(None):\n # No warnings about constructing Index from SparseArray\n df.sort_values(by=df.columns.tolist())\n\n def test_sort_values(self):\n frame = DataFrame(\n [[1, 1, 2], [3, 1, 0], [4, 5, 6]], index=[1, 2, 3], columns=list("ABC")\n )\n\n # by column (axis=0)\n sorted_df = frame.sort_values(by="A")\n indexer = frame["A"].argsort().values\n expected = frame.loc[frame.index[indexer]]\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.sort_values(by="A", ascending=False)\n indexer = indexer[::-1]\n expected = frame.loc[frame.index[indexer]]\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.sort_values(by="A", ascending=False)\n tm.assert_frame_equal(sorted_df, expected)\n\n # GH4839\n sorted_df = frame.sort_values(by=["A"], ascending=[False])\n tm.assert_frame_equal(sorted_df, expected)\n\n # multiple bys\n sorted_df = frame.sort_values(by=["B", "C"])\n expected = frame.loc[[2, 1, 3]]\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.sort_values(by=["B", "C"], ascending=False)\n tm.assert_frame_equal(sorted_df, expected[::-1])\n\n sorted_df = frame.sort_values(by=["B", "A"], ascending=[True, False])\n tm.assert_frame_equal(sorted_df, expected)\n\n msg = "No axis named 2 for object type DataFrame"\n with pytest.raises(ValueError, match=msg):\n frame.sort_values(by=["A", "B"], axis=2, inplace=True)\n\n # by row (axis=1): GH#10806\n sorted_df = frame.sort_values(by=3, axis=1)\n expected = frame\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.sort_values(by=3, axis=1, ascending=False)\n expected = frame.reindex(columns=["C", "B", "A"])\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.sort_values(by=[1, 2], axis="columns")\n expected = frame.reindex(columns=["B", "A", "C"])\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.sort_values(by=[1, 3], axis=1, ascending=[True, False])\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.sort_values(by=[1, 3], axis=1, ascending=False)\n expected = frame.reindex(columns=["C", "B", "A"])\n tm.assert_frame_equal(sorted_df, expected)\n\n msg = r"Length of ascending \(5\) != length of by \(2\)"\n with pytest.raises(ValueError, match=msg):\n frame.sort_values(by=["A", "B"], axis=0, ascending=[True] * 5)\n\n def test_sort_values_by_empty_list(self):\n # https://github.com/pandas-dev/pandas/issues/40258\n expected = DataFrame({"a": [1, 4, 2, 5, 3, 6]})\n result = expected.sort_values(by=[])\n tm.assert_frame_equal(result, expected)\n assert result is not expected\n\n def test_sort_values_inplace(self):\n frame = DataFrame(\n np.random.default_rng(2).standard_normal((4, 4)),\n index=[1, 2, 3, 4],\n columns=["A", "B", "C", "D"],\n )\n\n sorted_df = frame.copy()\n return_value = sorted_df.sort_values(by="A", inplace=True)\n assert return_value is None\n expected = frame.sort_values(by="A")\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.copy()\n return_value = sorted_df.sort_values(by=1, axis=1, inplace=True)\n assert return_value is None\n expected = frame.sort_values(by=1, axis=1)\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.copy()\n return_value = sorted_df.sort_values(by="A", ascending=False, inplace=True)\n assert return_value is None\n expected = frame.sort_values(by="A", ascending=False)\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.copy()\n return_value = sorted_df.sort_values(\n by=["A", "B"], ascending=False, inplace=True\n )\n assert return_value is None\n expected = frame.sort_values(by=["A", "B"], ascending=False)\n tm.assert_frame_equal(sorted_df, expected)\n\n def test_sort_values_multicolumn(self):\n A = np.arange(5).repeat(20)\n B = np.tile(np.arange(5), 20)\n np.random.default_rng(2).shuffle(A)\n np.random.default_rng(2).shuffle(B)\n frame = DataFrame(\n {"A": A, "B": B, "C": np.random.default_rng(2).standard_normal(100)}\n )\n\n result = frame.sort_values(by=["A", "B"])\n indexer = np.lexsort((frame["B"], frame["A"]))\n expected = frame.take(indexer)\n tm.assert_frame_equal(result, expected)\n\n result = frame.sort_values(by=["A", "B"], ascending=False)\n indexer = np.lexsort(\n (frame["B"].rank(ascending=False), frame["A"].rank(ascending=False))\n )\n expected = frame.take(indexer)\n tm.assert_frame_equal(result, expected)\n\n result = frame.sort_values(by=["B", "A"])\n indexer = np.lexsort((frame["A"], frame["B"]))\n expected = frame.take(indexer)\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_multicolumn_uint64(self):\n # GH#9918\n # uint64 multicolumn sort\n\n df = DataFrame(\n {\n "a": pd.Series([18446637057563306014, 1162265347240853609]),\n "b": pd.Series([1, 2]),\n }\n )\n df["a"] = df["a"].astype(np.uint64)\n result = df.sort_values(["a", "b"])\n\n expected = DataFrame(\n {\n "a": pd.Series([18446637057563306014, 1162265347240853609]),\n "b": pd.Series([1, 2]),\n },\n index=pd.Index([1, 0]),\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_nan(self):\n # GH#3917\n df = DataFrame(\n {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]}\n )\n\n # sort one column only\n expected = DataFrame(\n {"A": [np.nan, 1, 1, 2, 4, 6, 8], "B": [5, 9, 2, np.nan, 5, 5, 4]},\n index=[2, 0, 3, 1, 6, 4, 5],\n )\n sorted_df = df.sort_values(["A"], na_position="first")\n tm.assert_frame_equal(sorted_df, expected)\n\n expected = DataFrame(\n {"A": [np.nan, 8, 6, 4, 2, 1, 1], "B": [5, 4, 5, 5, np.nan, 9, 2]},\n index=[2, 5, 4, 6, 1, 0, 3],\n )\n sorted_df = df.sort_values(["A"], na_position="first", ascending=False)\n tm.assert_frame_equal(sorted_df, expected)\n\n expected = df.reindex(columns=["B", "A"])\n sorted_df = df.sort_values(by=1, axis=1, na_position="first")\n tm.assert_frame_equal(sorted_df, expected)\n\n # na_position='last', order\n expected = DataFrame(\n {"A": [1, 1, 2, 4, 6, 8, np.nan], "B": [2, 9, np.nan, 5, 5, 4, 5]},\n index=[3, 0, 1, 6, 4, 5, 2],\n )\n sorted_df = df.sort_values(["A", "B"])\n tm.assert_frame_equal(sorted_df, expected)\n\n # na_position='first', order\n expected = DataFrame(\n {"A": [np.nan, 1, 1, 2, 4, 6, 8], "B": [5, 2, 9, np.nan, 5, 5, 4]},\n index=[2, 3, 0, 1, 6, 4, 5],\n )\n sorted_df = df.sort_values(["A", "B"], na_position="first")\n tm.assert_frame_equal(sorted_df, expected)\n\n # na_position='first', not order\n expected = DataFrame(\n {"A": [np.nan, 1, 1, 2, 4, 6, 8], "B": [5, 9, 2, np.nan, 5, 5, 4]},\n index=[2, 0, 3, 1, 6, 4, 5],\n )\n sorted_df = df.sort_values(["A", "B"], ascending=[1, 0], na_position="first")\n tm.assert_frame_equal(sorted_df, expected)\n\n # na_position='last', not order\n expected = DataFrame(\n {"A": [8, 6, 4, 2, 1, 1, np.nan], "B": [4, 5, 5, np.nan, 2, 9, 5]},\n index=[5, 4, 6, 1, 3, 0, 2],\n )\n sorted_df = df.sort_values(["A", "B"], ascending=[0, 1], na_position="last")\n tm.assert_frame_equal(sorted_df, expected)\n\n def test_sort_values_stable_descending_sort(self):\n # GH#6399\n df = DataFrame(\n [[2, "first"], [2, "second"], [1, "a"], [1, "b"]],\n columns=["sort_col", "order"],\n )\n sorted_df = df.sort_values(by="sort_col", kind="mergesort", ascending=False)\n tm.assert_frame_equal(df, sorted_df)\n\n @pytest.mark.parametrize(\n "expected_idx_non_na, ascending",\n [\n [\n [3, 4, 5, 0, 1, 8, 6, 9, 7, 10, 13, 14],\n [True, True],\n ],\n [\n [0, 3, 4, 5, 1, 8, 6, 7, 10, 13, 14, 9],\n [True, False],\n ],\n [\n [9, 7, 10, 13, 14, 6, 8, 1, 3, 4, 5, 0],\n [False, True],\n ],\n [\n [7, 10, 13, 14, 9, 6, 8, 1, 0, 3, 4, 5],\n [False, False],\n ],\n ],\n )\n @pytest.mark.parametrize("na_position", ["first", "last"])\n def test_sort_values_stable_multicolumn_sort(\n self, expected_idx_non_na, ascending, na_position\n ):\n # GH#38426 Clarify sort_values with mult. columns / labels is stable\n df = DataFrame(\n {\n "A": [1, 2, np.nan, 1, 1, 1, 6, 8, 4, 8, 8, np.nan, np.nan, 8, 8],\n "B": [9, np.nan, 5, 2, 2, 2, 5, 4, 5, 3, 4, np.nan, np.nan, 4, 4],\n }\n )\n # All rows with NaN in col "B" only have unique values in "A", therefore,\n # only the rows with NaNs in "A" have to be treated individually:\n expected_idx = (\n [11, 12, 2] + expected_idx_non_na\n if na_position == "first"\n else expected_idx_non_na + [2, 11, 12]\n )\n expected = df.take(expected_idx)\n sorted_df = df.sort_values(\n ["A", "B"], ascending=ascending, na_position=na_position\n )\n tm.assert_frame_equal(sorted_df, expected)\n\n def test_sort_values_stable_categorial(self):\n # GH#16793\n df = DataFrame({"x": Categorical(np.repeat([1, 2, 3, 4], 5), ordered=True)})\n expected = df.copy()\n sorted_df = df.sort_values("x", kind="mergesort")\n tm.assert_frame_equal(sorted_df, expected)\n\n def test_sort_values_datetimes(self):\n # GH#3461, argsort / lexsort differences for a datetime column\n df = DataFrame(\n ["a", "a", "a", "b", "c", "d", "e", "f", "g"],\n columns=["A"],\n index=date_range("20130101", periods=9),\n )\n dts = [\n Timestamp(x)\n for x in [\n "2004-02-11",\n "2004-01-21",\n "2004-01-26",\n "2005-09-20",\n "2010-10-04",\n "2009-05-12",\n "2008-11-12",\n "2010-09-28",\n "2010-09-28",\n ]\n ]\n df["B"] = dts[::2] + dts[1::2]\n df["C"] = 2.0\n df["A1"] = 3.0\n\n df1 = df.sort_values(by="A")\n df2 = df.sort_values(by=["A"])\n tm.assert_frame_equal(df1, df2)\n\n df1 = df.sort_values(by="B")\n df2 = df.sort_values(by=["B"])\n tm.assert_frame_equal(df1, df2)\n\n df1 = df.sort_values(by="B")\n\n df2 = df.sort_values(by=["C", "B"])\n tm.assert_frame_equal(df1, df2)\n\n def test_sort_values_frame_column_inplace_sort_exception(\n self, float_frame, using_copy_on_write\n ):\n s = float_frame["A"]\n float_frame_orig = float_frame.copy()\n if using_copy_on_write:\n # INFO(CoW) Series is a new object, so can be changed inplace\n # without modifying original datafame\n s.sort_values(inplace=True)\n tm.assert_series_equal(s, float_frame_orig["A"].sort_values())\n # column in dataframe is not changed\n tm.assert_frame_equal(float_frame, float_frame_orig)\n else:\n with pytest.raises(ValueError, match="This Series is a view"):\n s.sort_values(inplace=True)\n\n cp = s.copy()\n cp.sort_values() # it works!\n\n def test_sort_values_nat_values_in_int_column(self):\n # GH#14922: "sorting with large float and multiple columns incorrect"\n\n # cause was that the int64 value NaT was considered as "na". Which is\n # only correct for datetime64 columns.\n\n int_values = (2, int(NaT._value))\n float_values = (2.0, -1.797693e308)\n\n df = DataFrame(\n {"int": int_values, "float": float_values}, columns=["int", "float"]\n )\n\n df_reversed = DataFrame(\n {"int": int_values[::-1], "float": float_values[::-1]},\n columns=["int", "float"],\n index=[1, 0],\n )\n\n # NaT is not a "na" for int64 columns, so na_position must not\n # influence the result:\n df_sorted = df.sort_values(["int", "float"], na_position="last")\n tm.assert_frame_equal(df_sorted, df_reversed)\n\n df_sorted = df.sort_values(["int", "float"], na_position="first")\n tm.assert_frame_equal(df_sorted, df_reversed)\n\n # reverse sorting order\n df_sorted = df.sort_values(["int", "float"], ascending=False)\n tm.assert_frame_equal(df_sorted, df)\n\n # and now check if NaT is still considered as "na" for datetime64\n # columns:\n df = DataFrame(\n {"datetime": [Timestamp("2016-01-01"), NaT], "float": float_values},\n columns=["datetime", "float"],\n )\n\n df_reversed = DataFrame(\n {"datetime": [NaT, Timestamp("2016-01-01")], "float": float_values[::-1]},\n columns=["datetime", "float"],\n index=[1, 0],\n )\n\n df_sorted = df.sort_values(["datetime", "float"], na_position="first")\n tm.assert_frame_equal(df_sorted, df_reversed)\n\n df_sorted = df.sort_values(["datetime", "float"], na_position="last")\n tm.assert_frame_equal(df_sorted, df)\n\n # Ascending should not affect the results.\n df_sorted = df.sort_values(["datetime", "float"], ascending=False)\n tm.assert_frame_equal(df_sorted, df)\n\n def test_sort_nat(self):\n # GH 16836\n\n d1 = [Timestamp(x) for x in ["2016-01-01", "2015-01-01", np.nan, "2016-01-01"]]\n d2 = [\n Timestamp(x)\n for x in ["2017-01-01", "2014-01-01", "2016-01-01", "2015-01-01"]\n ]\n df = DataFrame({"a": d1, "b": d2}, index=[0, 1, 2, 3])\n\n d3 = [Timestamp(x) for x in ["2015-01-01", "2016-01-01", "2016-01-01", np.nan]]\n d4 = [\n Timestamp(x)\n for x in ["2014-01-01", "2015-01-01", "2017-01-01", "2016-01-01"]\n ]\n expected = DataFrame({"a": d3, "b": d4}, index=[1, 3, 0, 2])\n sorted_df = df.sort_values(by=["a", "b"])\n tm.assert_frame_equal(sorted_df, expected)\n\n def test_sort_values_na_position_with_categories(self):\n # GH#22556\n # Positioning missing value properly when column is Categorical.\n categories = ["A", "B", "C"]\n category_indices = [0, 2, 4]\n list_of_nans = [np.nan, np.nan]\n na_indices = [1, 3]\n na_position_first = "first"\n na_position_last = "last"\n column_name = "c"\n\n reversed_categories = sorted(categories, reverse=True)\n reversed_category_indices = sorted(category_indices, reverse=True)\n reversed_na_indices = sorted(na_indices)\n\n df = DataFrame(\n {\n column_name: Categorical(\n ["A", np.nan, "B", np.nan, "C"], categories=categories, ordered=True\n )\n }\n )\n # sort ascending with na first\n result = df.sort_values(\n by=column_name, ascending=True, na_position=na_position_first\n )\n expected = DataFrame(\n {\n column_name: Categorical(\n list_of_nans + categories, categories=categories, ordered=True\n )\n },\n index=na_indices + category_indices,\n )\n\n tm.assert_frame_equal(result, expected)\n\n # sort ascending with na last\n result = df.sort_values(\n by=column_name, ascending=True, na_position=na_position_last\n )\n expected = DataFrame(\n {\n column_name: Categorical(\n categories + list_of_nans, categories=categories, ordered=True\n )\n },\n index=category_indices + na_indices,\n )\n\n tm.assert_frame_equal(result, expected)\n\n # sort descending with na first\n result = df.sort_values(\n by=column_name, ascending=False, na_position=na_position_first\n )\n expected = DataFrame(\n {\n column_name: Categorical(\n list_of_nans + reversed_categories,\n categories=categories,\n ordered=True,\n )\n },\n index=reversed_na_indices + reversed_category_indices,\n )\n\n tm.assert_frame_equal(result, expected)\n\n # sort descending with na last\n result = df.sort_values(\n by=column_name, ascending=False, na_position=na_position_last\n )\n expected = DataFrame(\n {\n column_name: Categorical(\n reversed_categories + list_of_nans,\n categories=categories,\n ordered=True,\n )\n },\n index=reversed_category_indices + reversed_na_indices,\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_nat(self):\n # GH#16836\n\n d1 = [Timestamp(x) for x in ["2016-01-01", "2015-01-01", np.nan, "2016-01-01"]]\n d2 = [\n Timestamp(x)\n for x in ["2017-01-01", "2014-01-01", "2016-01-01", "2015-01-01"]\n ]\n df = DataFrame({"a": d1, "b": d2}, index=[0, 1, 2, 3])\n\n d3 = [Timestamp(x) for x in ["2015-01-01", "2016-01-01", "2016-01-01", np.nan]]\n d4 = [\n Timestamp(x)\n for x in ["2014-01-01", "2015-01-01", "2017-01-01", "2016-01-01"]\n ]\n expected = DataFrame({"a": d3, "b": d4}, index=[1, 3, 0, 2])\n sorted_df = df.sort_values(by=["a", "b"])\n tm.assert_frame_equal(sorted_df, expected)\n\n def test_sort_values_na_position_with_categories_raises(self):\n df = DataFrame(\n {\n "c": Categorical(\n ["A", np.nan, "B", np.nan, "C"],\n categories=["A", "B", "C"],\n ordered=True,\n )\n }\n )\n\n with pytest.raises(ValueError, match="invalid na_position: bad_position"):\n df.sort_values(by="c", ascending=False, na_position="bad_position")\n\n @pytest.mark.parametrize("inplace", [True, False])\n @pytest.mark.parametrize(\n "original_dict, sorted_dict, ignore_index, output_index",\n [\n ({"A": [1, 2, 3]}, {"A": [3, 2, 1]}, True, [0, 1, 2]),\n ({"A": [1, 2, 3]}, {"A": [3, 2, 1]}, False, [2, 1, 0]),\n (\n {"A": [1, 2, 3], "B": [2, 3, 4]},\n {"A": [3, 2, 1], "B": [4, 3, 2]},\n True,\n [0, 1, 2],\n ),\n (\n {"A": [1, 2, 3], "B": [2, 3, 4]},\n {"A": [3, 2, 1], "B": [4, 3, 2]},\n False,\n [2, 1, 0],\n ),\n ],\n )\n def test_sort_values_ignore_index(\n self, inplace, original_dict, sorted_dict, ignore_index, output_index\n ):\n # GH 30114\n df = DataFrame(original_dict)\n expected = DataFrame(sorted_dict, index=output_index)\n kwargs = {"ignore_index": ignore_index, "inplace": inplace}\n\n if inplace:\n result_df = df.copy()\n result_df.sort_values("A", ascending=False, **kwargs)\n else:\n result_df = df.sort_values("A", ascending=False, **kwargs)\n\n tm.assert_frame_equal(result_df, expected)\n tm.assert_frame_equal(df, DataFrame(original_dict))\n\n def test_sort_values_nat_na_position_default(self):\n # GH 13230\n expected = DataFrame(\n {\n "A": [1, 2, 3, 4, 4],\n "date": pd.DatetimeIndex(\n [\n "2010-01-01 09:00:00",\n "2010-01-01 09:00:01",\n "2010-01-01 09:00:02",\n "2010-01-01 09:00:03",\n "NaT",\n ]\n ),\n }\n )\n result = expected.sort_values(["A", "date"])\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_item_cache(self, using_array_manager, using_copy_on_write):\n # previous behavior incorrect retained an invalid _item_cache entry\n df = DataFrame(\n np.random.default_rng(2).standard_normal((4, 3)), columns=["A", "B", "C"]\n )\n df["D"] = df["A"] * 2\n ser = df["A"]\n if not using_array_manager:\n assert len(df._mgr.blocks) == 2\n\n df.sort_values(by="A")\n\n if using_copy_on_write:\n ser.iloc[0] = 99\n assert df.iloc[0, 0] == df["A"][0]\n assert df.iloc[0, 0] != 99\n else:\n ser.values[0] = 99\n assert df.iloc[0, 0] == df["A"][0]\n assert df.iloc[0, 0] == 99\n\n def test_sort_values_reshaping(self):\n # GH 39426\n values = list(range(21))\n expected = DataFrame([values], columns=values)\n df = expected.sort_values(expected.index[0], axis=1, ignore_index=True)\n\n tm.assert_frame_equal(df, expected)\n\n def test_sort_values_no_by_inplace(self):\n # GH#50643\n df = DataFrame({"a": [1, 2, 3]})\n expected = df.copy()\n result = df.sort_values(by=[], inplace=True)\n tm.assert_frame_equal(df, expected)\n assert result is None\n\n def test_sort_values_no_op_reset_index(self):\n # GH#52553\n df = DataFrame({"A": [10, 20], "B": [1, 5]}, index=[2, 3])\n result = df.sort_values(by="A", ignore_index=True)\n expected = DataFrame({"A": [10, 20], "B": [1, 5]})\n tm.assert_frame_equal(result, expected)\n\n\nclass TestDataFrameSortKey: # test key sorting (issue 27237)\n def test_sort_values_inplace_key(self, sort_by_key):\n frame = DataFrame(\n np.random.default_rng(2).standard_normal((4, 4)),\n index=[1, 2, 3, 4],\n columns=["A", "B", "C", "D"],\n )\n\n sorted_df = frame.copy()\n return_value = sorted_df.sort_values(by="A", inplace=True, key=sort_by_key)\n assert return_value is None\n expected = frame.sort_values(by="A", key=sort_by_key)\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.copy()\n return_value = sorted_df.sort_values(\n by=1, axis=1, inplace=True, key=sort_by_key\n )\n assert return_value is None\n expected = frame.sort_values(by=1, axis=1, key=sort_by_key)\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.copy()\n return_value = sorted_df.sort_values(\n by="A", ascending=False, inplace=True, key=sort_by_key\n )\n assert return_value is None\n expected = frame.sort_values(by="A", ascending=False, key=sort_by_key)\n tm.assert_frame_equal(sorted_df, expected)\n\n sorted_df = frame.copy()\n sorted_df.sort_values(\n by=["A", "B"], ascending=False, inplace=True, key=sort_by_key\n )\n expected = frame.sort_values(by=["A", "B"], ascending=False, key=sort_by_key)\n tm.assert_frame_equal(sorted_df, expected)\n\n def test_sort_values_key(self):\n df = DataFrame(np.array([0, 5, np.nan, 3, 2, np.nan]))\n\n result = df.sort_values(0)\n expected = df.iloc[[0, 4, 3, 1, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values(0, key=lambda x: x + 5)\n expected = df.iloc[[0, 4, 3, 1, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values(0, key=lambda x: -x, ascending=False)\n expected = df.iloc[[0, 4, 3, 1, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_by_key(self):\n df = DataFrame(\n {\n "a": np.array([0, 3, np.nan, 3, 2, np.nan]),\n "b": np.array([0, 2, np.nan, 5, 2, np.nan]),\n }\n )\n\n result = df.sort_values("a", key=lambda x: -x)\n expected = df.iloc[[1, 3, 4, 0, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values(by=["a", "b"], key=lambda x: -x)\n expected = df.iloc[[3, 1, 4, 0, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values(by=["a", "b"], key=lambda x: -x, ascending=False)\n expected = df.iloc[[0, 4, 1, 3, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_by_key_by_name(self):\n df = DataFrame(\n {\n "a": np.array([0, 3, np.nan, 3, 2, np.nan]),\n "b": np.array([0, 2, np.nan, 5, 2, np.nan]),\n }\n )\n\n def key(col):\n if col.name == "a":\n return -col\n else:\n return col\n\n result = df.sort_values(by="a", key=key)\n expected = df.iloc[[1, 3, 4, 0, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values(by=["a"], key=key)\n expected = df.iloc[[1, 3, 4, 0, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values(by="b", key=key)\n expected = df.iloc[[0, 1, 4, 3, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values(by=["a", "b"], key=key)\n expected = df.iloc[[1, 3, 4, 0, 2, 5]]\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_key_string(self):\n df = DataFrame(np.array([["hello", "goodbye"], ["hello", "Hello"]]))\n\n result = df.sort_values(1)\n expected = df[::-1]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values([0, 1], key=lambda col: col.str.lower())\n tm.assert_frame_equal(result, df)\n\n result = df.sort_values(\n [0, 1], key=lambda col: col.str.lower(), ascending=False\n )\n expected = df.sort_values(1, key=lambda col: col.str.lower(), ascending=False)\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_key_empty(self, sort_by_key):\n df = DataFrame(np.array([]))\n\n df.sort_values(0, key=sort_by_key)\n df.sort_index(key=sort_by_key)\n\n def test_changes_length_raises(self):\n df = DataFrame({"A": [1, 2, 3]})\n with pytest.raises(ValueError, match="change the shape"):\n df.sort_values("A", key=lambda x: x[:1])\n\n def test_sort_values_key_axes(self):\n df = DataFrame({0: ["Hello", "goodbye"], 1: [0, 1]})\n\n result = df.sort_values(0, key=lambda col: col.str.lower())\n expected = df[::-1]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values(1, key=lambda col: -col)\n expected = df[::-1]\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_key_dict_axis(self):\n df = DataFrame({0: ["Hello", 0], 1: ["goodbye", 1]})\n\n result = df.sort_values(0, key=lambda col: col.str.lower(), axis=1)\n expected = df.loc[:, ::-1]\n tm.assert_frame_equal(result, expected)\n\n result = df.sort_values(1, key=lambda col: -col, axis=1)\n expected = df.loc[:, ::-1]\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("ordered", [True, False])\n def test_sort_values_key_casts_to_categorical(self, ordered):\n # https://github.com/pandas-dev/pandas/issues/36383\n categories = ["c", "b", "a"]\n df = DataFrame({"x": [1, 1, 1], "y": ["a", "b", "c"]})\n\n def sorter(key):\n if key.name == "y":\n return pd.Series(\n Categorical(key, categories=categories, ordered=ordered)\n )\n return key\n\n result = df.sort_values(by=["x", "y"], key=sorter)\n expected = DataFrame(\n {"x": [1, 1, 1], "y": ["c", "b", "a"]}, index=pd.Index([2, 1, 0])\n )\n\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.fixture\ndef df_none():\n return DataFrame(\n {\n "outer": ["a", "a", "a", "b", "b", "b"],\n "inner": [1, 2, 2, 2, 1, 1],\n "A": np.arange(6, 0, -1),\n ("B", 5): ["one", "one", "two", "two", "one", "one"],\n }\n )\n\n\n@pytest.fixture(params=[["outer"], ["outer", "inner"]])\ndef df_idx(request, df_none):\n levels = request.param\n return df_none.set_index(levels)\n\n\n@pytest.fixture(\n params=[\n "inner", # index level\n ["outer"], # list of index level\n "A", # column\n [("B", 5)], # list of column\n ["inner", "outer"], # two index levels\n [("B", 5), "outer"], # index level and column\n ["A", ("B", 5)], # Two columns\n ["inner", "outer"], # two index levels and column\n ]\n)\ndef sort_names(request):\n return request.param\n\n\n@pytest.fixture(params=[True, False])\ndef ascending(request):\n return request.param\n\n\nclass TestSortValuesLevelAsStr:\n def test_sort_index_level_and_column_label(\n self, df_none, df_idx, sort_names, ascending, request\n ):\n # GH#14353\n if (\n Version(np.__version__) >= Version("1.25")\n and request.node.callspec.id == "df_idx0-inner-True"\n ):\n request.applymarker(\n pytest.mark.xfail(\n reason=(\n "pandas default unstable sorting of duplicates"\n "issue with numpy>=1.25 with AVX instructions"\n ),\n strict=False,\n )\n )\n\n # Get index levels from df_idx\n levels = df_idx.index.names\n\n # Compute expected by sorting on columns and the setting index\n expected = df_none.sort_values(\n by=sort_names, ascending=ascending, axis=0\n ).set_index(levels)\n\n # Compute result sorting on mix on columns and index levels\n result = df_idx.sort_values(by=sort_names, ascending=ascending, axis=0)\n\n tm.assert_frame_equal(result, expected)\n\n def test_sort_column_level_and_index_label(\n self, df_none, df_idx, sort_names, ascending, request\n ):\n # GH#14353\n\n # Get levels from df_idx\n levels = df_idx.index.names\n\n # Compute expected by sorting on axis=0, setting index levels, and then\n # transposing. For some cases this will result in a frame with\n # multiple column levels\n expected = (\n df_none.sort_values(by=sort_names, ascending=ascending, axis=0)\n .set_index(levels)\n .T\n )\n\n # Compute result by transposing and sorting on axis=1.\n result = df_idx.T.sort_values(by=sort_names, ascending=ascending, axis=1)\n\n if Version(np.__version__) >= Version("1.25"):\n request.applymarker(\n pytest.mark.xfail(\n reason=(\n "pandas default unstable sorting of duplicates"\n "issue with numpy>=1.25 with AVX instructions"\n ),\n strict=False,\n )\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_validate_ascending_for_value_error(self):\n # GH41634\n df = DataFrame({"D": [23, 7, 21]})\n\n msg = 'For argument "ascending" expected type bool, received type str.'\n with pytest.raises(ValueError, match=msg):\n df.sort_values(by="D", ascending="False")\n\n @pytest.mark.parametrize("ascending", [False, 0, 1, True])\n def test_sort_values_validate_ascending_functional(self, ascending):\n df = DataFrame({"D": [23, 7, 21]})\n indexer = df["D"].argsort().values\n\n if not ascending:\n indexer = indexer[::-1]\n\n expected = df.loc[df.index[indexer]]\n result = df.sort_values(by="D", ascending=ascending)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_sort_values.py
test_sort_values.py
Python
32,982
0.95
0.075532
0.075159
python-kit
352
2024-07-08T14:39:15.109272
GPL-3.0
true
f4dd09897144e1568b8431bbad8ae734
import numpy as np\nimport pytest\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\nclass TestSwapAxes:\n def test_swapaxes(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))\n msg = "'DataFrame.swapaxes' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n tm.assert_frame_equal(df.T, df.swapaxes(0, 1))\n tm.assert_frame_equal(df.T, df.swapaxes(1, 0))\n\n def test_swapaxes_noop(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))\n msg = "'DataFrame.swapaxes' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n tm.assert_frame_equal(df, df.swapaxes(0, 0))\n\n def test_swapaxes_invalid_axis(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))\n msg = "'DataFrame.swapaxes' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n msg = "No axis named 2 for object type DataFrame"\n with pytest.raises(ValueError, match=msg):\n df.swapaxes(2, 5)\n\n def test_round_empty_not_input(self):\n # GH#51032\n df = DataFrame({"a": [1, 2]})\n msg = "'DataFrame.swapaxes' is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = df.swapaxes("index", "index")\n tm.assert_frame_equal(df, result)\n assert df is not result\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_swapaxes.py
test_swapaxes.py
Python
1,466
0.95
0.162162
0.032258
awesome-app
203
2025-02-21T17:32:45.529016
Apache-2.0
true
162965695b7f7172c04da53d73b275c3
import pytest\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\nclass TestSwaplevel:\n def test_swaplevel(self, multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n\n swapped = frame["A"].swaplevel()\n swapped2 = frame["A"].swaplevel(0)\n swapped3 = frame["A"].swaplevel(0, 1)\n swapped4 = frame["A"].swaplevel("first", "second")\n assert not swapped.index.equals(frame.index)\n tm.assert_series_equal(swapped, swapped2)\n tm.assert_series_equal(swapped, swapped3)\n tm.assert_series_equal(swapped, swapped4)\n\n back = swapped.swaplevel()\n back2 = swapped.swaplevel(0)\n back3 = swapped.swaplevel(0, 1)\n back4 = swapped.swaplevel("second", "first")\n assert back.index.equals(frame.index)\n tm.assert_series_equal(back, back2)\n tm.assert_series_equal(back, back3)\n tm.assert_series_equal(back, back4)\n\n ft = frame.T\n swapped = ft.swaplevel("first", "second", axis=1)\n exp = frame.swaplevel("first", "second").T\n tm.assert_frame_equal(swapped, exp)\n\n msg = "Can only swap levels on a hierarchical axis."\n with pytest.raises(TypeError, match=msg):\n DataFrame(range(3)).swaplevel()\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_swaplevel.py
test_swaplevel.py
Python
1,277
0.85
0.055556
0
python-kit
284
2025-06-05T19:19:15.694147
Apache-2.0
true
64481691ad90a88de7a972a8eead8f44
import csv\nfrom io import StringIO\nimport os\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import ParserError\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n NaT,\n Series,\n Timestamp,\n date_range,\n period_range,\n read_csv,\n to_datetime,\n)\nimport pandas._testing as tm\nimport pandas.core.common as com\n\nfrom pandas.io.common import get_handle\n\n\nclass TestDataFrameToCSV:\n def read_csv(self, path, **kwargs):\n params = {"index_col": 0}\n params.update(**kwargs)\n\n return read_csv(path, **params)\n\n def test_to_csv_from_csv1(self, float_frame, datetime_frame):\n with tm.ensure_clean("__tmp_to_csv_from_csv1__") as path:\n float_frame.iloc[:5, float_frame.columns.get_loc("A")] = np.nan\n\n float_frame.to_csv(path)\n float_frame.to_csv(path, columns=["A", "B"])\n float_frame.to_csv(path, header=False)\n float_frame.to_csv(path, index=False)\n\n # test roundtrip\n # freq does not roundtrip\n datetime_frame.index = datetime_frame.index._with_freq(None)\n datetime_frame.to_csv(path)\n recons = self.read_csv(path, parse_dates=True)\n tm.assert_frame_equal(datetime_frame, recons)\n\n datetime_frame.to_csv(path, index_label="index")\n recons = self.read_csv(path, index_col=None, parse_dates=True)\n\n assert len(recons.columns) == len(datetime_frame.columns) + 1\n\n # no index\n datetime_frame.to_csv(path, index=False)\n recons = self.read_csv(path, index_col=None, parse_dates=True)\n tm.assert_almost_equal(datetime_frame.values, recons.values)\n\n # corner case\n dm = DataFrame(\n {\n "s1": Series(range(3), index=np.arange(3, dtype=np.int64)),\n "s2": Series(range(2), index=np.arange(2, dtype=np.int64)),\n }\n )\n dm.to_csv(path)\n\n recons = self.read_csv(path)\n tm.assert_frame_equal(dm, recons)\n\n def test_to_csv_from_csv2(self, float_frame):\n with tm.ensure_clean("__tmp_to_csv_from_csv2__") as path:\n # duplicate index\n df = DataFrame(\n np.random.default_rng(2).standard_normal((3, 3)),\n index=["a", "a", "b"],\n columns=["x", "y", "z"],\n )\n df.to_csv(path)\n result = self.read_csv(path)\n tm.assert_frame_equal(result, df)\n\n midx = MultiIndex.from_tuples([("A", 1, 2), ("A", 1, 2), ("B", 1, 2)])\n df = DataFrame(\n np.random.default_rng(2).standard_normal((3, 3)),\n index=midx,\n columns=["x", "y", "z"],\n )\n\n df.to_csv(path)\n result = self.read_csv(path, index_col=[0, 1, 2], parse_dates=False)\n tm.assert_frame_equal(result, df, check_names=False)\n\n # column aliases\n col_aliases = Index(["AA", "X", "Y", "Z"])\n float_frame.to_csv(path, header=col_aliases)\n\n rs = self.read_csv(path)\n xp = float_frame.copy()\n xp.columns = col_aliases\n tm.assert_frame_equal(xp, rs)\n\n msg = "Writing 4 cols but got 2 aliases"\n with pytest.raises(ValueError, match=msg):\n float_frame.to_csv(path, header=["AA", "X"])\n\n def test_to_csv_from_csv3(self):\n with tm.ensure_clean("__tmp_to_csv_from_csv3__") as path:\n df1 = DataFrame(np.random.default_rng(2).standard_normal((3, 1)))\n df2 = DataFrame(np.random.default_rng(2).standard_normal((3, 1)))\n\n df1.to_csv(path)\n df2.to_csv(path, mode="a", header=False)\n xp = pd.concat([df1, df2])\n rs = read_csv(path, index_col=0)\n rs.columns = [int(label) for label in rs.columns]\n xp.columns = [int(label) for label in xp.columns]\n tm.assert_frame_equal(xp, rs)\n\n def test_to_csv_from_csv4(self):\n with tm.ensure_clean("__tmp_to_csv_from_csv4__") as path:\n # GH 10833 (TimedeltaIndex formatting)\n dt = pd.Timedelta(seconds=1)\n df = DataFrame(\n {"dt_data": [i * dt for i in range(3)]},\n index=Index([i * dt for i in range(3)], name="dt_index"),\n )\n df.to_csv(path)\n\n result = read_csv(path, index_col="dt_index")\n result.index = pd.to_timedelta(result.index)\n result["dt_data"] = pd.to_timedelta(result["dt_data"])\n\n tm.assert_frame_equal(df, result, check_index_type=True)\n\n def test_to_csv_from_csv5(self, timezone_frame):\n # tz, 8260\n with tm.ensure_clean("__tmp_to_csv_from_csv5__") as path:\n timezone_frame.to_csv(path)\n result = read_csv(path, index_col=0, parse_dates=["A"])\n\n converter = (\n lambda c: to_datetime(result[c])\n .dt.tz_convert("UTC")\n .dt.tz_convert(timezone_frame[c].dt.tz)\n )\n result["B"] = converter("B")\n result["C"] = converter("C")\n tm.assert_frame_equal(result, timezone_frame)\n\n def test_to_csv_cols_reordering(self):\n # GH3454\n chunksize = 5\n N = int(chunksize * 2.5)\n\n df = DataFrame(\n np.ones((N, 3)),\n index=Index([f"i-{i}" for i in range(N)], name="a"),\n columns=Index([f"i-{i}" for i in range(3)], name="a"),\n )\n cs = df.columns\n cols = [cs[2], cs[0]]\n\n with tm.ensure_clean() as path:\n df.to_csv(path, columns=cols, chunksize=chunksize)\n rs_c = read_csv(path, index_col=0)\n\n tm.assert_frame_equal(df[cols], rs_c, check_names=False)\n\n @pytest.mark.parametrize("cols", [None, ["b", "a"]])\n def test_to_csv_new_dupe_cols(self, cols):\n chunksize = 5\n N = int(chunksize * 2.5)\n\n # dupe cols\n df = DataFrame(\n np.ones((N, 3)),\n index=Index([f"i-{i}" for i in range(N)], name="a"),\n columns=["a", "a", "b"],\n )\n with tm.ensure_clean() as path:\n df.to_csv(path, columns=cols, chunksize=chunksize)\n rs_c = read_csv(path, index_col=0)\n\n # we wrote them in a different order\n # so compare them in that order\n if cols is not None:\n if df.columns.is_unique:\n rs_c.columns = cols\n else:\n indexer, missing = df.columns.get_indexer_non_unique(cols)\n rs_c.columns = df.columns.take(indexer)\n\n for c in cols:\n obj_df = df[c]\n obj_rs = rs_c[c]\n if isinstance(obj_df, Series):\n tm.assert_series_equal(obj_df, obj_rs)\n else:\n tm.assert_frame_equal(obj_df, obj_rs, check_names=False)\n\n # wrote in the same order\n else:\n rs_c.columns = df.columns\n tm.assert_frame_equal(df, rs_c, check_names=False)\n\n @pytest.mark.slow\n def test_to_csv_dtnat(self):\n # GH3437\n def make_dtnat_arr(n, nnat=None):\n if nnat is None:\n nnat = int(n * 0.1) # 10%\n s = list(date_range("2000", freq="5min", periods=n))\n if nnat:\n for i in np.random.default_rng(2).integers(0, len(s), nnat):\n s[i] = NaT\n i = np.random.default_rng(2).integers(100)\n s[-i] = NaT\n s[i] = NaT\n return s\n\n chunksize = 1000\n s1 = make_dtnat_arr(chunksize + 5)\n s2 = make_dtnat_arr(chunksize + 5, 0)\n\n with tm.ensure_clean("1.csv") as pth:\n df = DataFrame({"a": s1, "b": s2})\n df.to_csv(pth, chunksize=chunksize)\n\n recons = self.read_csv(pth).apply(to_datetime)\n tm.assert_frame_equal(df, recons, check_names=False)\n\n def _return_result_expected(\n self,\n df,\n chunksize,\n r_dtype=None,\n c_dtype=None,\n rnlvl=None,\n cnlvl=None,\n dupe_col=False,\n ):\n kwargs = {"parse_dates": False}\n if cnlvl:\n if rnlvl is not None:\n kwargs["index_col"] = list(range(rnlvl))\n kwargs["header"] = list(range(cnlvl))\n\n with tm.ensure_clean("__tmp_to_csv_moar__") as path:\n df.to_csv(path, encoding="utf8", chunksize=chunksize)\n recons = self.read_csv(path, **kwargs)\n else:\n kwargs["header"] = 0\n\n with tm.ensure_clean("__tmp_to_csv_moar__") as path:\n df.to_csv(path, encoding="utf8", chunksize=chunksize)\n recons = self.read_csv(path, **kwargs)\n\n def _to_uni(x):\n if not isinstance(x, str):\n return x.decode("utf8")\n return x\n\n if dupe_col:\n # read_Csv disambiguates the columns by\n # labeling them dupe.1,dupe.2, etc'. monkey patch columns\n recons.columns = df.columns\n if rnlvl and not cnlvl:\n delta_lvl = [recons.iloc[:, i].values for i in range(rnlvl - 1)]\n ix = MultiIndex.from_arrays([list(recons.index)] + delta_lvl)\n recons.index = ix\n recons = recons.iloc[:, rnlvl - 1 :]\n\n type_map = {"i": "i", "f": "f", "s": "O", "u": "O", "dt": "O", "p": "O"}\n if r_dtype:\n if r_dtype == "u": # unicode\n r_dtype = "O"\n recons.index = np.array(\n [_to_uni(label) for label in recons.index], dtype=r_dtype\n )\n df.index = np.array(\n [_to_uni(label) for label in df.index], dtype=r_dtype\n )\n elif r_dtype == "dt": # unicode\n r_dtype = "O"\n recons.index = np.array(\n [Timestamp(label) for label in recons.index], dtype=r_dtype\n )\n df.index = np.array(\n [Timestamp(label) for label in df.index], dtype=r_dtype\n )\n elif r_dtype == "p":\n r_dtype = "O"\n idx_list = to_datetime(recons.index)\n recons.index = np.array(\n [Timestamp(label) for label in idx_list], dtype=r_dtype\n )\n df.index = np.array(\n list(map(Timestamp, df.index.to_timestamp())), dtype=r_dtype\n )\n else:\n r_dtype = type_map.get(r_dtype)\n recons.index = np.array(recons.index, dtype=r_dtype)\n df.index = np.array(df.index, dtype=r_dtype)\n if c_dtype:\n if c_dtype == "u":\n c_dtype = "O"\n recons.columns = np.array(\n [_to_uni(label) for label in recons.columns], dtype=c_dtype\n )\n df.columns = np.array(\n [_to_uni(label) for label in df.columns], dtype=c_dtype\n )\n elif c_dtype == "dt":\n c_dtype = "O"\n recons.columns = np.array(\n [Timestamp(label) for label in recons.columns], dtype=c_dtype\n )\n df.columns = np.array(\n [Timestamp(label) for label in df.columns], dtype=c_dtype\n )\n elif c_dtype == "p":\n c_dtype = "O"\n col_list = to_datetime(recons.columns)\n recons.columns = np.array(\n [Timestamp(label) for label in col_list], dtype=c_dtype\n )\n col_list = df.columns.to_timestamp()\n df.columns = np.array(\n [Timestamp(label) for label in col_list], dtype=c_dtype\n )\n else:\n c_dtype = type_map.get(c_dtype)\n recons.columns = np.array(recons.columns, dtype=c_dtype)\n df.columns = np.array(df.columns, dtype=c_dtype)\n return df, recons\n\n @pytest.mark.slow\n @pytest.mark.parametrize(\n "nrows", [2, 10, 99, 100, 101, 102, 198, 199, 200, 201, 202, 249, 250, 251]\n )\n def test_to_csv_nrows(self, nrows):\n df = DataFrame(\n np.ones((nrows, 4)),\n index=date_range("2020-01-01", periods=nrows),\n columns=Index(list("abcd"), dtype=object),\n )\n result, expected = self._return_result_expected(df, 1000, "dt", "s")\n tm.assert_frame_equal(result, expected, check_names=False)\n\n @pytest.mark.slow\n @pytest.mark.parametrize(\n "nrows", [2, 10, 99, 100, 101, 102, 198, 199, 200, 201, 202, 249, 250, 251]\n )\n @pytest.mark.parametrize(\n "r_idx_type, c_idx_type", [("i", "i"), ("s", "s"), ("s", "dt"), ("p", "p")]\n )\n @pytest.mark.parametrize("ncols", [1, 2, 3, 4])\n @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\n def test_to_csv_idx_types(self, nrows, r_idx_type, c_idx_type, ncols):\n axes = {\n "i": lambda n: Index(np.arange(n), dtype=np.int64),\n "s": lambda n: Index([f"{i}_{chr(i)}" for i in range(97, 97 + n)]),\n "dt": lambda n: date_range("2020-01-01", periods=n),\n "p": lambda n: period_range("2020-01-01", periods=n, freq="D"),\n }\n df = DataFrame(\n np.ones((nrows, ncols)),\n index=axes[r_idx_type](nrows),\n columns=axes[c_idx_type](ncols),\n )\n result, expected = self._return_result_expected(\n df,\n 1000,\n r_idx_type,\n c_idx_type,\n )\n tm.assert_frame_equal(result, expected, check_names=False)\n\n @pytest.mark.slow\n @pytest.mark.parametrize(\n "nrows", [10, 98, 99, 100, 101, 102, 198, 199, 200, 201, 202, 249, 250, 251]\n )\n @pytest.mark.parametrize("ncols", [1, 2, 3, 4])\n def test_to_csv_idx_ncols(self, nrows, ncols):\n df = DataFrame(\n np.ones((nrows, ncols)),\n index=Index([f"i-{i}" for i in range(nrows)], name="a"),\n columns=Index([f"i-{i}" for i in range(ncols)], name="a"),\n )\n result, expected = self._return_result_expected(df, 1000)\n tm.assert_frame_equal(result, expected, check_names=False)\n\n @pytest.mark.slow\n @pytest.mark.parametrize("nrows", [10, 98, 99, 100, 101, 102])\n def test_to_csv_dup_cols(self, nrows):\n df = DataFrame(\n np.ones((nrows, 3)),\n index=Index([f"i-{i}" for i in range(nrows)], name="a"),\n columns=Index([f"i-{i}" for i in range(3)], name="a"),\n )\n\n cols = list(df.columns)\n cols[:2] = ["dupe", "dupe"]\n cols[-2:] = ["dupe", "dupe"]\n ix = list(df.index)\n ix[:2] = ["rdupe", "rdupe"]\n ix[-2:] = ["rdupe", "rdupe"]\n df.index = ix\n df.columns = cols\n result, expected = self._return_result_expected(df, 1000, dupe_col=True)\n tm.assert_frame_equal(result, expected, check_names=False)\n\n @pytest.mark.slow\n def test_to_csv_empty(self):\n df = DataFrame(index=np.arange(10, dtype=np.int64))\n result, expected = self._return_result_expected(df, 1000)\n tm.assert_frame_equal(result, expected, check_column_type=False)\n\n @pytest.mark.slow\n def test_to_csv_chunksize(self):\n chunksize = 1000\n rows = chunksize // 2 + 1\n df = DataFrame(\n np.ones((rows, 2)),\n columns=Index(list("ab")),\n index=MultiIndex.from_arrays([range(rows) for _ in range(2)]),\n )\n result, expected = self._return_result_expected(df, chunksize, rnlvl=2)\n tm.assert_frame_equal(result, expected, check_names=False)\n\n @pytest.mark.slow\n @pytest.mark.parametrize(\n "nrows", [2, 10, 99, 100, 101, 102, 198, 199, 200, 201, 202, 249, 250, 251]\n )\n @pytest.mark.parametrize("ncols", [2, 3, 4])\n @pytest.mark.parametrize(\n "df_params, func_params",\n [\n [{"r_idx_nlevels": 2}, {"rnlvl": 2}],\n [{"c_idx_nlevels": 2}, {"cnlvl": 2}],\n [{"r_idx_nlevels": 2, "c_idx_nlevels": 2}, {"rnlvl": 2, "cnlvl": 2}],\n ],\n )\n def test_to_csv_params(self, nrows, df_params, func_params, ncols):\n if df_params.get("r_idx_nlevels"):\n index = MultiIndex.from_arrays(\n [f"i-{i}" for i in range(nrows)]\n for _ in range(df_params["r_idx_nlevels"])\n )\n else:\n index = None\n\n if df_params.get("c_idx_nlevels"):\n columns = MultiIndex.from_arrays(\n [f"i-{i}" for i in range(ncols)]\n for _ in range(df_params["c_idx_nlevels"])\n )\n else:\n columns = Index([f"i-{i}" for i in range(ncols)])\n df = DataFrame(np.ones((nrows, ncols)), index=index, columns=columns)\n result, expected = self._return_result_expected(df, 1000, **func_params)\n tm.assert_frame_equal(result, expected, check_names=False)\n\n def test_to_csv_from_csv_w_some_infs(self, float_frame):\n # test roundtrip with inf, -inf, nan, as full columns and mix\n float_frame["G"] = np.nan\n f = lambda x: [np.inf, np.nan][np.random.default_rng(2).random() < 0.5]\n float_frame["h"] = float_frame.index.map(f)\n\n with tm.ensure_clean() as path:\n float_frame.to_csv(path)\n recons = self.read_csv(path)\n\n tm.assert_frame_equal(float_frame, recons)\n tm.assert_frame_equal(np.isinf(float_frame), np.isinf(recons))\n\n def test_to_csv_from_csv_w_all_infs(self, float_frame):\n # test roundtrip with inf, -inf, nan, as full columns and mix\n float_frame["E"] = np.inf\n float_frame["F"] = -np.inf\n\n with tm.ensure_clean() as path:\n float_frame.to_csv(path)\n recons = self.read_csv(path)\n\n tm.assert_frame_equal(float_frame, recons)\n tm.assert_frame_equal(np.isinf(float_frame), np.isinf(recons))\n\n def test_to_csv_no_index(self):\n # GH 3624, after appending columns, to_csv fails\n with tm.ensure_clean("__tmp_to_csv_no_index__") as path:\n df = DataFrame({"c1": [1, 2, 3], "c2": [4, 5, 6]})\n df.to_csv(path, index=False)\n result = read_csv(path)\n tm.assert_frame_equal(df, result)\n df["c3"] = Series([7, 8, 9], dtype="int64")\n df.to_csv(path, index=False)\n result = read_csv(path)\n tm.assert_frame_equal(df, result)\n\n def test_to_csv_with_mix_columns(self):\n # gh-11637: incorrect output when a mix of integer and string column\n # names passed as columns parameter in to_csv\n\n df = DataFrame({0: ["a", "b", "c"], 1: ["aa", "bb", "cc"]})\n df["test"] = "txt"\n assert df.to_csv() == df.to_csv(columns=[0, 1, "test"])\n\n def test_to_csv_headers(self):\n # GH6186, the presence or absence of `index` incorrectly\n # causes to_csv to have different header semantics.\n from_df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"])\n to_df = DataFrame([[1, 2], [3, 4]], columns=["X", "Y"])\n with tm.ensure_clean("__tmp_to_csv_headers__") as path:\n from_df.to_csv(path, header=["X", "Y"])\n recons = self.read_csv(path)\n\n tm.assert_frame_equal(to_df, recons)\n\n from_df.to_csv(path, index=False, header=["X", "Y"])\n recons = self.read_csv(path)\n\n return_value = recons.reset_index(inplace=True)\n assert return_value is None\n tm.assert_frame_equal(to_df, recons)\n\n def test_to_csv_multiindex(self, float_frame, datetime_frame):\n frame = float_frame\n old_index = frame.index\n arrays = np.arange(len(old_index) * 2, dtype=np.int64).reshape(2, -1)\n new_index = MultiIndex.from_arrays(arrays, names=["first", "second"])\n frame.index = new_index\n\n with tm.ensure_clean("__tmp_to_csv_multiindex__") as path:\n frame.to_csv(path, header=False)\n frame.to_csv(path, columns=["A", "B"])\n\n # round trip\n frame.to_csv(path)\n\n df = self.read_csv(path, index_col=[0, 1], parse_dates=False)\n\n # TODO to_csv drops column name\n tm.assert_frame_equal(frame, df, check_names=False)\n assert frame.index.names == df.index.names\n\n # needed if setUp becomes a class method\n float_frame.index = old_index\n\n # try multiindex with dates\n tsframe = datetime_frame\n old_index = tsframe.index\n new_index = [old_index, np.arange(len(old_index), dtype=np.int64)]\n tsframe.index = MultiIndex.from_arrays(new_index)\n\n tsframe.to_csv(path, index_label=["time", "foo"])\n with tm.assert_produces_warning(\n UserWarning, match="Could not infer format"\n ):\n recons = self.read_csv(path, index_col=[0, 1], parse_dates=True)\n\n # TODO to_csv drops column name\n tm.assert_frame_equal(tsframe, recons, check_names=False)\n\n # do not load index\n tsframe.to_csv(path)\n recons = self.read_csv(path, index_col=None)\n assert len(recons.columns) == len(tsframe.columns) + 2\n\n # no index\n tsframe.to_csv(path, index=False)\n recons = self.read_csv(path, index_col=None)\n tm.assert_almost_equal(recons.values, datetime_frame.values)\n\n # needed if setUp becomes class method\n datetime_frame.index = old_index\n\n with tm.ensure_clean("__tmp_to_csv_multiindex__") as path:\n # GH3571, GH1651, GH3141\n\n def _make_frame(names=None):\n if names is True:\n names = ["first", "second"]\n return DataFrame(\n np.random.default_rng(2).integers(0, 10, size=(3, 3)),\n columns=MultiIndex.from_tuples(\n [("bah", "foo"), ("bah", "bar"), ("ban", "baz")], names=names\n ),\n dtype="int64",\n )\n\n # column & index are multi-index\n df = DataFrame(\n np.ones((5, 3)),\n columns=MultiIndex.from_arrays(\n [[f"i-{i}" for i in range(3)] for _ in range(4)], names=list("abcd")\n ),\n index=MultiIndex.from_arrays(\n [[f"i-{i}" for i in range(5)] for _ in range(2)], names=list("ab")\n ),\n )\n df.to_csv(path)\n result = read_csv(path, header=[0, 1, 2, 3], index_col=[0, 1])\n tm.assert_frame_equal(df, result)\n\n # column is mi\n df = DataFrame(\n np.ones((5, 3)),\n columns=MultiIndex.from_arrays(\n [[f"i-{i}" for i in range(3)] for _ in range(4)], names=list("abcd")\n ),\n )\n df.to_csv(path)\n result = read_csv(path, header=[0, 1, 2, 3], index_col=0)\n tm.assert_frame_equal(df, result)\n\n # dup column names?\n df = DataFrame(\n np.ones((5, 3)),\n columns=MultiIndex.from_arrays(\n [[f"i-{i}" for i in range(3)] for _ in range(4)], names=list("abcd")\n ),\n index=MultiIndex.from_arrays(\n [[f"i-{i}" for i in range(5)] for _ in range(3)], names=list("abc")\n ),\n )\n df.to_csv(path)\n result = read_csv(path, header=[0, 1, 2, 3], index_col=[0, 1, 2])\n tm.assert_frame_equal(df, result)\n\n # writing with no index\n df = _make_frame()\n df.to_csv(path, index=False)\n result = read_csv(path, header=[0, 1])\n tm.assert_frame_equal(df, result)\n\n # we lose the names here\n df = _make_frame(True)\n df.to_csv(path, index=False)\n result = read_csv(path, header=[0, 1])\n assert com.all_none(*result.columns.names)\n result.columns.names = df.columns.names\n tm.assert_frame_equal(df, result)\n\n # whatsnew example\n df = _make_frame()\n df.to_csv(path)\n result = read_csv(path, header=[0, 1], index_col=[0])\n tm.assert_frame_equal(df, result)\n\n df = _make_frame(True)\n df.to_csv(path)\n result = read_csv(path, header=[0, 1], index_col=[0])\n tm.assert_frame_equal(df, result)\n\n # invalid options\n df = _make_frame(True)\n df.to_csv(path)\n\n for i in [6, 7]:\n msg = f"len of {i}, but only 5 lines in file"\n with pytest.raises(ParserError, match=msg):\n read_csv(path, header=list(range(i)), index_col=0)\n\n # write with cols\n msg = "cannot specify cols with a MultiIndex"\n with pytest.raises(TypeError, match=msg):\n df.to_csv(path, columns=["foo", "bar"])\n\n with tm.ensure_clean("__tmp_to_csv_multiindex__") as path:\n # empty\n tsframe[:0].to_csv(path)\n recons = self.read_csv(path)\n\n exp = tsframe[:0]\n exp.index = []\n\n tm.assert_index_equal(recons.columns, exp.columns)\n assert len(recons) == 0\n\n def test_to_csv_interval_index(self, using_infer_string):\n # GH 28210\n df = DataFrame({"A": list("abc"), "B": range(3)}, index=pd.interval_range(0, 3))\n\n with tm.ensure_clean("__tmp_to_csv_interval_index__.csv") as path:\n df.to_csv(path)\n result = self.read_csv(path, index_col=0)\n\n # can't roundtrip intervalindex via read_csv so check string repr (GH 23595)\n expected = df.copy()\n expected.index = expected.index.astype("str")\n\n tm.assert_frame_equal(result, expected)\n\n def test_to_csv_float32_nanrep(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((1, 4)).astype(np.float32)\n )\n df[1] = np.nan\n\n with tm.ensure_clean("__tmp_to_csv_float32_nanrep__.csv") as path:\n df.to_csv(path, na_rep=999)\n\n with open(path, encoding="utf-8") as f:\n lines = f.readlines()\n assert lines[1].split(",")[2] == "999"\n\n def test_to_csv_withcommas(self):\n # Commas inside fields should be correctly escaped when saving as CSV.\n df = DataFrame({"A": [1, 2, 3], "B": ["5,6", "7,8", "9,0"]})\n\n with tm.ensure_clean("__tmp_to_csv_withcommas__.csv") as path:\n df.to_csv(path)\n df2 = self.read_csv(path)\n tm.assert_frame_equal(df2, df)\n\n def test_to_csv_mixed(self):\n def create_cols(name):\n return [f"{name}{i:03d}" for i in range(5)]\n\n df_float = DataFrame(\n np.random.default_rng(2).standard_normal((100, 5)),\n dtype="float64",\n columns=create_cols("float"),\n )\n df_int = DataFrame(\n np.random.default_rng(2).standard_normal((100, 5)).astype("int64"),\n dtype="int64",\n columns=create_cols("int"),\n )\n df_bool = DataFrame(True, index=df_float.index, columns=create_cols("bool"))\n df_object = DataFrame(\n "foo", index=df_float.index, columns=create_cols("object"), dtype="object"\n )\n df_dt = DataFrame(\n Timestamp("20010101").as_unit("ns"),\n index=df_float.index,\n columns=create_cols("date"),\n )\n\n # add in some nans\n df_float.iloc[30:50, 1:3] = np.nan\n df_dt.iloc[30:50, 1:3] = np.nan\n\n df = pd.concat([df_float, df_int, df_bool, df_object, df_dt], axis=1)\n\n # dtype\n dtypes = {}\n for n, dtype in [\n ("float", np.float64),\n ("int", np.int64),\n ("bool", np.bool_),\n ("object", object),\n ]:\n for c in create_cols(n):\n dtypes[c] = dtype\n\n with tm.ensure_clean() as filename:\n df.to_csv(filename)\n rs = read_csv(\n filename, index_col=0, dtype=dtypes, parse_dates=create_cols("date")\n )\n tm.assert_frame_equal(rs, df)\n\n def test_to_csv_dups_cols(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((1000, 30)),\n columns=list(range(15)) + list(range(15)),\n dtype="float64",\n )\n\n with tm.ensure_clean() as filename:\n df.to_csv(filename) # single dtype, fine\n result = read_csv(filename, index_col=0)\n result.columns = df.columns\n tm.assert_frame_equal(result, df)\n\n df_float = DataFrame(\n np.random.default_rng(2).standard_normal((1000, 3)), dtype="float64"\n )\n df_int = DataFrame(np.random.default_rng(2).standard_normal((1000, 3))).astype(\n "int64"\n )\n df_bool = DataFrame(True, index=df_float.index, columns=range(3))\n df_object = DataFrame("foo", index=df_float.index, columns=range(3))\n df_dt = DataFrame(\n Timestamp("20010101").as_unit("ns"), index=df_float.index, columns=range(3)\n )\n df = pd.concat(\n [df_float, df_int, df_bool, df_object, df_dt], axis=1, ignore_index=True\n )\n\n df.columns = [0, 1, 2] * 5\n\n with tm.ensure_clean() as filename:\n df.to_csv(filename)\n result = read_csv(filename, index_col=0)\n\n # date cols\n for i in ["0.4", "1.4", "2.4"]:\n result[i] = to_datetime(result[i])\n\n result.columns = df.columns\n tm.assert_frame_equal(result, df)\n\n def test_to_csv_dups_cols2(self):\n # GH3457\n df = DataFrame(\n np.ones((5, 3)),\n index=Index([f"i-{i}" for i in range(5)], name="foo"),\n columns=Index(["a", "a", "b"]),\n )\n\n with tm.ensure_clean() as filename:\n df.to_csv(filename)\n\n # read_csv will rename the dups columns\n result = read_csv(filename, index_col=0)\n result = result.rename(columns={"a.1": "a"})\n tm.assert_frame_equal(result, df)\n\n @pytest.mark.parametrize("chunksize", [10000, 50000, 100000])\n def test_to_csv_chunking(self, chunksize):\n aa = DataFrame({"A": range(100000)})\n aa["B"] = aa.A + 1.0\n aa["C"] = aa.A + 2.0\n aa["D"] = aa.A + 3.0\n\n with tm.ensure_clean() as filename:\n aa.to_csv(filename, chunksize=chunksize)\n rs = read_csv(filename, index_col=0)\n tm.assert_frame_equal(rs, aa)\n\n @pytest.mark.slow\n def test_to_csv_wide_frame_formatting(self, monkeypatch):\n # Issue #8621\n chunksize = 100\n df = DataFrame(\n np.random.default_rng(2).standard_normal((1, chunksize + 10)),\n columns=None,\n index=None,\n )\n with tm.ensure_clean() as filename:\n with monkeypatch.context() as m:\n m.setattr("pandas.io.formats.csvs._DEFAULT_CHUNKSIZE_CELLS", chunksize)\n df.to_csv(filename, header=False, index=False)\n rs = read_csv(filename, header=None)\n tm.assert_frame_equal(rs, df)\n\n def test_to_csv_bug(self):\n f1 = StringIO("a,1.0\nb,2.0")\n df = self.read_csv(f1, header=None)\n newdf = DataFrame({"t": df[df.columns[0]]})\n\n with tm.ensure_clean() as path:\n newdf.to_csv(path)\n\n recons = read_csv(path, index_col=0)\n # don't check_names as t != 1\n tm.assert_frame_equal(recons, newdf, check_names=False)\n\n def test_to_csv_unicode(self):\n df = DataFrame({"c/\u03c3": [1, 2, 3]})\n with tm.ensure_clean() as path:\n df.to_csv(path, encoding="UTF-8")\n df2 = read_csv(path, index_col=0, encoding="UTF-8")\n tm.assert_frame_equal(df, df2)\n\n df.to_csv(path, encoding="UTF-8", index=False)\n df2 = read_csv(path, index_col=None, encoding="UTF-8")\n tm.assert_frame_equal(df, df2)\n\n def test_to_csv_unicode_index_col(self):\n buf = StringIO("")\n df = DataFrame(\n [["\u05d0", "d2", "d3", "d4"], ["a1", "a2", "a3", "a4"]],\n columns=["\u05d0", "\u05d1", "\u05d2", "\u05d3"],\n index=["\u05d0", "\u05d1"],\n )\n\n df.to_csv(buf, encoding="UTF-8")\n buf.seek(0)\n\n df2 = read_csv(buf, index_col=0, encoding="UTF-8")\n tm.assert_frame_equal(df, df2)\n\n def test_to_csv_stringio(self, float_frame):\n buf = StringIO()\n float_frame.to_csv(buf)\n buf.seek(0)\n recons = read_csv(buf, index_col=0)\n tm.assert_frame_equal(recons, float_frame)\n\n def test_to_csv_float_format(self):\n df = DataFrame(\n [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],\n index=["A", "B"],\n columns=["X", "Y", "Z"],\n )\n\n with tm.ensure_clean() as filename:\n df.to_csv(filename, float_format="%.2f")\n\n rs = read_csv(filename, index_col=0)\n xp = DataFrame(\n [[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]],\n index=["A", "B"],\n columns=["X", "Y", "Z"],\n )\n tm.assert_frame_equal(rs, xp)\n\n def test_to_csv_float_format_over_decimal(self):\n # GH#47436\n df = DataFrame({"a": [0.5, 1.0]})\n result = df.to_csv(\n decimal=",",\n float_format=lambda x: np.format_float_positional(x, trim="-"),\n index=False,\n )\n expected_rows = ["a", "0.5", "1"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n\n def test_to_csv_unicodewriter_quoting(self):\n df = DataFrame({"A": [1, 2, 3], "B": ["foo", "bar", "baz"]})\n\n buf = StringIO()\n df.to_csv(buf, index=False, quoting=csv.QUOTE_NONNUMERIC, encoding="utf-8")\n\n result = buf.getvalue()\n expected_rows = ['"A","B"', '1,"foo"', '2,"bar"', '3,"baz"']\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n\n @pytest.mark.parametrize("encoding", [None, "utf-8"])\n def test_to_csv_quote_none(self, encoding):\n # GH4328\n df = DataFrame({"A": ["hello", '{"hello"}']})\n buf = StringIO()\n df.to_csv(buf, quoting=csv.QUOTE_NONE, encoding=encoding, index=False)\n\n result = buf.getvalue()\n expected_rows = ["A", "hello", '{"hello"}']\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n\n def test_to_csv_index_no_leading_comma(self):\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["one", "two", "three"])\n\n buf = StringIO()\n df.to_csv(buf, index_label=False)\n\n expected_rows = ["A,B", "one,1,4", "two,2,5", "three,3,6"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert buf.getvalue() == expected\n\n def test_to_csv_lineterminators(self):\n # see gh-20353\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["one", "two", "three"])\n\n with tm.ensure_clean() as path:\n # case 1: CRLF as line terminator\n df.to_csv(path, lineterminator="\r\n")\n expected = b",A,B\r\none,1,4\r\ntwo,2,5\r\nthree,3,6\r\n"\n\n with open(path, mode="rb") as f:\n assert f.read() == expected\n\n with tm.ensure_clean() as path:\n # case 2: LF as line terminator\n df.to_csv(path, lineterminator="\n")\n expected = b",A,B\none,1,4\ntwo,2,5\nthree,3,6\n"\n\n with open(path, mode="rb") as f:\n assert f.read() == expected\n\n with tm.ensure_clean() as path:\n # case 3: The default line terminator(=os.linesep)(gh-21406)\n df.to_csv(path)\n os_linesep = os.linesep.encode("utf-8")\n expected = (\n b",A,B"\n + os_linesep\n + b"one,1,4"\n + os_linesep\n + b"two,2,5"\n + os_linesep\n + b"three,3,6"\n + os_linesep\n )\n\n with open(path, mode="rb") as f:\n assert f.read() == expected\n\n def test_to_csv_from_csv_categorical(self):\n # CSV with categoricals should result in the same output\n # as when one would add a "normal" Series/DataFrame.\n s = Series(pd.Categorical(["a", "b", "b", "a", "a", "c", "c", "c"]))\n s2 = Series(["a", "b", "b", "a", "a", "c", "c", "c"])\n res = StringIO()\n\n s.to_csv(res, header=False)\n exp = StringIO()\n\n s2.to_csv(exp, header=False)\n assert res.getvalue() == exp.getvalue()\n\n df = DataFrame({"s": s})\n df2 = DataFrame({"s": s2})\n\n res = StringIO()\n df.to_csv(res)\n\n exp = StringIO()\n df2.to_csv(exp)\n\n assert res.getvalue() == exp.getvalue()\n\n def test_to_csv_path_is_none(self, float_frame):\n # GH 8215\n # Make sure we return string for consistency with\n # Series.to_csv()\n csv_str = float_frame.to_csv(path_or_buf=None)\n assert isinstance(csv_str, str)\n recons = read_csv(StringIO(csv_str), index_col=0)\n tm.assert_frame_equal(float_frame, recons)\n\n @pytest.mark.parametrize(\n "df,encoding",\n [\n (\n DataFrame(\n [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],\n index=["A", "B"],\n columns=["X", "Y", "Z"],\n ),\n None,\n ),\n # GH 21241, 21118\n (DataFrame([["abc", "def", "ghi"]], columns=["X", "Y", "Z"]), "ascii"),\n (DataFrame(5 * [[123, "你好", "世界"]], columns=["X", "Y", "Z"]), "gb2312"),\n (\n DataFrame(\n 5 * [[123, "Γειά σου", "Κόσμε"]], # noqa: RUF001\n columns=["X", "Y", "Z"],\n ),\n "cp737",\n ),\n ],\n )\n def test_to_csv_compression(self, df, encoding, compression):\n with tm.ensure_clean() as filename:\n df.to_csv(filename, compression=compression, encoding=encoding)\n # test the round trip - to_csv -> read_csv\n result = read_csv(\n filename, compression=compression, index_col=0, encoding=encoding\n )\n tm.assert_frame_equal(df, result)\n\n # test the round trip using file handle - to_csv -> read_csv\n with get_handle(\n filename, "w", compression=compression, encoding=encoding\n ) as handles:\n df.to_csv(handles.handle, encoding=encoding)\n assert not handles.handle.closed\n\n result = read_csv(\n filename,\n compression=compression,\n encoding=encoding,\n index_col=0,\n ).squeeze("columns")\n tm.assert_frame_equal(df, result)\n\n # explicitly make sure file is compressed\n with tm.decompress_file(filename, compression) as fh:\n text = fh.read().decode(encoding or "utf8")\n for col in df.columns:\n assert col in text\n\n with tm.decompress_file(filename, compression) as fh:\n tm.assert_frame_equal(df, read_csv(fh, index_col=0, encoding=encoding))\n\n def test_to_csv_date_format(self, datetime_frame):\n with tm.ensure_clean("__tmp_to_csv_date_format__") as path:\n dt_index = datetime_frame.index\n datetime_frame = DataFrame(\n {"A": dt_index, "B": dt_index.shift(1)}, index=dt_index\n )\n datetime_frame.to_csv(path, date_format="%Y%m%d")\n\n # Check that the data was put in the specified format\n test = read_csv(path, index_col=0)\n\n datetime_frame_int = datetime_frame.map(lambda x: int(x.strftime("%Y%m%d")))\n datetime_frame_int.index = datetime_frame_int.index.map(\n lambda x: int(x.strftime("%Y%m%d"))\n )\n\n tm.assert_frame_equal(test, datetime_frame_int)\n\n datetime_frame.to_csv(path, date_format="%Y-%m-%d")\n\n # Check that the data was put in the specified format\n test = read_csv(path, index_col=0)\n datetime_frame_str = datetime_frame.map(lambda x: x.strftime("%Y-%m-%d"))\n datetime_frame_str.index = datetime_frame_str.index.map(\n lambda x: x.strftime("%Y-%m-%d")\n )\n\n tm.assert_frame_equal(test, datetime_frame_str)\n\n # Check that columns get converted\n datetime_frame_columns = datetime_frame.T\n datetime_frame_columns.to_csv(path, date_format="%Y%m%d")\n\n test = read_csv(path, index_col=0)\n\n datetime_frame_columns = datetime_frame_columns.map(\n lambda x: int(x.strftime("%Y%m%d"))\n )\n # Columns don't get converted to ints by read_csv\n datetime_frame_columns.columns = datetime_frame_columns.columns.map(\n lambda x: x.strftime("%Y%m%d")\n )\n\n tm.assert_frame_equal(test, datetime_frame_columns)\n\n # test NaTs\n nat_index = to_datetime(\n ["NaT"] * 10 + ["2000-01-01", "2000-01-01", "2000-01-01"]\n )\n nat_frame = DataFrame({"A": nat_index}, index=nat_index)\n nat_frame.to_csv(path, date_format="%Y-%m-%d")\n\n test = read_csv(path, parse_dates=[0, 1], index_col=0)\n\n tm.assert_frame_equal(test, nat_frame)\n\n @pytest.mark.parametrize("td", [pd.Timedelta(0), pd.Timedelta("10s")])\n def test_to_csv_with_dst_transitions(self, td):\n with tm.ensure_clean("csv_date_format_with_dst") as path:\n # make sure we are not failing on transitions\n times = date_range(\n "2013-10-26 23:00",\n "2013-10-27 01:00",\n tz="Europe/London",\n freq="h",\n ambiguous="infer",\n )\n i = times + td\n i = i._with_freq(None) # freq is not preserved by read_csv\n time_range = np.array(range(len(i)), dtype="int64")\n df = DataFrame({"A": time_range}, index=i)\n df.to_csv(path, index=True)\n # we have to reconvert the index as we\n # don't parse the tz's\n result = read_csv(path, index_col=0)\n result.index = to_datetime(result.index, utc=True).tz_convert(\n "Europe/London"\n )\n tm.assert_frame_equal(result, df)\n\n def test_to_csv_with_dst_transitions_with_pickle(self):\n # GH11619\n idx = date_range("2015-01-01", "2015-12-31", freq="h", tz="Europe/Paris")\n idx = idx._with_freq(None) # freq does not round-trip\n idx._data._freq = None # otherwise there is trouble on unpickle\n df = DataFrame({"values": 1, "idx": idx}, index=idx)\n with tm.ensure_clean("csv_date_format_with_dst") as path:\n df.to_csv(path, index=True)\n result = read_csv(path, index_col=0)\n result.index = to_datetime(result.index, utc=True).tz_convert(\n "Europe/Paris"\n )\n result["idx"] = to_datetime(result["idx"], utc=True).astype(\n "datetime64[ns, Europe/Paris]"\n )\n tm.assert_frame_equal(result, df)\n\n # assert working\n df.astype(str)\n\n with tm.ensure_clean("csv_date_format_with_dst") as path:\n df.to_pickle(path)\n result = pd.read_pickle(path)\n tm.assert_frame_equal(result, df)\n\n def test_to_csv_quoting(self):\n df = DataFrame(\n {\n "c_bool": [True, False],\n "c_float": [1.0, 3.2],\n "c_int": [42, np.nan],\n "c_string": ["a", "b,c"],\n }\n )\n\n expected_rows = [\n ",c_bool,c_float,c_int,c_string",\n "0,True,1.0,42.0,a",\n '1,False,3.2,,"b,c"',\n ]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n\n result = df.to_csv()\n assert result == expected\n\n result = df.to_csv(quoting=None)\n assert result == expected\n\n expected_rows = [\n ",c_bool,c_float,c_int,c_string",\n "0,True,1.0,42.0,a",\n '1,False,3.2,,"b,c"',\n ]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n\n result = df.to_csv(quoting=csv.QUOTE_MINIMAL)\n assert result == expected\n\n expected_rows = [\n '"","c_bool","c_float","c_int","c_string"',\n '"0","True","1.0","42.0","a"',\n '"1","False","3.2","","b,c"',\n ]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n\n result = df.to_csv(quoting=csv.QUOTE_ALL)\n assert result == expected\n\n # see gh-12922, gh-13259: make sure changes to\n # the formatters do not break this behaviour\n expected_rows = [\n '"","c_bool","c_float","c_int","c_string"',\n '0,True,1.0,42.0,"a"',\n '1,False,3.2,"","b,c"',\n ]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n result = df.to_csv(quoting=csv.QUOTE_NONNUMERIC)\n assert result == expected\n\n msg = "need to escape, but no escapechar set"\n with pytest.raises(csv.Error, match=msg):\n df.to_csv(quoting=csv.QUOTE_NONE)\n\n with pytest.raises(csv.Error, match=msg):\n df.to_csv(quoting=csv.QUOTE_NONE, escapechar=None)\n\n expected_rows = [\n ",c_bool,c_float,c_int,c_string",\n "0,True,1.0,42.0,a",\n "1,False,3.2,,b!,c",\n ]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n result = df.to_csv(quoting=csv.QUOTE_NONE, escapechar="!")\n assert result == expected\n\n expected_rows = [\n ",c_bool,c_ffloat,c_int,c_string",\n "0,True,1.0,42.0,a",\n "1,False,3.2,,bf,c",\n ]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n result = df.to_csv(quoting=csv.QUOTE_NONE, escapechar="f")\n assert result == expected\n\n # see gh-3503: quoting Windows line terminators\n # presents with encoding?\n text_rows = ["a,b,c", '1,"test \r\n",3']\n text = tm.convert_rows_list_to_csv_str(text_rows)\n df = read_csv(StringIO(text))\n\n buf = StringIO()\n df.to_csv(buf, encoding="utf-8", index=False)\n assert buf.getvalue() == text\n\n # xref gh-7791: make sure the quoting parameter is passed through\n # with multi-indexes\n df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]})\n df = df.set_index(["a", "b"])\n\n expected_rows = ['"a","b","c"', '"1","3","5"', '"2","4","6"']\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df.to_csv(quoting=csv.QUOTE_ALL) == expected\n\n def test_period_index_date_overflow(self):\n # see gh-15982\n\n dates = ["1990-01-01", "2000-01-01", "3005-01-01"]\n index = pd.PeriodIndex(dates, freq="D")\n\n df = DataFrame([4, 5, 6], index=index)\n result = df.to_csv()\n\n expected_rows = [",0", "1990-01-01,4", "2000-01-01,5", "3005-01-01,6"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n\n date_format = "%m-%d-%Y"\n result = df.to_csv(date_format=date_format)\n\n expected_rows = [",0", "01-01-1990,4", "01-01-2000,5", "01-01-3005,6"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n\n # Overflow with pd.NaT\n dates = ["1990-01-01", NaT, "3005-01-01"]\n index = pd.PeriodIndex(dates, freq="D")\n\n df = DataFrame([4, 5, 6], index=index)\n result = df.to_csv()\n\n expected_rows = [",0", "1990-01-01,4", ",5", "3005-01-01,6"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n\n def test_multi_index_header(self):\n # see gh-5539\n columns = MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), ("b", 2)])\n df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])\n df.columns = columns\n\n header = ["a", "b", "c", "d"]\n result = df.to_csv(header=header)\n\n expected_rows = [",a,b,c,d", "0,1,2,3,4", "1,5,6,7,8"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n\n def test_to_csv_single_level_multi_index(self):\n # see gh-26303\n index = Index([(1,), (2,), (3,)])\n df = DataFrame([[1, 2, 3]], columns=index)\n df = df.reindex(columns=[(1,), (3,)])\n expected = ",1,3\n0,1,3\n"\n result = df.to_csv(lineterminator="\n")\n tm.assert_almost_equal(result, expected)\n\n def test_gz_lineend(self):\n # GH 25311\n df = DataFrame({"a": [1, 2]})\n expected_rows = ["a", "1", "2"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n with tm.ensure_clean("__test_gz_lineend.csv.gz") as path:\n df.to_csv(path, index=False)\n with tm.decompress_file(path, compression="gzip") as f:\n result = f.read().decode("utf-8")\n\n assert result == expected\n\n def test_to_csv_numpy_16_bug(self):\n frame = DataFrame({"a": date_range("1/1/2000", periods=10)})\n\n buf = StringIO()\n frame.to_csv(buf)\n\n result = buf.getvalue()\n assert "2000-01-01" in result\n\n def test_to_csv_na_quoting(self):\n # GH 15891\n # Normalize carriage return for Windows OS\n result = (\n DataFrame([None, None])\n .to_csv(None, header=False, index=False, na_rep="")\n .replace("\r\n", "\n")\n )\n expected = '""\n""\n'\n assert result == expected\n\n def test_to_csv_categorical_and_ea(self):\n # GH#46812\n df = DataFrame({"a": "x", "b": [1, pd.NA]})\n df["b"] = df["b"].astype("Int16")\n df["b"] = df["b"].astype("category")\n result = df.to_csv()\n expected_rows = [",a,b", "0,x,1", "1,x,"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n\n def test_to_csv_categorical_and_interval(self):\n # GH#46297\n df = DataFrame(\n {\n "a": [\n pd.Interval(\n Timestamp("2020-01-01"),\n Timestamp("2020-01-02"),\n closed="both",\n )\n ]\n }\n )\n df["a"] = df["a"].astype("category")\n result = df.to_csv()\n expected_rows = [",a", '0,"[2020-01-01 00:00:00, 2020-01-02 00:00:00]"']\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_to_csv.py
test_to_csv.py
Python
51,560
0.75
0.096222
0.076988
python-kit
486
2023-11-25T02:24:57.247187
BSD-3-Clause
true
0d3bcb1af25b8def542c44fbead4fdf2
from collections import (\n OrderedDict,\n defaultdict,\n)\nfrom datetime import datetime\n\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas import (\n NA,\n DataFrame,\n Index,\n Interval,\n MultiIndex,\n Period,\n Series,\n Timedelta,\n Timestamp,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameToDict:\n def test_to_dict_timestamp(self):\n # GH#11247\n # split/records producing np.datetime64 rather than Timestamps\n # on datetime64[ns] dtypes only\n\n tsmp = Timestamp("20130101")\n test_data = DataFrame({"A": [tsmp, tsmp], "B": [tsmp, tsmp]})\n test_data_mixed = DataFrame({"A": [tsmp, tsmp], "B": [1, 2]})\n\n expected_records = [{"A": tsmp, "B": tsmp}, {"A": tsmp, "B": tsmp}]\n expected_records_mixed = [{"A": tsmp, "B": 1}, {"A": tsmp, "B": 2}]\n\n assert test_data.to_dict(orient="records") == expected_records\n assert test_data_mixed.to_dict(orient="records") == expected_records_mixed\n\n expected_series = {\n "A": Series([tsmp, tsmp], name="A"),\n "B": Series([tsmp, tsmp], name="B"),\n }\n expected_series_mixed = {\n "A": Series([tsmp, tsmp], name="A"),\n "B": Series([1, 2], name="B"),\n }\n\n tm.assert_dict_equal(test_data.to_dict(orient="series"), expected_series)\n tm.assert_dict_equal(\n test_data_mixed.to_dict(orient="series"), expected_series_mixed\n )\n\n expected_split = {\n "index": [0, 1],\n "data": [[tsmp, tsmp], [tsmp, tsmp]],\n "columns": ["A", "B"],\n }\n expected_split_mixed = {\n "index": [0, 1],\n "data": [[tsmp, 1], [tsmp, 2]],\n "columns": ["A", "B"],\n }\n\n tm.assert_dict_equal(test_data.to_dict(orient="split"), expected_split)\n tm.assert_dict_equal(\n test_data_mixed.to_dict(orient="split"), expected_split_mixed\n )\n\n def test_to_dict_index_not_unique_with_index_orient(self):\n # GH#22801\n # Data loss when indexes are not unique. Raise ValueError.\n df = DataFrame({"a": [1, 2], "b": [0.5, 0.75]}, index=["A", "A"])\n msg = "DataFrame index must be unique for orient='index'"\n with pytest.raises(ValueError, match=msg):\n df.to_dict(orient="index")\n\n def test_to_dict_invalid_orient(self):\n df = DataFrame({"A": [0, 1]})\n msg = "orient 'xinvalid' not understood"\n with pytest.raises(ValueError, match=msg):\n df.to_dict(orient="xinvalid")\n\n @pytest.mark.parametrize("orient", ["d", "l", "r", "sp", "s", "i"])\n def test_to_dict_short_orient_raises(self, orient):\n # GH#32515\n df = DataFrame({"A": [0, 1]})\n with pytest.raises(ValueError, match="not understood"):\n df.to_dict(orient=orient)\n\n @pytest.mark.parametrize("mapping", [dict, defaultdict(list), OrderedDict])\n def test_to_dict(self, mapping):\n # orient= should only take the listed options\n # see GH#32515\n test_data = {"A": {"1": 1, "2": 2}, "B": {"1": "1", "2": "2", "3": "3"}}\n\n # GH#16122\n recons_data = DataFrame(test_data).to_dict(into=mapping)\n\n for k, v in test_data.items():\n for k2, v2 in v.items():\n assert v2 == recons_data[k][k2]\n\n recons_data = DataFrame(test_data).to_dict("list", into=mapping)\n\n for k, v in test_data.items():\n for k2, v2 in v.items():\n assert v2 == recons_data[k][int(k2) - 1]\n\n recons_data = DataFrame(test_data).to_dict("series", into=mapping)\n\n for k, v in test_data.items():\n for k2, v2 in v.items():\n assert v2 == recons_data[k][k2]\n\n recons_data = DataFrame(test_data).to_dict("split", into=mapping)\n expected_split = {\n "columns": ["A", "B"],\n "index": ["1", "2", "3"],\n "data": [[1.0, "1"], [2.0, "2"], [np.nan, "3"]],\n }\n tm.assert_dict_equal(recons_data, expected_split)\n\n recons_data = DataFrame(test_data).to_dict("records", into=mapping)\n expected_records = [\n {"A": 1.0, "B": "1"},\n {"A": 2.0, "B": "2"},\n {"A": np.nan, "B": "3"},\n ]\n assert isinstance(recons_data, list)\n assert len(recons_data) == 3\n for left, right in zip(recons_data, expected_records):\n tm.assert_dict_equal(left, right)\n\n # GH#10844\n recons_data = DataFrame(test_data).to_dict("index")\n\n for k, v in test_data.items():\n for k2, v2 in v.items():\n assert v2 == recons_data[k2][k]\n\n df = DataFrame(test_data)\n df["duped"] = df[df.columns[0]]\n recons_data = df.to_dict("index")\n comp_data = test_data.copy()\n comp_data["duped"] = comp_data[df.columns[0]]\n for k, v in comp_data.items():\n for k2, v2 in v.items():\n assert v2 == recons_data[k2][k]\n\n @pytest.mark.parametrize("mapping", [list, defaultdict, []])\n def test_to_dict_errors(self, mapping):\n # GH#16122\n df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)))\n msg = "|".join(\n [\n "unsupported type: <class 'list'>",\n r"to_dict\(\) only accepts initialized defaultdicts",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n df.to_dict(into=mapping)\n\n def test_to_dict_not_unique_warning(self):\n # GH#16927: When converting to a dict, if a column has a non-unique name\n # it will be dropped, throwing a warning.\n df = DataFrame([[1, 2, 3]], columns=["a", "a", "b"])\n with tm.assert_produces_warning(UserWarning):\n df.to_dict()\n\n @pytest.mark.filterwarnings("ignore::UserWarning")\n @pytest.mark.parametrize(\n "orient,expected",\n [\n ("list", {"A": [2, 5], "B": [3, 6]}),\n ("dict", {"A": {0: 2, 1: 5}, "B": {0: 3, 1: 6}}),\n ],\n )\n def test_to_dict_not_unique(self, orient, expected):\n # GH#54824: This is to make sure that dataframes with non-unique column\n # would have uniform behavior throughout different orients\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "A", "B"])\n result = df.to_dict(orient)\n assert result == expected\n\n # orient - orient argument to to_dict function\n # item_getter - function for extracting value from\n # the resulting dict using column name and index\n @pytest.mark.parametrize(\n "orient,item_getter",\n [\n ("dict", lambda d, col, idx: d[col][idx]),\n ("records", lambda d, col, idx: d[idx][col]),\n ("list", lambda d, col, idx: d[col][idx]),\n ("split", lambda d, col, idx: d["data"][idx][d["columns"].index(col)]),\n ("index", lambda d, col, idx: d[idx][col]),\n ],\n )\n def test_to_dict_box_scalars(self, orient, item_getter):\n # GH#14216, GH#23753\n # make sure that we are boxing properly\n df = DataFrame({"a": [1, 2], "b": [0.1, 0.2]})\n result = df.to_dict(orient=orient)\n assert isinstance(item_getter(result, "a", 0), int)\n assert isinstance(item_getter(result, "b", 0), float)\n\n def test_to_dict_tz(self):\n # GH#18372 When converting to dict with orient='records' columns of\n # datetime that are tz-aware were not converted to required arrays\n data = [\n (datetime(2017, 11, 18, 21, 53, 0, 219225, tzinfo=pytz.utc),),\n (datetime(2017, 11, 18, 22, 6, 30, 61810, tzinfo=pytz.utc),),\n ]\n df = DataFrame(list(data), columns=["d"])\n\n result = df.to_dict(orient="records")\n expected = [\n {"d": Timestamp("2017-11-18 21:53:00.219225+0000", tz=pytz.utc)},\n {"d": Timestamp("2017-11-18 22:06:30.061810+0000", tz=pytz.utc)},\n ]\n tm.assert_dict_equal(result[0], expected[0])\n tm.assert_dict_equal(result[1], expected[1])\n\n @pytest.mark.parametrize(\n "into, expected",\n [\n (\n dict,\n {\n 0: {"int_col": 1, "float_col": 1.0},\n 1: {"int_col": 2, "float_col": 2.0},\n 2: {"int_col": 3, "float_col": 3.0},\n },\n ),\n (\n OrderedDict,\n OrderedDict(\n [\n (0, {"int_col": 1, "float_col": 1.0}),\n (1, {"int_col": 2, "float_col": 2.0}),\n (2, {"int_col": 3, "float_col": 3.0}),\n ]\n ),\n ),\n (\n defaultdict(dict),\n defaultdict(\n dict,\n {\n 0: {"int_col": 1, "float_col": 1.0},\n 1: {"int_col": 2, "float_col": 2.0},\n 2: {"int_col": 3, "float_col": 3.0},\n },\n ),\n ),\n ],\n )\n def test_to_dict_index_dtypes(self, into, expected):\n # GH#18580\n # When using to_dict(orient='index') on a dataframe with int\n # and float columns only the int columns were cast to float\n\n df = DataFrame({"int_col": [1, 2, 3], "float_col": [1.0, 2.0, 3.0]})\n\n result = df.to_dict(orient="index", into=into)\n cols = ["int_col", "float_col"]\n result = DataFrame.from_dict(result, orient="index")[cols]\n expected = DataFrame.from_dict(expected, orient="index")[cols]\n tm.assert_frame_equal(result, expected)\n\n def test_to_dict_numeric_names(self):\n # GH#24940\n df = DataFrame({str(i): [i] for i in range(5)})\n result = set(df.to_dict("records")[0].keys())\n expected = set(df.columns)\n assert result == expected\n\n def test_to_dict_wide(self):\n # GH#24939\n df = DataFrame({(f"A_{i:d}"): [i] for i in range(256)})\n result = df.to_dict("records")[0]\n expected = {f"A_{i:d}": i for i in range(256)}\n assert result == expected\n\n @pytest.mark.parametrize(\n "data,dtype",\n (\n ([True, True, False], bool),\n [\n [\n datetime(2018, 1, 1),\n datetime(2019, 2, 2),\n datetime(2020, 3, 3),\n ],\n Timestamp,\n ],\n [[1.0, 2.0, 3.0], float],\n [[1, 2, 3], int],\n [["X", "Y", "Z"], str],\n ),\n )\n def test_to_dict_orient_dtype(self, data, dtype):\n # GH22620 & GH21256\n\n df = DataFrame({"a": data})\n d = df.to_dict(orient="records")\n assert all(type(record["a"]) is dtype for record in d)\n\n @pytest.mark.parametrize(\n "data,expected_dtype",\n (\n [np.uint64(2), int],\n [np.int64(-9), int],\n [np.float64(1.1), float],\n [np.bool_(True), bool],\n [np.datetime64("2005-02-25"), Timestamp],\n ),\n )\n def test_to_dict_scalar_constructor_orient_dtype(self, data, expected_dtype):\n # GH22620 & GH21256\n\n df = DataFrame({"a": data}, index=[0])\n d = df.to_dict(orient="records")\n result = type(d[0]["a"])\n assert result is expected_dtype\n\n def test_to_dict_mixed_numeric_frame(self):\n # GH 12859\n df = DataFrame({"a": [1.0], "b": [9.0]})\n result = df.reset_index().to_dict("records")\n expected = [{"index": 0, "a": 1.0, "b": 9.0}]\n assert result == expected\n\n @pytest.mark.parametrize(\n "index",\n [\n None,\n Index(["aa", "bb"]),\n Index(["aa", "bb"], name="cc"),\n MultiIndex.from_tuples([("a", "b"), ("a", "c")]),\n MultiIndex.from_tuples([("a", "b"), ("a", "c")], names=["n1", "n2"]),\n ],\n )\n @pytest.mark.parametrize(\n "columns",\n [\n ["x", "y"],\n Index(["x", "y"]),\n Index(["x", "y"], name="z"),\n MultiIndex.from_tuples([("x", 1), ("y", 2)]),\n MultiIndex.from_tuples([("x", 1), ("y", 2)], names=["z1", "z2"]),\n ],\n )\n def test_to_dict_orient_tight(self, index, columns):\n df = DataFrame.from_records(\n [[1, 3], [2, 4]],\n columns=columns,\n index=index,\n )\n roundtrip = DataFrame.from_dict(df.to_dict(orient="tight"), orient="tight")\n\n tm.assert_frame_equal(df, roundtrip)\n\n @pytest.mark.parametrize(\n "orient",\n ["dict", "list", "split", "records", "index", "tight"],\n )\n @pytest.mark.parametrize(\n "data,expected_types",\n (\n (\n {\n "a": [np.int64(1), 1, np.int64(3)],\n "b": [np.float64(1.0), 2.0, np.float64(3.0)],\n "c": [np.float64(1.0), 2, np.int64(3)],\n "d": [np.float64(1.0), "a", np.int64(3)],\n "e": [np.float64(1.0), ["a"], np.int64(3)],\n "f": [np.float64(1.0), ("a",), np.int64(3)],\n },\n {\n "a": [int, int, int],\n "b": [float, float, float],\n "c": [float, float, float],\n "d": [float, str, int],\n "e": [float, list, int],\n "f": [float, tuple, int],\n },\n ),\n (\n {\n "a": [1, 2, 3],\n "b": [1.1, 2.2, 3.3],\n },\n {\n "a": [int, int, int],\n "b": [float, float, float],\n },\n ),\n ( # Make sure we have one df which is all object type cols\n {\n "a": [1, "hello", 3],\n "b": [1.1, "world", 3.3],\n },\n {\n "a": [int, str, int],\n "b": [float, str, float],\n },\n ),\n ),\n )\n def test_to_dict_returns_native_types(self, orient, data, expected_types):\n # GH 46751\n # Tests we get back native types for all orient types\n df = DataFrame(data)\n result = df.to_dict(orient)\n if orient == "dict":\n assertion_iterator = (\n (i, key, value)\n for key, index_value_map in result.items()\n for i, value in index_value_map.items()\n )\n elif orient == "list":\n assertion_iterator = (\n (i, key, value)\n for key, values in result.items()\n for i, value in enumerate(values)\n )\n elif orient in {"split", "tight"}:\n assertion_iterator = (\n (i, key, result["data"][i][j])\n for i in result["index"]\n for j, key in enumerate(result["columns"])\n )\n elif orient == "records":\n assertion_iterator = (\n (i, key, value)\n for i, record in enumerate(result)\n for key, value in record.items()\n )\n elif orient == "index":\n assertion_iterator = (\n (i, key, value)\n for i, record in result.items()\n for key, value in record.items()\n )\n\n for i, key, value in assertion_iterator:\n assert value == data[key][i]\n assert type(value) is expected_types[key][i]\n\n @pytest.mark.parametrize("orient", ["dict", "list", "series", "records", "index"])\n def test_to_dict_index_false_error(self, orient):\n # GH#46398\n df = DataFrame({"col1": [1, 2], "col2": [3, 4]}, index=["row1", "row2"])\n msg = "'index=False' is only valid when 'orient' is 'split' or 'tight'"\n with pytest.raises(ValueError, match=msg):\n df.to_dict(orient=orient, index=False)\n\n @pytest.mark.parametrize(\n "orient, expected",\n [\n ("split", {"columns": ["col1", "col2"], "data": [[1, 3], [2, 4]]}),\n (\n "tight",\n {\n "columns": ["col1", "col2"],\n "data": [[1, 3], [2, 4]],\n "column_names": [None],\n },\n ),\n ],\n )\n def test_to_dict_index_false(self, orient, expected):\n # GH#46398\n df = DataFrame({"col1": [1, 2], "col2": [3, 4]}, index=["row1", "row2"])\n result = df.to_dict(orient=orient, index=False)\n tm.assert_dict_equal(result, expected)\n\n @pytest.mark.parametrize(\n "orient, expected",\n [\n ("dict", {"a": {0: 1, 1: None}}),\n ("list", {"a": [1, None]}),\n ("split", {"index": [0, 1], "columns": ["a"], "data": [[1], [None]]}),\n (\n "tight",\n {\n "index": [0, 1],\n "columns": ["a"],\n "data": [[1], [None]],\n "index_names": [None],\n "column_names": [None],\n },\n ),\n ("records", [{"a": 1}, {"a": None}]),\n ("index", {0: {"a": 1}, 1: {"a": None}}),\n ],\n )\n def test_to_dict_na_to_none(self, orient, expected):\n # GH#50795\n df = DataFrame({"a": [1, NA]}, dtype="Int64")\n result = df.to_dict(orient=orient)\n assert result == expected\n\n def test_to_dict_masked_native_python(self):\n # GH#34665\n df = DataFrame({"a": Series([1, 2], dtype="Int64"), "B": 1})\n result = df.to_dict(orient="records")\n assert isinstance(result[0]["a"], int)\n\n df = DataFrame({"a": Series([1, NA], dtype="Int64"), "B": 1})\n result = df.to_dict(orient="records")\n assert isinstance(result[0]["a"], int)\n\n def test_to_dict_pos_args_deprecation(self):\n # GH-54229\n df = DataFrame({"a": [1, 2, 3]})\n msg = (\n r"Starting with pandas version 3.0 all arguments of to_dict except for the "\n r"argument 'orient' will be keyword-only."\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n df.to_dict("records", {})\n\n\n@pytest.mark.parametrize(\n "val", [Timestamp(2020, 1, 1), Timedelta(1), Period("2020"), Interval(1, 2)]\n)\ndef test_to_dict_list_pd_scalars(val):\n # GH 54824\n df = DataFrame({"a": [val]})\n result = df.to_dict(orient="list")\n expected = {"a": [val]}\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_to_dict.py
test_to_dict.py
Python
18,640
0.95
0.11215
0.079002
react-lib
782
2024-02-11T00:39:30.757412
Apache-2.0
true
a81c12a4f6da650630efd3710f0225d1
import numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n DataFrame,\n MultiIndex,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import NumpyExtensionArray\n\npytestmark = td.skip_array_manager_invalid_test\n\n\nclass TestToDictOfBlocks:\n @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")\n def test_no_copy_blocks(self, float_frame, using_copy_on_write):\n # GH#9607\n df = DataFrame(float_frame, copy=True)\n column = df.columns[0]\n\n _last_df = None\n # use the copy=False, change a column\n blocks = df._to_dict_of_blocks()\n for _df in blocks.values():\n _last_df = _df\n if column in _df:\n _df.loc[:, column] = _df[column] + 1\n\n if not using_copy_on_write:\n # make sure we did change the original DataFrame\n assert _last_df is not None and _last_df[column].equals(df[column])\n else:\n assert _last_df is not None and not _last_df[column].equals(df[column])\n\n\n@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")\ndef test_to_dict_of_blocks_item_cache(using_copy_on_write, warn_copy_on_write):\n # Calling to_dict_of_blocks should not poison item_cache\n df = DataFrame({"a": [1, 2, 3, 4], "b": ["a", "b", "c", "d"]})\n df["c"] = NumpyExtensionArray(np.array([1, 2, None, 3], dtype=object))\n mgr = df._mgr\n assert len(mgr.blocks) == 3 # i.e. not consolidated\n\n ser = df["b"] # populations item_cache["b"]\n\n df._to_dict_of_blocks()\n\n if using_copy_on_write:\n with pytest.raises(ValueError, match="read-only"):\n ser.values[0] = "foo"\n elif warn_copy_on_write:\n ser.values[0] = "foo"\n assert df.loc[0, "b"] == "foo"\n # with warning mode, the item cache is disabled\n assert df["b"] is not ser\n else:\n # Check that the to_dict_of_blocks didn't break link between ser and df\n ser.values[0] = "foo"\n assert df.loc[0, "b"] == "foo"\n\n assert df["b"] is ser\n\n\ndef test_set_change_dtype_slice():\n # GH#8850\n cols = MultiIndex.from_tuples([("1st", "a"), ("2nd", "b"), ("3rd", "c")])\n df = DataFrame([[1.0, 2, 3], [4.0, 5, 6]], columns=cols)\n df["2nd"] = df["2nd"] * 2.0\n\n blocks = df._to_dict_of_blocks()\n assert sorted(blocks.keys()) == ["float64", "int64"]\n tm.assert_frame_equal(\n blocks["float64"], DataFrame([[1.0, 4.0], [4.0, 10.0]], columns=cols[:2])\n )\n tm.assert_frame_equal(blocks["int64"], DataFrame([[3], [6]], columns=cols[2:]))\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_to_dict_of_blocks.py
test_to_dict_of_blocks.py
Python
2,641
0.95
0.101266
0.112903
react-lib
476
2024-03-06T23:05:57.410625
BSD-3-Clause
true
0e26d19e142887277d5ebd5d63d4a57e
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n DataFrame,\n Timestamp,\n)\nimport pandas._testing as tm\n\n\nclass TestToNumpy:\n def test_to_numpy(self):\n df = DataFrame({"A": [1, 2], "B": [3, 4.5]})\n expected = np.array([[1, 3], [2, 4.5]])\n result = df.to_numpy()\n tm.assert_numpy_array_equal(result, expected)\n\n def test_to_numpy_dtype(self):\n df = DataFrame({"A": [1, 2], "B": [3, 4.5]})\n expected = np.array([[1, 3], [2, 4]], dtype="int64")\n result = df.to_numpy(dtype="int64")\n tm.assert_numpy_array_equal(result, expected)\n\n @td.skip_array_manager_invalid_test\n def test_to_numpy_copy(self, using_copy_on_write):\n arr = np.random.default_rng(2).standard_normal((4, 3))\n df = DataFrame(arr)\n if using_copy_on_write:\n assert df.values.base is not arr\n assert df.to_numpy(copy=False).base is df.values.base\n else:\n assert df.values.base is arr\n assert df.to_numpy(copy=False).base is arr\n assert df.to_numpy(copy=True).base is not arr\n\n # we still don't want a copy when na_value=np.nan is passed,\n # and that can be respected because we are already numpy-float\n if using_copy_on_write:\n assert df.to_numpy(copy=False).base is df.values.base\n else:\n assert df.to_numpy(copy=False, na_value=np.nan).base is arr\n\n @pytest.mark.filterwarnings(\n "ignore:invalid value encountered in cast:RuntimeWarning"\n )\n def test_to_numpy_mixed_dtype_to_str(self):\n # https://github.com/pandas-dev/pandas/issues/35455\n df = DataFrame([[Timestamp("2020-01-01 00:00:00"), 100.0]])\n result = df.to_numpy(dtype=str)\n expected = np.array([["2020-01-01 00:00:00", "100.0"]], dtype=str)\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_to_numpy.py
test_to_numpy.py
Python
1,914
0.95
0.132075
0.066667
node-utils
868
2024-11-11T04:15:05.373632
GPL-3.0
true
9a35a33384745e5aeeb0f89e7fbe27d8
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n DatetimeIndex,\n PeriodIndex,\n Series,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestToPeriod:\n def test_to_period(self, frame_or_series):\n K = 5\n\n dr = date_range("1/1/2000", "1/1/2001", freq="D")\n obj = DataFrame(\n np.random.default_rng(2).standard_normal((len(dr), K)),\n index=dr,\n columns=["A", "B", "C", "D", "E"],\n )\n obj["mix"] = "a"\n obj = tm.get_obj(obj, frame_or_series)\n\n pts = obj.to_period()\n exp = obj.copy()\n exp.index = period_range("1/1/2000", "1/1/2001")\n tm.assert_equal(pts, exp)\n\n pts = obj.to_period("M")\n exp.index = exp.index.asfreq("M")\n tm.assert_equal(pts, exp)\n\n def test_to_period_without_freq(self, frame_or_series):\n # GH#7606 without freq\n idx = DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"])\n exp_idx = PeriodIndex(\n ["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], freq="D"\n )\n\n obj = DataFrame(\n np.random.default_rng(2).standard_normal((4, 4)), index=idx, columns=idx\n )\n obj = tm.get_obj(obj, frame_or_series)\n expected = obj.copy()\n expected.index = exp_idx\n tm.assert_equal(obj.to_period(), expected)\n\n if frame_or_series is DataFrame:\n expected = obj.copy()\n expected.columns = exp_idx\n tm.assert_frame_equal(obj.to_period(axis=1), expected)\n\n def test_to_period_columns(self):\n dr = date_range("1/1/2000", "1/1/2001")\n df = DataFrame(np.random.default_rng(2).standard_normal((len(dr), 5)), index=dr)\n df["mix"] = "a"\n\n df = df.T\n pts = df.to_period(axis=1)\n exp = df.copy()\n exp.columns = period_range("1/1/2000", "1/1/2001")\n tm.assert_frame_equal(pts, exp)\n\n pts = df.to_period("M", axis=1)\n tm.assert_index_equal(pts.columns, exp.columns.asfreq("M"))\n\n def test_to_period_invalid_axis(self):\n dr = date_range("1/1/2000", "1/1/2001")\n df = DataFrame(np.random.default_rng(2).standard_normal((len(dr), 5)), index=dr)\n df["mix"] = "a"\n\n msg = "No axis named 2 for object type DataFrame"\n with pytest.raises(ValueError, match=msg):\n df.to_period(axis=2)\n\n def test_to_period_raises(self, index, frame_or_series):\n # https://github.com/pandas-dev/pandas/issues/33327\n obj = Series(index=index, dtype=object)\n if frame_or_series is DataFrame:\n obj = obj.to_frame()\n\n if not isinstance(index, DatetimeIndex):\n msg = f"unsupported Type {type(index).__name__}"\n with pytest.raises(TypeError, match=msg):\n obj.to_period()\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_to_period.py
test_to_period.py
Python
2,863
0.95
0.11236
0.027397
node-utils
342
2023-11-22T18:29:08.866231
MIT
true
243710c97ffdb74a5539e53297e56fa5
from collections import abc\nimport email\nfrom email.parser import Parser\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n CategoricalDtype,\n DataFrame,\n MultiIndex,\n Series,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameToRecords:\n def test_to_records_timeseries(self):\n index = date_range("1/1/2000", periods=10)\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 3)),\n index=index,\n columns=["a", "b", "c"],\n )\n\n result = df.to_records()\n assert result["index"].dtype == "M8[ns]"\n\n result = df.to_records(index=False)\n\n def test_to_records_dt64(self):\n df = DataFrame(\n [["one", "two", "three"], ["four", "five", "six"]],\n index=date_range("2012-01-01", "2012-01-02"),\n )\n\n expected = df.index.values[0]\n result = df.to_records()["index"][0]\n assert expected == result\n\n def test_to_records_dt64tz_column(self):\n # GH#32535 dont less tz in to_records\n df = DataFrame({"A": date_range("2012-01-01", "2012-01-02", tz="US/Eastern")})\n\n result = df.to_records()\n\n assert result.dtype["A"] == object\n val = result[0][1]\n assert isinstance(val, Timestamp)\n assert val == df.loc[0, "A"]\n\n def test_to_records_with_multindex(self):\n # GH#3189\n index = [\n ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n data = np.zeros((8, 4))\n df = DataFrame(data, index=index)\n r = df.to_records(index=True)["level_0"]\n assert "bar" in r\n assert "one" not in r\n\n def test_to_records_with_Mapping_type(self):\n abc.Mapping.register(email.message.Message)\n\n headers = Parser().parsestr(\n "From: <user@example.com>\n"\n "To: <someone_else@example.com>\n"\n "Subject: Test message\n"\n "\n"\n "Body would go here\n"\n )\n\n frame = DataFrame.from_records([headers])\n all(x in frame for x in ["Type", "Subject", "From"])\n\n def test_to_records_floats(self):\n df = DataFrame(np.random.default_rng(2).random((10, 10)))\n df.to_records()\n\n def test_to_records_index_name(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)))\n df.index.name = "X"\n rs = df.to_records()\n assert "X" in rs.dtype.fields\n\n df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)))\n rs = df.to_records()\n assert "index" in rs.dtype.fields\n\n df.index = MultiIndex.from_tuples([("a", "x"), ("a", "y"), ("b", "z")])\n df.index.names = ["A", None]\n result = df.to_records()\n expected = np.rec.fromarrays(\n [np.array(["a", "a", "b"]), np.array(["x", "y", "z"])]\n + [np.asarray(df.iloc[:, i]) for i in range(3)],\n dtype={\n "names": ["A", "level_1", "0", "1", "2"],\n "formats": [\n "O",\n "O",\n f"{tm.ENDIAN}f8",\n f"{tm.ENDIAN}f8",\n f"{tm.ENDIAN}f8",\n ],\n },\n )\n tm.assert_numpy_array_equal(result, expected)\n\n def test_to_records_with_unicode_index(self):\n # GH#13172\n # unicode_literals conflict with to_records\n result = DataFrame([{"a": "x", "b": "y"}]).set_index("a").to_records()\n expected = np.rec.array([("x", "y")], dtype=[("a", "O"), ("b", "O")])\n tm.assert_almost_equal(result, expected)\n\n def test_to_records_index_dtype(self):\n # GH 47263: consistent data types for Index and MultiIndex\n df = DataFrame(\n {\n 1: date_range("2022-01-01", periods=2),\n 2: date_range("2022-01-01", periods=2),\n 3: date_range("2022-01-01", periods=2),\n }\n )\n\n expected = np.rec.array(\n [\n ("2022-01-01", "2022-01-01", "2022-01-01"),\n ("2022-01-02", "2022-01-02", "2022-01-02"),\n ],\n dtype=[\n ("1", f"{tm.ENDIAN}M8[ns]"),\n ("2", f"{tm.ENDIAN}M8[ns]"),\n ("3", f"{tm.ENDIAN}M8[ns]"),\n ],\n )\n\n result = df.to_records(index=False)\n tm.assert_almost_equal(result, expected)\n\n result = df.set_index(1).to_records(index=True)\n tm.assert_almost_equal(result, expected)\n\n result = df.set_index([1, 2]).to_records(index=True)\n tm.assert_almost_equal(result, expected)\n\n def test_to_records_with_unicode_column_names(self):\n # xref issue: https://github.com/numpy/numpy/issues/2407\n # Issue GH#11879. to_records used to raise an exception when used\n # with column names containing non-ascii characters in Python 2\n result = DataFrame(data={"accented_name_é": [1.0]}).to_records()\n\n # Note that numpy allows for unicode field names but dtypes need\n # to be specified using dictionary instead of list of tuples.\n expected = np.rec.array(\n [(0, 1.0)],\n dtype={"names": ["index", "accented_name_é"], "formats": ["=i8", "=f8"]},\n )\n tm.assert_almost_equal(result, expected)\n\n def test_to_records_with_categorical(self):\n # GH#8626\n\n # dict creation\n df = DataFrame({"A": list("abc")}, dtype="category")\n expected = Series(list("abc"), dtype="category", name="A")\n tm.assert_series_equal(df["A"], expected)\n\n # list-like creation\n df = DataFrame(list("abc"), dtype="category")\n expected = Series(list("abc"), dtype="category", name=0)\n tm.assert_series_equal(df[0], expected)\n\n # to record array\n # this coerces\n result = df.to_records()\n expected = np.rec.array(\n [(0, "a"), (1, "b"), (2, "c")], dtype=[("index", "=i8"), ("0", "O")]\n )\n tm.assert_almost_equal(result, expected)\n\n @pytest.mark.parametrize(\n "kwargs,expected",\n [\n # No dtypes --> default to array dtypes.\n (\n {},\n np.rec.array(\n [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}i8"),\n ("A", f"{tm.ENDIAN}i8"),\n ("B", f"{tm.ENDIAN}f8"),\n ("C", "O"),\n ],\n ),\n ),\n # Should have no effect in this case.\n (\n {"index": True},\n np.rec.array(\n [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}i8"),\n ("A", f"{tm.ENDIAN}i8"),\n ("B", f"{tm.ENDIAN}f8"),\n ("C", "O"),\n ],\n ),\n ),\n # Column dtype applied across the board. Index unaffected.\n (\n {"column_dtypes": f"{tm.ENDIAN}U4"},\n np.rec.array(\n [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}i8"),\n ("A", f"{tm.ENDIAN}U4"),\n ("B", f"{tm.ENDIAN}U4"),\n ("C", f"{tm.ENDIAN}U4"),\n ],\n ),\n ),\n # Index dtype applied across the board. Columns unaffected.\n (\n {"index_dtypes": f"{tm.ENDIAN}U1"},\n np.rec.array(\n [("0", 1, 0.2, "a"), ("1", 2, 1.5, "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}U1"),\n ("A", f"{tm.ENDIAN}i8"),\n ("B", f"{tm.ENDIAN}f8"),\n ("C", "O"),\n ],\n ),\n ),\n # Pass in a type instance.\n (\n {"column_dtypes": str},\n np.rec.array(\n [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}i8"),\n ("A", f"{tm.ENDIAN}U"),\n ("B", f"{tm.ENDIAN}U"),\n ("C", f"{tm.ENDIAN}U"),\n ],\n ),\n ),\n # Pass in a dtype instance.\n (\n {"column_dtypes": np.dtype(np.str_)},\n np.rec.array(\n [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}i8"),\n ("A", f"{tm.ENDIAN}U"),\n ("B", f"{tm.ENDIAN}U"),\n ("C", f"{tm.ENDIAN}U"),\n ],\n ),\n ),\n # Pass in a dictionary (name-only).\n (\n {\n "column_dtypes": {\n "A": np.int8,\n "B": np.float32,\n "C": f"{tm.ENDIAN}U2",\n }\n },\n np.rec.array(\n [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}i8"),\n ("A", "i1"),\n ("B", f"{tm.ENDIAN}f4"),\n ("C", f"{tm.ENDIAN}U2"),\n ],\n ),\n ),\n # Pass in a dictionary (indices-only).\n (\n {"index_dtypes": {0: "int16"}},\n np.rec.array(\n [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],\n dtype=[\n ("index", "i2"),\n ("A", f"{tm.ENDIAN}i8"),\n ("B", f"{tm.ENDIAN}f8"),\n ("C", "O"),\n ],\n ),\n ),\n # Ignore index mappings if index is not True.\n (\n {"index": False, "index_dtypes": f"{tm.ENDIAN}U2"},\n np.rec.array(\n [(1, 0.2, "a"), (2, 1.5, "bc")],\n dtype=[\n ("A", f"{tm.ENDIAN}i8"),\n ("B", f"{tm.ENDIAN}f8"),\n ("C", "O"),\n ],\n ),\n ),\n # Non-existent names / indices in mapping should not error.\n (\n {"index_dtypes": {0: "int16", "not-there": "float32"}},\n np.rec.array(\n [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")],\n dtype=[\n ("index", "i2"),\n ("A", f"{tm.ENDIAN}i8"),\n ("B", f"{tm.ENDIAN}f8"),\n ("C", "O"),\n ],\n ),\n ),\n # Names / indices not in mapping default to array dtype.\n (\n {"column_dtypes": {"A": np.int8, "B": np.float32}},\n np.rec.array(\n [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}i8"),\n ("A", "i1"),\n ("B", f"{tm.ENDIAN}f4"),\n ("C", "O"),\n ],\n ),\n ),\n # Names / indices not in dtype mapping default to array dtype.\n (\n {"column_dtypes": {"A": np.dtype("int8"), "B": np.dtype("float32")}},\n np.rec.array(\n [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}i8"),\n ("A", "i1"),\n ("B", f"{tm.ENDIAN}f4"),\n ("C", "O"),\n ],\n ),\n ),\n # Mixture of everything.\n (\n {\n "column_dtypes": {"A": np.int8, "B": np.float32},\n "index_dtypes": f"{tm.ENDIAN}U2",\n },\n np.rec.array(\n [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}U2"),\n ("A", "i1"),\n ("B", f"{tm.ENDIAN}f4"),\n ("C", "O"),\n ],\n ),\n ),\n # Invalid dype values.\n (\n {"index": False, "column_dtypes": []},\n (ValueError, "Invalid dtype \\[\\] specified for column A"),\n ),\n (\n {"index": False, "column_dtypes": {"A": "int32", "B": 5}},\n (ValueError, "Invalid dtype 5 specified for column B"),\n ),\n # Numpy can't handle EA types, so check error is raised\n (\n {\n "index": False,\n "column_dtypes": {"A": "int32", "B": CategoricalDtype(["a", "b"])},\n },\n (ValueError, "Invalid dtype category specified for column B"),\n ),\n # Check that bad types raise\n (\n {"index": False, "column_dtypes": {"A": "int32", "B": "foo"}},\n (TypeError, "data type [\"']foo[\"'] not understood"),\n ),\n ],\n )\n def test_to_records_dtype(self, kwargs, expected):\n # see GH#18146\n df = DataFrame({"A": [1, 2], "B": [0.2, 1.5], "C": ["a", "bc"]})\n\n if not isinstance(expected, np.rec.recarray):\n with pytest.raises(expected[0], match=expected[1]):\n df.to_records(**kwargs)\n else:\n result = df.to_records(**kwargs)\n tm.assert_almost_equal(result, expected)\n\n @pytest.mark.parametrize(\n "df,kwargs,expected",\n [\n # MultiIndex in the index.\n (\n DataFrame(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("abc")\n ).set_index(["a", "b"]),\n {"column_dtypes": "float64", "index_dtypes": {0: "int32", 1: "int8"}},\n np.rec.array(\n [(1, 2, 3.0), (4, 5, 6.0), (7, 8, 9.0)],\n dtype=[\n ("a", f"{tm.ENDIAN}i4"),\n ("b", "i1"),\n ("c", f"{tm.ENDIAN}f8"),\n ],\n ),\n ),\n # MultiIndex in the columns.\n (\n DataFrame(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n columns=MultiIndex.from_tuples(\n [("a", "d"), ("b", "e"), ("c", "f")]\n ),\n ),\n {\n "column_dtypes": {0: f"{tm.ENDIAN}U1", 2: "float32"},\n "index_dtypes": "float32",\n },\n np.rec.array(\n [(0.0, "1", 2, 3.0), (1.0, "4", 5, 6.0), (2.0, "7", 8, 9.0)],\n dtype=[\n ("index", f"{tm.ENDIAN}f4"),\n ("('a', 'd')", f"{tm.ENDIAN}U1"),\n ("('b', 'e')", f"{tm.ENDIAN}i8"),\n ("('c', 'f')", f"{tm.ENDIAN}f4"),\n ],\n ),\n ),\n # MultiIndex in both the columns and index.\n (\n DataFrame(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n columns=MultiIndex.from_tuples(\n [("a", "d"), ("b", "e"), ("c", "f")], names=list("ab")\n ),\n index=MultiIndex.from_tuples(\n [("d", -4), ("d", -5), ("f", -6)], names=list("cd")\n ),\n ),\n {\n "column_dtypes": "float64",\n "index_dtypes": {0: f"{tm.ENDIAN}U2", 1: "int8"},\n },\n np.rec.array(\n [\n ("d", -4, 1.0, 2.0, 3.0),\n ("d", -5, 4.0, 5.0, 6.0),\n ("f", -6, 7, 8, 9.0),\n ],\n dtype=[\n ("c", f"{tm.ENDIAN}U2"),\n ("d", "i1"),\n ("('a', 'd')", f"{tm.ENDIAN}f8"),\n ("('b', 'e')", f"{tm.ENDIAN}f8"),\n ("('c', 'f')", f"{tm.ENDIAN}f8"),\n ],\n ),\n ),\n ],\n )\n def test_to_records_dtype_mi(self, df, kwargs, expected):\n # see GH#18146\n result = df.to_records(**kwargs)\n tm.assert_almost_equal(result, expected)\n\n def test_to_records_dict_like(self):\n # see GH#18146\n class DictLike:\n def __init__(self, **kwargs) -> None:\n self.d = kwargs.copy()\n\n def __getitem__(self, key):\n return self.d.__getitem__(key)\n\n def __contains__(self, key) -> bool:\n return key in self.d\n\n def keys(self):\n return self.d.keys()\n\n df = DataFrame({"A": [1, 2], "B": [0.2, 1.5], "C": ["a", "bc"]})\n\n dtype_mappings = {\n "column_dtypes": DictLike(A=np.int8, B=np.float32),\n "index_dtypes": f"{tm.ENDIAN}U2",\n }\n\n result = df.to_records(**dtype_mappings)\n expected = np.rec.array(\n [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],\n dtype=[\n ("index", f"{tm.ENDIAN}U2"),\n ("A", "i1"),\n ("B", f"{tm.ENDIAN}f4"),\n ("C", "O"),\n ],\n )\n tm.assert_almost_equal(result, expected)\n\n @pytest.mark.parametrize("tz", ["UTC", "GMT", "US/Eastern"])\n def test_to_records_datetimeindex_with_tz(self, tz):\n # GH#13937\n dr = date_range("2016-01-01", periods=10, freq="s", tz=tz)\n\n df = DataFrame({"datetime": dr}, index=dr)\n\n expected = df.to_records()\n result = df.tz_convert("UTC").to_records()\n\n # both converted to UTC, so they are equal\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_to_records.py
test_to_records.py
Python
18,553
0.95
0.057361
0.08159
react-lib
251
2024-02-22T20:14:00.085417
Apache-2.0
true
bdb988513c1545b9d274269dde76f1c3
from datetime import timedelta\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n DatetimeIndex,\n PeriodIndex,\n Series,\n Timedelta,\n date_range,\n period_range,\n to_datetime,\n)\nimport pandas._testing as tm\n\n\ndef _get_with_delta(delta, freq="YE-DEC"):\n return date_range(\n to_datetime("1/1/2001") + delta,\n to_datetime("12/31/2009") + delta,\n freq=freq,\n )\n\n\nclass TestToTimestamp:\n def test_to_timestamp(self, frame_or_series):\n K = 5\n index = period_range(freq="Y", start="1/1/2001", end="12/1/2009")\n obj = DataFrame(\n np.random.default_rng(2).standard_normal((len(index), K)),\n index=index,\n columns=["A", "B", "C", "D", "E"],\n )\n obj["mix"] = "a"\n obj = tm.get_obj(obj, frame_or_series)\n\n exp_index = date_range("1/1/2001", end="12/31/2009", freq="YE-DEC")\n exp_index = exp_index + Timedelta(1, "D") - Timedelta(1, "ns")\n result = obj.to_timestamp("D", "end")\n tm.assert_index_equal(result.index, exp_index)\n tm.assert_numpy_array_equal(result.values, obj.values)\n if frame_or_series is Series:\n assert result.name == "A"\n\n exp_index = date_range("1/1/2001", end="1/1/2009", freq="YS-JAN")\n result = obj.to_timestamp("D", "start")\n tm.assert_index_equal(result.index, exp_index)\n\n result = obj.to_timestamp(how="start")\n tm.assert_index_equal(result.index, exp_index)\n\n delta = timedelta(hours=23)\n result = obj.to_timestamp("H", "end")\n exp_index = _get_with_delta(delta)\n exp_index = exp_index + Timedelta(1, "h") - Timedelta(1, "ns")\n tm.assert_index_equal(result.index, exp_index)\n\n delta = timedelta(hours=23, minutes=59)\n result = obj.to_timestamp("T", "end")\n exp_index = _get_with_delta(delta)\n exp_index = exp_index + Timedelta(1, "m") - Timedelta(1, "ns")\n tm.assert_index_equal(result.index, exp_index)\n\n result = obj.to_timestamp("S", "end")\n delta = timedelta(hours=23, minutes=59, seconds=59)\n exp_index = _get_with_delta(delta)\n exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")\n tm.assert_index_equal(result.index, exp_index)\n\n def test_to_timestamp_columns(self):\n K = 5\n index = period_range(freq="Y", start="1/1/2001", end="12/1/2009")\n df = DataFrame(\n np.random.default_rng(2).standard_normal((len(index), K)),\n index=index,\n columns=["A", "B", "C", "D", "E"],\n )\n df["mix"] = "a"\n\n # columns\n df = df.T\n\n exp_index = date_range("1/1/2001", end="12/31/2009", freq="YE-DEC")\n exp_index = exp_index + Timedelta(1, "D") - Timedelta(1, "ns")\n result = df.to_timestamp("D", "end", axis=1)\n tm.assert_index_equal(result.columns, exp_index)\n tm.assert_numpy_array_equal(result.values, df.values)\n\n exp_index = date_range("1/1/2001", end="1/1/2009", freq="YS-JAN")\n result = df.to_timestamp("D", "start", axis=1)\n tm.assert_index_equal(result.columns, exp_index)\n\n delta = timedelta(hours=23)\n result = df.to_timestamp("H", "end", axis=1)\n exp_index = _get_with_delta(delta)\n exp_index = exp_index + Timedelta(1, "h") - Timedelta(1, "ns")\n tm.assert_index_equal(result.columns, exp_index)\n\n delta = timedelta(hours=23, minutes=59)\n result = df.to_timestamp("min", "end", axis=1)\n exp_index = _get_with_delta(delta)\n exp_index = exp_index + Timedelta(1, "m") - Timedelta(1, "ns")\n tm.assert_index_equal(result.columns, exp_index)\n\n result = df.to_timestamp("S", "end", axis=1)\n delta = timedelta(hours=23, minutes=59, seconds=59)\n exp_index = _get_with_delta(delta)\n exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")\n tm.assert_index_equal(result.columns, exp_index)\n\n result1 = df.to_timestamp("5min", axis=1)\n result2 = df.to_timestamp("min", axis=1)\n expected = date_range("2001-01-01", "2009-01-01", freq="YS")\n assert isinstance(result1.columns, DatetimeIndex)\n assert isinstance(result2.columns, DatetimeIndex)\n tm.assert_numpy_array_equal(result1.columns.asi8, expected.asi8)\n tm.assert_numpy_array_equal(result2.columns.asi8, expected.asi8)\n # PeriodIndex.to_timestamp always use 'infer'\n assert result1.columns.freqstr == "YS-JAN"\n assert result2.columns.freqstr == "YS-JAN"\n\n def test_to_timestamp_invalid_axis(self):\n index = period_range(freq="Y", start="1/1/2001", end="12/1/2009")\n obj = DataFrame(\n np.random.default_rng(2).standard_normal((len(index), 5)), index=index\n )\n\n # invalid axis\n with pytest.raises(ValueError, match="axis"):\n obj.to_timestamp(axis=2)\n\n def test_to_timestamp_hourly(self, frame_or_series):\n index = period_range(freq="h", start="1/1/2001", end="1/2/2001")\n obj = Series(1, index=index, name="foo")\n if frame_or_series is not Series:\n obj = obj.to_frame()\n\n exp_index = date_range("1/1/2001 00:59:59", end="1/2/2001 00:59:59", freq="h")\n result = obj.to_timestamp(how="end")\n exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")\n tm.assert_index_equal(result.index, exp_index)\n if frame_or_series is Series:\n assert result.name == "foo"\n\n def test_to_timestamp_raises(self, index, frame_or_series):\n # GH#33327\n obj = frame_or_series(index=index, dtype=object)\n\n if not isinstance(index, PeriodIndex):\n msg = f"unsupported Type {type(index).__name__}"\n with pytest.raises(TypeError, match=msg):\n obj.to_timestamp()\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_to_timestamp.py
test_to_timestamp.py
Python
5,866
0.95
0.071429
0.03125
react-lib
140
2024-08-23T01:31:12.158359
BSD-3-Clause
true
aa62bb61ec47578a3246acf3c7fcf256
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n DatetimeIndex,\n Index,\n IntervalIndex,\n Series,\n Timestamp,\n bdate_range,\n date_range,\n timedelta_range,\n)\nimport pandas._testing as tm\n\n\nclass TestTranspose:\n def test_transpose_td64_intervals(self):\n # GH#44917\n tdi = timedelta_range("0 Days", "3 Days")\n ii = IntervalIndex.from_breaks(tdi)\n ii = ii.insert(-1, np.nan)\n df = DataFrame(ii)\n\n result = df.T\n expected = DataFrame({i: ii[i : i + 1] for i in range(len(ii))})\n tm.assert_frame_equal(result, expected)\n\n def test_transpose_empty_preserves_datetimeindex(self):\n # GH#41382\n dti = DatetimeIndex([], dtype="M8[ns]")\n df = DataFrame(index=dti)\n\n expected = DatetimeIndex([], dtype="datetime64[ns]", freq=None)\n\n result1 = df.T.sum().index\n result2 = df.sum(axis=1).index\n\n tm.assert_index_equal(result1, expected)\n tm.assert_index_equal(result2, expected)\n\n def test_transpose_tzaware_1col_single_tz(self):\n # GH#26825\n dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")\n\n df = DataFrame(dti)\n assert (df.dtypes == dti.dtype).all()\n res = df.T\n assert (res.dtypes == dti.dtype).all()\n\n def test_transpose_tzaware_2col_single_tz(self):\n # GH#26825\n dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")\n\n df3 = DataFrame({"A": dti, "B": dti})\n assert (df3.dtypes == dti.dtype).all()\n res3 = df3.T\n assert (res3.dtypes == dti.dtype).all()\n\n def test_transpose_tzaware_2col_mixed_tz(self):\n # GH#26825\n dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")\n dti2 = dti.tz_convert("US/Pacific")\n\n df4 = DataFrame({"A": dti, "B": dti2})\n assert (df4.dtypes == [dti.dtype, dti2.dtype]).all()\n assert (df4.T.dtypes == object).all()\n tm.assert_frame_equal(df4.T.T, df4.astype(object))\n\n @pytest.mark.parametrize("tz", [None, "America/New_York"])\n def test_transpose_preserves_dtindex_equality_with_dst(self, tz):\n # GH#19970\n idx = date_range("20161101", "20161130", freq="4h", tz=tz)\n df = DataFrame({"a": range(len(idx)), "b": range(len(idx))}, index=idx)\n result = df.T == df.T\n expected = DataFrame(True, index=list("ab"), columns=idx)\n tm.assert_frame_equal(result, expected)\n\n def test_transpose_object_to_tzaware_mixed_tz(self):\n # GH#26825\n dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")\n dti2 = dti.tz_convert("US/Pacific")\n\n # mixed all-tzaware dtypes\n df2 = DataFrame([dti, dti2])\n assert (df2.dtypes == object).all()\n res2 = df2.T\n assert (res2.dtypes == object).all()\n\n def test_transpose_uint64(self):\n df = DataFrame(\n {"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]},\n dtype=np.uint64,\n )\n result = df.T\n expected = DataFrame(df.values.T)\n expected.index = ["A", "B"]\n tm.assert_frame_equal(result, expected)\n\n def test_transpose_float(self, float_frame):\n frame = float_frame\n dft = frame.T\n for idx, series in dft.items():\n for col, value in series.items():\n if np.isnan(value):\n assert np.isnan(frame[col][idx])\n else:\n assert value == frame[col][idx]\n\n def test_transpose_mixed(self):\n # mixed type\n mixed = DataFrame(\n {\n "A": [0.0, 1.0, 2.0, 3.0, 4.0],\n "B": [0.0, 1.0, 0.0, 1.0, 0.0],\n "C": ["foo1", "foo2", "foo3", "foo4", "foo5"],\n "D": bdate_range("1/1/2009", periods=5),\n },\n index=Index(["a", "b", "c", "d", "e"], dtype=object),\n )\n\n mixed_T = mixed.T\n for col, s in mixed_T.items():\n assert s.dtype == np.object_\n\n @td.skip_array_manager_invalid_test\n def test_transpose_get_view(self, float_frame, using_copy_on_write):\n dft = float_frame.T\n dft.iloc[:, 5:10] = 5\n\n if using_copy_on_write:\n assert (float_frame.values[5:10] != 5).all()\n else:\n assert (float_frame.values[5:10] == 5).all()\n\n @td.skip_array_manager_invalid_test\n def test_transpose_get_view_dt64tzget_view(self, using_copy_on_write):\n dti = date_range("2016-01-01", periods=6, tz="US/Pacific")\n arr = dti._data.reshape(3, 2)\n df = DataFrame(arr)\n assert df._mgr.nblocks == 1\n\n result = df.T\n assert result._mgr.nblocks == 1\n\n rtrip = result._mgr.blocks[0].values\n if using_copy_on_write:\n assert np.shares_memory(df._mgr.blocks[0].values._ndarray, rtrip._ndarray)\n else:\n assert np.shares_memory(arr._ndarray, rtrip._ndarray)\n\n def test_transpose_not_inferring_dt(self):\n # GH#51546\n df = DataFrame(\n {\n "a": [Timestamp("2019-12-31"), Timestamp("2019-12-31")],\n },\n dtype=object,\n )\n result = df.T\n expected = DataFrame(\n [[Timestamp("2019-12-31"), Timestamp("2019-12-31")]],\n columns=[0, 1],\n index=["a"],\n dtype=object,\n )\n tm.assert_frame_equal(result, expected)\n\n def test_transpose_not_inferring_dt_mixed_blocks(self):\n # GH#51546\n df = DataFrame(\n {\n "a": Series(\n [Timestamp("2019-12-31"), Timestamp("2019-12-31")], dtype=object\n ),\n "b": [Timestamp("2019-12-31"), Timestamp("2019-12-31")],\n }\n )\n result = df.T\n expected = DataFrame(\n [\n [Timestamp("2019-12-31"), Timestamp("2019-12-31")],\n [Timestamp("2019-12-31"), Timestamp("2019-12-31")],\n ],\n columns=[0, 1],\n index=["a", "b"],\n dtype=object,\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("dtype1", ["Int64", "Float64"])\n @pytest.mark.parametrize("dtype2", ["Int64", "Float64"])\n def test_transpose(self, dtype1, dtype2):\n # GH#57315 - transpose should have F contiguous blocks\n df = DataFrame(\n {\n "a": pd.array([1, 1, 2], dtype=dtype1),\n "b": pd.array([3, 4, 5], dtype=dtype2),\n }\n )\n result = df.T\n for blk in result._mgr.blocks:\n # When dtypes are unequal, we get NumPy object array\n data = blk.values._data if dtype1 == dtype2 else blk.values\n assert data.flags["F_CONTIGUOUS"]\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_transpose.py
test_transpose.py
Python
6,830
0.95
0.119617
0.072626
node-utils
120
2024-07-31T16:16:44.666141
Apache-2.0
true
1bb018696cfe0301ddcbd729014a5171
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n DatetimeIndex,\n Index,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameTruncate:\n def test_truncate(self, datetime_frame, frame_or_series):\n ts = datetime_frame[::3]\n ts = tm.get_obj(ts, frame_or_series)\n\n start, end = datetime_frame.index[3], datetime_frame.index[6]\n\n start_missing = datetime_frame.index[2]\n end_missing = datetime_frame.index[7]\n\n # neither specified\n truncated = ts.truncate()\n tm.assert_equal(truncated, ts)\n\n # both specified\n expected = ts[1:3]\n\n truncated = ts.truncate(start, end)\n tm.assert_equal(truncated, expected)\n\n truncated = ts.truncate(start_missing, end_missing)\n tm.assert_equal(truncated, expected)\n\n # start specified\n expected = ts[1:]\n\n truncated = ts.truncate(before=start)\n tm.assert_equal(truncated, expected)\n\n truncated = ts.truncate(before=start_missing)\n tm.assert_equal(truncated, expected)\n\n # end specified\n expected = ts[:3]\n\n truncated = ts.truncate(after=end)\n tm.assert_equal(truncated, expected)\n\n truncated = ts.truncate(after=end_missing)\n tm.assert_equal(truncated, expected)\n\n # corner case, empty series/frame returned\n truncated = ts.truncate(after=ts.index[0] - ts.index.freq)\n assert len(truncated) == 0\n\n truncated = ts.truncate(before=ts.index[-1] + ts.index.freq)\n assert len(truncated) == 0\n\n msg = "Truncate: 2000-01-06 00:00:00 must be after 2000-05-16 00:00:00"\n with pytest.raises(ValueError, match=msg):\n ts.truncate(\n before=ts.index[-1] - ts.index.freq, after=ts.index[0] + ts.index.freq\n )\n\n def test_truncate_nonsortedindex(self, frame_or_series):\n # GH#17935\n\n obj = DataFrame({"A": ["a", "b", "c", "d", "e"]}, index=[5, 3, 2, 9, 0])\n obj = tm.get_obj(obj, frame_or_series)\n\n msg = "truncate requires a sorted index"\n with pytest.raises(ValueError, match=msg):\n obj.truncate(before=3, after=9)\n\n def test_sort_values_nonsortedindex(self):\n rng = date_range("2011-01-01", "2012-01-01", freq="W")\n ts = DataFrame(\n {\n "A": np.random.default_rng(2).standard_normal(len(rng)),\n "B": np.random.default_rng(2).standard_normal(len(rng)),\n },\n index=rng,\n )\n\n decreasing = ts.sort_values("A", ascending=False)\n\n msg = "truncate requires a sorted index"\n with pytest.raises(ValueError, match=msg):\n decreasing.truncate(before="2011-11", after="2011-12")\n\n def test_truncate_nonsortedindex_axis1(self):\n # GH#17935\n\n df = DataFrame(\n {\n 3: np.random.default_rng(2).standard_normal(5),\n 20: np.random.default_rng(2).standard_normal(5),\n 2: np.random.default_rng(2).standard_normal(5),\n 0: np.random.default_rng(2).standard_normal(5),\n },\n columns=[3, 20, 2, 0],\n )\n msg = "truncate requires a sorted index"\n with pytest.raises(ValueError, match=msg):\n df.truncate(before=2, after=20, axis=1)\n\n @pytest.mark.parametrize(\n "before, after, indices",\n [(1, 2, [2, 1]), (None, 2, [2, 1, 0]), (1, None, [3, 2, 1])],\n )\n @pytest.mark.parametrize("dtyp", [*tm.ALL_REAL_NUMPY_DTYPES, "datetime64[ns]"])\n def test_truncate_decreasing_index(\n self, before, after, indices, dtyp, frame_or_series\n ):\n # https://github.com/pandas-dev/pandas/issues/33756\n idx = Index([3, 2, 1, 0], dtype=dtyp)\n if isinstance(idx, DatetimeIndex):\n before = pd.Timestamp(before) if before is not None else None\n after = pd.Timestamp(after) if after is not None else None\n indices = [pd.Timestamp(i) for i in indices]\n values = frame_or_series(range(len(idx)), index=idx)\n result = values.truncate(before=before, after=after)\n expected = values.loc[indices]\n tm.assert_equal(result, expected)\n\n def test_truncate_multiindex(self, frame_or_series):\n # GH 34564\n mi = pd.MultiIndex.from_product([[1, 2, 3, 4], ["A", "B"]], names=["L1", "L2"])\n s1 = DataFrame(range(mi.shape[0]), index=mi, columns=["col"])\n s1 = tm.get_obj(s1, frame_or_series)\n\n result = s1.truncate(before=2, after=3)\n\n df = DataFrame.from_dict(\n {"L1": [2, 2, 3, 3], "L2": ["A", "B", "A", "B"], "col": [2, 3, 4, 5]}\n )\n expected = df.set_index(["L1", "L2"])\n expected = tm.get_obj(expected, frame_or_series)\n\n tm.assert_equal(result, expected)\n\n def test_truncate_index_only_one_unique_value(self, frame_or_series):\n # GH 42365\n obj = Series(0, index=date_range("2021-06-30", "2021-06-30")).repeat(5)\n if frame_or_series is DataFrame:\n obj = obj.to_frame(name="a")\n\n truncated = obj.truncate("2021-06-28", "2021-07-01")\n\n tm.assert_equal(truncated, obj)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_truncate.py
test_truncate.py
Python
5,216
0.95
0.084416
0.083333
python-kit
418
2025-04-02T00:14:53.604022
BSD-3-Clause
true
417d3a62d74e916d6c92d247624438df
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestTZConvert:\n def test_tz_convert(self, frame_or_series):\n rng = date_range("1/1/2011", periods=200, freq="D", tz="US/Eastern")\n\n obj = DataFrame({"a": 1}, index=rng)\n obj = tm.get_obj(obj, frame_or_series)\n\n result = obj.tz_convert("Europe/Berlin")\n expected = DataFrame({"a": 1}, rng.tz_convert("Europe/Berlin"))\n expected = tm.get_obj(expected, frame_or_series)\n\n assert result.index.tz.zone == "Europe/Berlin"\n tm.assert_equal(result, expected)\n\n def test_tz_convert_axis1(self):\n rng = date_range("1/1/2011", periods=200, freq="D", tz="US/Eastern")\n\n obj = DataFrame({"a": 1}, index=rng)\n\n obj = obj.T\n result = obj.tz_convert("Europe/Berlin", axis=1)\n assert result.columns.tz.zone == "Europe/Berlin"\n\n expected = DataFrame({"a": 1}, rng.tz_convert("Europe/Berlin"))\n\n tm.assert_equal(result, expected.T)\n\n def test_tz_convert_naive(self, frame_or_series):\n # can't convert tz-naive\n rng = date_range("1/1/2011", periods=200, freq="D")\n ts = Series(1, index=rng)\n ts = frame_or_series(ts)\n\n with pytest.raises(TypeError, match="Cannot convert tz-naive"):\n ts.tz_convert("US/Eastern")\n\n @pytest.mark.parametrize("fn", ["tz_localize", "tz_convert"])\n def test_tz_convert_and_localize(self, fn):\n l0 = date_range("20140701", periods=5, freq="D")\n l1 = date_range("20140701", periods=5, freq="D")\n\n int_idx = Index(range(5))\n\n if fn == "tz_convert":\n l0 = l0.tz_localize("UTC")\n l1 = l1.tz_localize("UTC")\n\n for idx in [l0, l1]:\n l0_expected = getattr(idx, fn)("US/Pacific")\n l1_expected = getattr(idx, fn)("US/Pacific")\n\n df1 = DataFrame(np.ones(5), index=l0)\n df1 = getattr(df1, fn)("US/Pacific")\n tm.assert_index_equal(df1.index, l0_expected)\n\n # MultiIndex\n # GH7846\n df2 = DataFrame(np.ones(5), MultiIndex.from_arrays([l0, l1]))\n\n # freq is not preserved in MultiIndex construction\n l1_expected = l1_expected._with_freq(None)\n l0_expected = l0_expected._with_freq(None)\n l1 = l1._with_freq(None)\n l0 = l0._with_freq(None)\n\n df3 = getattr(df2, fn)("US/Pacific", level=0)\n assert not df3.index.levels[0].equals(l0)\n tm.assert_index_equal(df3.index.levels[0], l0_expected)\n tm.assert_index_equal(df3.index.levels[1], l1)\n assert not df3.index.levels[1].equals(l1_expected)\n\n df3 = getattr(df2, fn)("US/Pacific", level=1)\n tm.assert_index_equal(df3.index.levels[0], l0)\n assert not df3.index.levels[0].equals(l0_expected)\n tm.assert_index_equal(df3.index.levels[1], l1_expected)\n assert not df3.index.levels[1].equals(l1)\n\n df4 = DataFrame(np.ones(5), MultiIndex.from_arrays([int_idx, l0]))\n\n # TODO: untested\n getattr(df4, fn)("US/Pacific", level=1)\n\n tm.assert_index_equal(df3.index.levels[0], l0)\n assert not df3.index.levels[0].equals(l0_expected)\n tm.assert_index_equal(df3.index.levels[1], l1_expected)\n assert not df3.index.levels[1].equals(l1)\n\n # Bad Inputs\n\n # Not DatetimeIndex / PeriodIndex\n with pytest.raises(TypeError, match="DatetimeIndex"):\n df = DataFrame(index=int_idx)\n getattr(df, fn)("US/Pacific")\n\n # Not DatetimeIndex / PeriodIndex\n with pytest.raises(TypeError, match="DatetimeIndex"):\n df = DataFrame(np.ones(5), MultiIndex.from_arrays([int_idx, l0]))\n getattr(df, fn)("US/Pacific", level=0)\n\n # Invalid level\n with pytest.raises(ValueError, match="not valid"):\n df = DataFrame(index=l0)\n getattr(df, fn)("US/Pacific", level=1)\n\n @pytest.mark.parametrize("copy", [True, False])\n def test_tz_convert_copy_inplace_mutate(self, copy, frame_or_series):\n # GH#6326\n obj = frame_or_series(\n np.arange(0, 5),\n index=date_range("20131027", periods=5, freq="h", tz="Europe/Berlin"),\n )\n orig = obj.copy()\n result = obj.tz_convert("UTC", copy=copy)\n expected = frame_or_series(np.arange(0, 5), index=obj.index.tz_convert("UTC"))\n tm.assert_equal(result, expected)\n tm.assert_equal(obj, orig)\n assert result.index is not obj.index\n assert result is not obj\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_tz_convert.py
test_tz_convert.py
Python
4,707
0.95
0.061069
0.09901
awesome-app
449
2024-11-19T07:57:32.038953
BSD-3-Clause
true
1912743513671420150598e312672ff0
from datetime import timezone\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestTZLocalize:\n # See also:\n # test_tz_convert_and_localize in test_tz_convert\n\n def test_tz_localize(self, frame_or_series):\n rng = date_range("1/1/2011", periods=100, freq="h")\n\n obj = DataFrame({"a": 1}, index=rng)\n obj = tm.get_obj(obj, frame_or_series)\n\n result = obj.tz_localize("utc")\n expected = DataFrame({"a": 1}, rng.tz_localize("UTC"))\n expected = tm.get_obj(expected, frame_or_series)\n\n assert result.index.tz is timezone.utc\n tm.assert_equal(result, expected)\n\n def test_tz_localize_axis1(self):\n rng = date_range("1/1/2011", periods=100, freq="h")\n\n df = DataFrame({"a": 1}, index=rng)\n\n df = df.T\n result = df.tz_localize("utc", axis=1)\n assert result.columns.tz is timezone.utc\n\n expected = DataFrame({"a": 1}, rng.tz_localize("UTC"))\n\n tm.assert_frame_equal(result, expected.T)\n\n def test_tz_localize_naive(self, frame_or_series):\n # Can't localize if already tz-aware\n rng = date_range("1/1/2011", periods=100, freq="h", tz="utc")\n ts = Series(1, index=rng)\n ts = frame_or_series(ts)\n\n with pytest.raises(TypeError, match="Already tz-aware"):\n ts.tz_localize("US/Eastern")\n\n @pytest.mark.parametrize("copy", [True, False])\n def test_tz_localize_copy_inplace_mutate(self, copy, frame_or_series):\n # GH#6326\n obj = frame_or_series(\n np.arange(0, 5), index=date_range("20131027", periods=5, freq="1h", tz=None)\n )\n orig = obj.copy()\n result = obj.tz_localize("UTC", copy=copy)\n expected = frame_or_series(\n np.arange(0, 5),\n index=date_range("20131027", periods=5, freq="1h", tz="UTC"),\n )\n tm.assert_equal(result, expected)\n tm.assert_equal(obj, orig)\n assert result.index is not obj.index\n assert result is not obj\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_tz_localize.py
test_tz_localize.py
Python
2,084
0.95
0.088235
0.076923
python-kit
458
2024-09-11T17:42:35.105975
GPL-3.0
true
7ac46c940d9072f7c3e52d6119786d96
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameUpdate:\n def test_update_nan(self):\n # #15593 #15617\n # test 1\n df1 = DataFrame({"A": [1.0, 2, 3], "B": date_range("2000", periods=3)})\n df2 = DataFrame({"A": [None, 2, 3]})\n expected = df1.copy()\n df1.update(df2, overwrite=False)\n\n tm.assert_frame_equal(df1, expected)\n\n # test 2\n df1 = DataFrame({"A": [1.0, None, 3], "B": date_range("2000", periods=3)})\n df2 = DataFrame({"A": [None, 2, 3]})\n expected = DataFrame({"A": [1.0, 2, 3], "B": date_range("2000", periods=3)})\n df1.update(df2, overwrite=False)\n\n tm.assert_frame_equal(df1, expected)\n\n def test_update(self):\n df = DataFrame(\n [[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]]\n )\n\n other = DataFrame([[3.6, 2.0, np.nan], [np.nan, np.nan, 7]], index=[1, 3])\n\n df.update(other)\n\n expected = DataFrame(\n [[1.5, np.nan, 3], [3.6, 2, 3], [1.5, np.nan, 3], [1.5, np.nan, 7.0]]\n )\n tm.assert_frame_equal(df, expected)\n\n def test_update_dtypes(self):\n # gh 3016\n df = DataFrame(\n [[1.0, 2.0, 1, False, True], [4.0, 5.0, 2, True, False]],\n columns=["A", "B", "int", "bool1", "bool2"],\n )\n\n other = DataFrame(\n [[45, 45, 3, True]], index=[0], columns=["A", "B", "int", "bool1"]\n )\n df.update(other)\n\n expected = DataFrame(\n [[45.0, 45.0, 3, True, True], [4.0, 5.0, 2, True, False]],\n columns=["A", "B", "int", "bool1", "bool2"],\n )\n tm.assert_frame_equal(df, expected)\n\n def test_update_nooverwrite(self):\n df = DataFrame(\n [[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]]\n )\n\n other = DataFrame([[3.6, 2.0, np.nan], [np.nan, np.nan, 7]], index=[1, 3])\n\n df.update(other, overwrite=False)\n\n expected = DataFrame(\n [[1.5, np.nan, 3], [1.5, 2, 3], [1.5, np.nan, 3], [1.5, np.nan, 3.0]]\n )\n tm.assert_frame_equal(df, expected)\n\n def test_update_filtered(self):\n df = DataFrame(\n [[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]]\n )\n\n other = DataFrame([[3.6, 2.0, np.nan], [np.nan, np.nan, 7]], index=[1, 3])\n\n df.update(other, filter_func=lambda x: x > 2)\n\n expected = DataFrame(\n [[1.5, np.nan, 3], [1.5, np.nan, 3], [1.5, np.nan, 3], [1.5, np.nan, 7.0]]\n )\n tm.assert_frame_equal(df, expected)\n\n @pytest.mark.parametrize(\n "bad_kwarg, exception, msg",\n [\n # errors must be 'ignore' or 'raise'\n ({"errors": "something"}, ValueError, "The parameter errors must.*"),\n ({"join": "inner"}, NotImplementedError, "Only left join is supported"),\n ],\n )\n def test_update_raise_bad_parameter(self, bad_kwarg, exception, msg):\n df = DataFrame([[1.5, 1, 3.0]])\n with pytest.raises(exception, match=msg):\n df.update(df, **bad_kwarg)\n\n def test_update_raise_on_overlap(self):\n df = DataFrame(\n [[1.5, 1, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]]\n )\n\n other = DataFrame([[2.0, np.nan], [np.nan, 7]], index=[1, 3], columns=[1, 2])\n with pytest.raises(ValueError, match="Data overlaps"):\n df.update(other, errors="raise")\n\n def test_update_from_non_df(self):\n d = {"a": Series([1, 2, 3, 4]), "b": Series([5, 6, 7, 8])}\n df = DataFrame(d)\n\n d["a"] = Series([5, 6, 7, 8])\n df.update(d)\n\n expected = DataFrame(d)\n\n tm.assert_frame_equal(df, expected)\n\n d = {"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]}\n df = DataFrame(d)\n\n d["a"] = [5, 6, 7, 8]\n df.update(d)\n\n expected = DataFrame(d)\n\n tm.assert_frame_equal(df, expected)\n\n def test_update_datetime_tz(self):\n # GH 25807\n result = DataFrame([pd.Timestamp("2019", tz="UTC")])\n with tm.assert_produces_warning(None):\n result.update(result)\n expected = DataFrame([pd.Timestamp("2019", tz="UTC")])\n tm.assert_frame_equal(result, expected)\n\n def test_update_datetime_tz_in_place(self, using_copy_on_write, warn_copy_on_write):\n # https://github.com/pandas-dev/pandas/issues/56227\n result = DataFrame([pd.Timestamp("2019", tz="UTC")])\n orig = result.copy()\n view = result[:]\n with tm.assert_produces_warning(\n FutureWarning if warn_copy_on_write else None, match="Setting a value"\n ):\n result.update(result + pd.Timedelta(days=1))\n expected = DataFrame([pd.Timestamp("2019-01-02", tz="UTC")])\n tm.assert_frame_equal(result, expected)\n if not using_copy_on_write:\n tm.assert_frame_equal(view, expected)\n else:\n tm.assert_frame_equal(view, orig)\n\n def test_update_with_different_dtype(self, using_copy_on_write):\n # GH#3217\n df = DataFrame({"a": [1, 3], "b": [np.nan, 2]})\n df["c"] = np.nan\n with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"):\n df.update({"c": Series(["foo"], index=[0])})\n\n expected = DataFrame(\n {\n "a": [1, 3],\n "b": [np.nan, 2],\n "c": Series(["foo", np.nan]),\n }\n )\n tm.assert_frame_equal(df, expected)\n\n @td.skip_array_manager_invalid_test\n def test_update_modify_view(\n self, using_copy_on_write, warn_copy_on_write, using_infer_string\n ):\n # GH#47188\n df = DataFrame({"A": ["1", np.nan], "B": ["100", np.nan]})\n df2 = DataFrame({"A": ["a", "x"], "B": ["100", "200"]})\n df2_orig = df2.copy()\n result_view = df2[:]\n # TODO(CoW-warn) better warning message\n with tm.assert_cow_warning(warn_copy_on_write):\n df2.update(df)\n expected = DataFrame({"A": ["1", "x"], "B": ["100", "200"]})\n tm.assert_frame_equal(df2, expected)\n if using_copy_on_write or using_infer_string:\n tm.assert_frame_equal(result_view, df2_orig)\n else:\n tm.assert_frame_equal(result_view, expected)\n\n def test_update_dt_column_with_NaT_create_column(self):\n # GH#16713\n df = DataFrame({"A": [1, None], "B": [pd.NaT, pd.to_datetime("2016-01-01")]})\n df2 = DataFrame({"A": [2, 3]})\n df.update(df2, overwrite=False)\n expected = DataFrame(\n {"A": [1.0, 3.0], "B": [pd.NaT, pd.to_datetime("2016-01-01")]}\n )\n tm.assert_frame_equal(df, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_update.py
test_update.py
Python
6,888
0.95
0.083333
0.066667
react-lib
99
2024-07-01T01:14:57.083879
MIT
true
8b8f7fe4d8d89cf81ec031eddc076dea
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n DataFrame,\n NaT,\n Series,\n Timestamp,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameValues:\n @td.skip_array_manager_invalid_test\n def test_values(self, float_frame, using_copy_on_write):\n if using_copy_on_write:\n with pytest.raises(ValueError, match="read-only"):\n float_frame.values[:, 0] = 5.0\n assert (float_frame.values[:, 0] != 5).all()\n else:\n float_frame.values[:, 0] = 5.0\n assert (float_frame.values[:, 0] == 5).all()\n\n def test_more_values(self, float_string_frame):\n values = float_string_frame.values\n assert values.shape[1] == len(float_string_frame.columns)\n\n def test_values_mixed_dtypes(self, float_frame, float_string_frame):\n frame = float_frame\n arr = frame.values\n\n frame_cols = frame.columns\n for i, row in enumerate(arr):\n for j, value in enumerate(row):\n col = frame_cols[j]\n if np.isnan(value):\n assert np.isnan(frame[col].iloc[i])\n else:\n assert value == frame[col].iloc[i]\n\n # mixed type\n arr = float_string_frame[["foo", "A"]].values\n assert arr[0, 0] == "bar"\n\n df = DataFrame({"complex": [1j, 2j, 3j], "real": [1, 2, 3]})\n arr = df.values\n assert arr[0, 0] == 1j\n\n def test_values_duplicates(self):\n df = DataFrame(\n [[1, 2, "a", "b"], [1, 2, "a", "b"]], columns=["one", "one", "two", "two"]\n )\n\n result = df.values\n expected = np.array([[1, 2, "a", "b"], [1, 2, "a", "b"]], dtype=object)\n\n tm.assert_numpy_array_equal(result, expected)\n\n def test_values_with_duplicate_columns(self):\n df = DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=["x", "x"])\n result = df.values\n expected = np.array([[1, 2.5], [3, 4.5]])\n assert (result == expected).all().all()\n\n @pytest.mark.parametrize("constructor", [date_range, period_range])\n def test_values_casts_datetimelike_to_object(self, constructor):\n series = Series(constructor("2000-01-01", periods=10, freq="D"))\n\n expected = series.astype("object")\n\n df = DataFrame(\n {"a": series, "b": np.random.default_rng(2).standard_normal(len(series))}\n )\n\n result = df.values.squeeze()\n assert (result[:, 0] == expected.values).all()\n\n df = DataFrame({"a": series, "b": ["foo"] * len(series)})\n\n result = df.values.squeeze()\n assert (result[:, 0] == expected.values).all()\n\n def test_frame_values_with_tz(self):\n tz = "US/Central"\n df = DataFrame({"A": date_range("2000", periods=4, tz=tz)})\n result = df.values\n expected = np.array(\n [\n [Timestamp("2000-01-01", tz=tz)],\n [Timestamp("2000-01-02", tz=tz)],\n [Timestamp("2000-01-03", tz=tz)],\n [Timestamp("2000-01-04", tz=tz)],\n ]\n )\n tm.assert_numpy_array_equal(result, expected)\n\n # two columns, homogeneous\n\n df["B"] = df["A"]\n result = df.values\n expected = np.concatenate([expected, expected], axis=1)\n tm.assert_numpy_array_equal(result, expected)\n\n # three columns, heterogeneous\n est = "US/Eastern"\n df["C"] = df["A"].dt.tz_convert(est)\n\n new = np.array(\n [\n [Timestamp("2000-01-01T01:00:00", tz=est)],\n [Timestamp("2000-01-02T01:00:00", tz=est)],\n [Timestamp("2000-01-03T01:00:00", tz=est)],\n [Timestamp("2000-01-04T01:00:00", tz=est)],\n ]\n )\n expected = np.concatenate([expected, new], axis=1)\n result = df.values\n tm.assert_numpy_array_equal(result, expected)\n\n def test_interleave_with_tzaware(self, timezone_frame):\n # interleave with object\n result = timezone_frame.assign(D="foo").values\n expected = np.array(\n [\n [\n Timestamp("2013-01-01 00:00:00"),\n Timestamp("2013-01-02 00:00:00"),\n Timestamp("2013-01-03 00:00:00"),\n ],\n [\n Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),\n NaT,\n Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),\n ],\n [\n Timestamp("2013-01-01 00:00:00+0100", tz="CET"),\n NaT,\n Timestamp("2013-01-03 00:00:00+0100", tz="CET"),\n ],\n ["foo", "foo", "foo"],\n ],\n dtype=object,\n ).T\n tm.assert_numpy_array_equal(result, expected)\n\n # interleave with only datetime64[ns]\n result = timezone_frame.values\n expected = np.array(\n [\n [\n Timestamp("2013-01-01 00:00:00"),\n Timestamp("2013-01-02 00:00:00"),\n Timestamp("2013-01-03 00:00:00"),\n ],\n [\n Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),\n NaT,\n Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),\n ],\n [\n Timestamp("2013-01-01 00:00:00+0100", tz="CET"),\n NaT,\n Timestamp("2013-01-03 00:00:00+0100", tz="CET"),\n ],\n ],\n dtype=object,\n ).T\n tm.assert_numpy_array_equal(result, expected)\n\n def test_values_interleave_non_unique_cols(self):\n df = DataFrame(\n [[Timestamp("20130101"), 3.5], [Timestamp("20130102"), 4.5]],\n columns=["x", "x"],\n index=[1, 2],\n )\n\n df_unique = df.copy()\n df_unique.columns = ["x", "y"]\n assert df_unique.values.shape == df.values.shape\n tm.assert_numpy_array_equal(df_unique.values[0], df.values[0])\n tm.assert_numpy_array_equal(df_unique.values[1], df.values[1])\n\n def test_values_numeric_cols(self, float_frame):\n float_frame["foo"] = "bar"\n\n values = float_frame[["A", "B", "C", "D"]].values\n assert values.dtype == np.float64\n\n def test_values_lcd(self, mixed_float_frame, mixed_int_frame):\n # mixed lcd\n values = mixed_float_frame[["A", "B", "C", "D"]].values\n assert values.dtype == np.float64\n\n values = mixed_float_frame[["A", "B", "C"]].values\n assert values.dtype == np.float32\n\n values = mixed_float_frame[["C"]].values\n assert values.dtype == np.float16\n\n # GH#10364\n # B uint64 forces float because there are other signed int types\n values = mixed_int_frame[["A", "B", "C", "D"]].values\n assert values.dtype == np.float64\n\n values = mixed_int_frame[["A", "D"]].values\n assert values.dtype == np.int64\n\n # B uint64 forces float because there are other signed int types\n values = mixed_int_frame[["A", "B", "C"]].values\n assert values.dtype == np.float64\n\n # as B and C are both unsigned, no forcing to float is needed\n values = mixed_int_frame[["B", "C"]].values\n assert values.dtype == np.uint64\n\n values = mixed_int_frame[["A", "C"]].values\n assert values.dtype == np.int32\n\n values = mixed_int_frame[["C", "D"]].values\n assert values.dtype == np.int64\n\n values = mixed_int_frame[["A"]].values\n assert values.dtype == np.int32\n\n values = mixed_int_frame[["C"]].values\n assert values.dtype == np.uint8\n\n\nclass TestPrivateValues:\n @td.skip_array_manager_invalid_test\n def test_private_values_dt64tz(self, using_copy_on_write):\n dta = date_range("2000", periods=4, tz="US/Central")._data.reshape(-1, 1)\n\n df = DataFrame(dta, columns=["A"])\n tm.assert_equal(df._values, dta)\n\n if using_copy_on_write:\n assert not np.shares_memory(df._values._ndarray, dta._ndarray)\n else:\n # we have a view\n assert np.shares_memory(df._values._ndarray, dta._ndarray)\n\n # TimedeltaArray\n tda = dta - dta\n df2 = df - df\n tm.assert_equal(df2._values, tda)\n\n @td.skip_array_manager_invalid_test\n def test_private_values_dt64tz_multicol(self, using_copy_on_write):\n dta = date_range("2000", periods=8, tz="US/Central")._data.reshape(-1, 2)\n\n df = DataFrame(dta, columns=["A", "B"])\n tm.assert_equal(df._values, dta)\n\n if using_copy_on_write:\n assert not np.shares_memory(df._values._ndarray, dta._ndarray)\n else:\n # we have a view\n assert np.shares_memory(df._values._ndarray, dta._ndarray)\n\n # TimedeltaArray\n tda = dta - dta\n df2 = df - df\n tm.assert_equal(df2._values, tda)\n\n def test_private_values_dt64_multiblock(self):\n dta = date_range("2000", periods=8)._data\n\n df = DataFrame({"A": dta[:4]}, copy=False)\n df["B"] = dta[4:]\n\n assert len(df._mgr.arrays) == 2\n\n result = df._values\n expected = dta.reshape(2, 4).T\n tm.assert_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\frame\methods\test_values.py
test_values.py
Python
9,406
0.95
0.078571
0.061947
awesome-app
18
2024-07-08T17:50:24.310033
MIT
true
388a9fd303dbdc4f34e9fe1fabdc8c13