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
import numpy as np\nimport pytest\n\nfrom pandas import (\n NA,\n DataFrame,\n MultiIndex,\n Series,\n array,\n)\nimport pandas._testing as tm\n\n\nclass TestMultiIndexSorted:\n def test_getitem_multilevel_index_tuple_not_sorted(self):\n index_columns = list("abc")\n df = DataFrame(\n [[0, 1, 0, "x"], [0, 0, 1, "y"]], columns=index_columns + ["data"]\n )\n df = df.set_index(index_columns)\n query_index = df.index[:1]\n rs = df.loc[query_index, "data"]\n\n xp_idx = MultiIndex.from_tuples([(0, 1, 0)], names=["a", "b", "c"])\n xp = Series(["x"], index=xp_idx, name="data")\n tm.assert_series_equal(rs, xp)\n\n def test_getitem_slice_not_sorted(self, multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n df = frame.sort_index(level=1).T\n\n # buglet with int typechecking\n result = df.iloc[:, : np.int32(3)]\n expected = df.reindex(columns=df.columns[:3])\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("key", [None, lambda x: x])\n def test_frame_getitem_not_sorted2(self, key):\n # 13431\n df = DataFrame(\n {\n "col1": ["b", "d", "b", "a"],\n "col2": [3, 1, 1, 2],\n "data": ["one", "two", "three", "four"],\n }\n )\n\n df2 = df.set_index(["col1", "col2"])\n df2_original = df2.copy()\n\n df2.index = df2.index.set_levels(["b", "d", "a"], level="col1")\n df2.index = df2.index.set_codes([0, 1, 0, 2], level="col1")\n assert not df2.index.is_monotonic_increasing\n\n assert df2_original.index.equals(df2.index)\n expected = df2.sort_index(key=key)\n assert expected.index.is_monotonic_increasing\n\n result = df2.sort_index(level=0, key=key)\n assert result.index.is_monotonic_increasing\n tm.assert_frame_equal(result, expected)\n\n def test_sort_values_key(self):\n arrays = [\n ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n tuples = zip(*arrays)\n index = MultiIndex.from_tuples(tuples)\n index = index.sort_values( # sort by third letter\n key=lambda x: x.map(lambda entry: entry[2])\n )\n result = DataFrame(range(8), index=index)\n\n arrays = [\n ["foo", "foo", "bar", "bar", "qux", "qux", "baz", "baz"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n tuples = zip(*arrays)\n index = MultiIndex.from_tuples(tuples)\n expected = DataFrame(range(8), index=index)\n\n tm.assert_frame_equal(result, expected)\n\n def test_argsort_with_na(self):\n # GH48495\n arrays = [\n array([2, NA, 1], dtype="Int64"),\n array([1, 2, 3], dtype="Int64"),\n ]\n index = MultiIndex.from_arrays(arrays)\n result = index.argsort()\n expected = np.array([2, 0, 1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_sort_values_with_na(self):\n # GH48495\n arrays = [\n array([2, NA, 1], dtype="Int64"),\n array([1, 2, 3], dtype="Int64"),\n ]\n index = MultiIndex.from_arrays(arrays)\n index = index.sort_values()\n result = DataFrame(range(3), index=index)\n\n arrays = [\n array([1, 2, NA], dtype="Int64"),\n array([3, 1, 2], dtype="Int64"),\n ]\n index = MultiIndex.from_arrays(arrays)\n expected = DataFrame(range(3), index=index)\n\n tm.assert_frame_equal(result, expected)\n\n def test_frame_getitem_not_sorted(self, multiindex_dataframe_random_data):\n frame = multiindex_dataframe_random_data\n df = frame.T\n df["foo", "four"] = "foo"\n\n arrays = [np.array(x) for x in zip(*df.columns.values)]\n\n result = df["foo"]\n result2 = df.loc[:, "foo"]\n expected = df.reindex(columns=df.columns[arrays[0] == "foo"])\n expected.columns = expected.columns.droplevel(0)\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(result2, expected)\n\n df = df.T\n result = df.xs("foo")\n result2 = df.loc["foo"]\n expected = df.reindex(df.index[arrays[0] == "foo"])\n expected.index = expected.index.droplevel(0)\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(result2, expected)\n\n def test_series_getitem_not_sorted(self):\n arrays = [\n ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n tuples = zip(*arrays)\n index = MultiIndex.from_tuples(tuples)\n s = Series(np.random.default_rng(2).standard_normal(8), index=index)\n\n arrays = [np.array(x) for x in zip(*index.values)]\n\n result = s["qux"]\n result2 = s.loc["qux"]\n expected = s[arrays[0] == "qux"]\n expected.index = expected.index.droplevel(0)\n tm.assert_series_equal(result, expected)\n tm.assert_series_equal(result2, expected)\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\test_sorted.py
test_sorted.py
Python
5,192
0.95
0.071895
0.03125
vue-tools
635
2024-12-29T01:48:18.683610
MIT
true
073340ff2487dc54e822d0c037d72a92
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_chaining_and_caching.cpython-313.pyc
test_chaining_and_caching.cpython-313.pyc
Other
4,545
0.8
0
0
node-utils
58
2024-04-18T02:35:12.775485
BSD-3-Clause
true
f87b750ae27f4836e8530cdc5420051f
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_datetime.cpython-313.pyc
test_datetime.cpython-313.pyc
Other
1,986
0.8
0
0.074074
react-lib
218
2025-01-12T14:21:13.189541
Apache-2.0
true
fcbba297587ab14c0b6ae53549a8b49a
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_getitem.cpython-313.pyc
test_getitem.cpython-313.pyc
Other
18,120
0.8
0.012346
0.018987
awesome-app
927
2024-08-25T17:59:29.380980
GPL-3.0
true
acd583afd0badff402206f4006995908
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_iloc.cpython-313.pyc
test_iloc.cpython-313.pyc
Other
8,412
0.95
0.01087
0.011494
awesome-app
27
2024-03-03T06:54:37.426319
BSD-3-Clause
true
9ad8407fb706ba1f035a8b08023b82fe
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_indexing_slow.cpython-313.pyc
test_indexing_slow.cpython-313.pyc
Other
6,454
0.8
0
0.016393
python-kit
800
2024-08-05T04:05:55.001584
MIT
true
be57cc4d73586b38d4c7f2c84090fd0c
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_loc.cpython-313.pyc
test_loc.cpython-313.pyc
Other
52,776
0.95
0
0.023077
node-utils
457
2024-02-18T01:39:51.073394
BSD-3-Clause
true
fe5c6496d52a08e7c0d6d434ebb10f0d
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_multiindex.cpython-313.pyc
test_multiindex.cpython-313.pyc
Other
13,818
0.8
0
0.055215
python-kit
176
2024-03-03T12:54:48.662023
BSD-3-Clause
true
78265361c04655151ada3b763dc7c7f0
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_partial.cpython-313.pyc
test_partial.cpython-313.pyc
Other
13,387
0.8
0
0
vue-tools
489
2025-03-12T03:19:37.401506
GPL-3.0
true
5830c6bf38159c38c0eba92f66e00e40
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_setitem.cpython-313.pyc
test_setitem.cpython-313.pyc
Other
29,913
0.8
0
0.015789
awesome-app
295
2023-11-15T19:20:36.399990
BSD-3-Clause
true
b5511f0604f2b4472246fe4c84f6c55f
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_slice.cpython-313.pyc
test_slice.cpython-313.pyc
Other
36,720
0.95
0.002179
0.004525
react-lib
58
2025-01-22T18:12:28.701940
GPL-3.0
true
db9627286560425136fe75c6f9f510d8
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\test_sorted.cpython-313.pyc
test_sorted.cpython-313.pyc
Other
8,896
0.8
0
0
awesome-app
432
2025-07-02T05:56:43.698756
GPL-3.0
true
18fdb2ff3300e50ffa4f98a04025c775
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\multiindex\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
207
0.7
0
0
react-lib
527
2024-02-17T05:15:43.473310
GPL-3.0
true
194dc31f7246edacf9e1a28de5d11c14
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\common.cpython-313.pyc
common.cpython-313.pyc
Other
1,579
0.7
0
0
vue-tools
750
2023-09-18T02:40:53.361510
GPL-3.0
true
eee8b71a2bee585b0bf7148b2f43d687
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\conftest.cpython-313.pyc
conftest.cpython-313.pyc
Other
6,918
0.8
0
0
react-lib
157
2024-06-20T23:43:11.458207
Apache-2.0
true
72b48e2ff0f8386bc6cec43e12319dcb
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_at.cpython-313.pyc
test_at.cpython-313.pyc
Other
13,905
0.95
0.005263
0
python-kit
917
2025-06-09T07:49:03.127268
GPL-3.0
true
3a0fbb1889fd59448d86edccf15151d2
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_categorical.cpython-313.pyc
test_categorical.cpython-313.pyc
Other
29,358
0.8
0
0.006289
awesome-app
503
2024-06-30T10:57:21.830616
GPL-3.0
true
4b27622cef9d7d55a6ccaf25fab3b29d
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_chaining_and_caching.cpython-313.pyc
test_chaining_and_caching.cpython-313.pyc
Other
37,334
0.8
0.002545
0.005155
node-utils
628
2025-03-13T03:14:03.269911
Apache-2.0
true
e4ed1932e1e5b87d49d4ff7d54af33cf
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_check_indexer.cpython-313.pyc
test_check_indexer.cpython-313.pyc
Other
5,540
0.8
0
0.016129
node-utils
711
2023-08-16T20:02:06.704883
MIT
true
ae6c8e06deb116095f98cc99d1432cdf
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_coercion.cpython-313.pyc
test_coercion.cpython-313.pyc
Other
46,269
0.8
0.005277
0
awesome-app
199
2024-06-01T08:22:23.832082
Apache-2.0
true
1e7bb0055e9a5d8380a959755b7e9048
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_datetime.cpython-313.pyc
test_datetime.cpython-313.pyc
Other
8,500
0.95
0
0
python-kit
655
2024-10-04T10:29:07.171242
GPL-3.0
true
3ca4450ecf5c5edb9fa422dea7bab688
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_floats.cpython-313.pyc
test_floats.cpython-313.pyc
Other
27,661
0.8
0.00349
0.001776
python-kit
561
2023-11-14T20:56:57.212115
GPL-3.0
true
dae1ce3bff62c4926769051a70ba1e59
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_iat.cpython-313.pyc
test_iat.cpython-313.pyc
Other
2,775
0.8
0
0
react-lib
676
2025-04-11T16:19:56.635934
Apache-2.0
true
6421860c4483a62b976f571c62d88049
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_iloc.cpython-313.pyc
test_iloc.cpython-313.pyc
Other
82,825
0.75
0.006203
0.0025
node-utils
84
2024-02-09T03:40:33.993373
BSD-3-Clause
true
e01c2e861b732b3d310480f00eccbd59
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_indexers.cpython-313.pyc
test_indexers.cpython-313.pyc
Other
3,787
0.8
0
0.028571
python-kit
267
2024-09-10T04:23:19.646260
MIT
true
890694f76066588244610da09f4b01ee
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_indexing.cpython-313.pyc
test_indexing.cpython-313.pyc
Other
58,695
0.6
0.001761
0.010676
awesome-app
217
2025-05-28T05:54:11.499518
BSD-3-Clause
true
31df30fc96f324b4832c3c12f8ee907d
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_na_indexing.cpython-313.pyc
test_na_indexing.cpython-313.pyc
Other
3,536
0.8
0
0.058824
react-lib
877
2024-03-21T00:03:07.233205
BSD-3-Clause
true
af0736b338ac3ac9afb1183eda0a8c61
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_partial.cpython-313.pyc
test_partial.cpython-313.pyc
Other
36,704
0.8
0.004211
0.019272
react-lib
82
2024-11-07T11:10:13.109498
Apache-2.0
true
5745aa15a0ba2b4e9f8ffc116c2a2eea
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\test_scalar.cpython-313.pyc
test_scalar.cpython-313.pyc
Other
17,143
0.8
0.017964
0
awesome-app
578
2025-05-12T05:17:02.064206
MIT
true
21adcf3411f5d5bf618a976611dda900
\n\n
.venv\Lib\site-packages\pandas\tests\indexing\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
196
0.7
0
0
node-utils
812
2024-05-27T14:59:47.906474
Apache-2.0
true
3b01055f69b94d4756bf42532fb7147b
from datetime import (\n datetime,\n timezone,\n)\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import iNaT\nfrom pandas.compat import (\n is_ci_environment,\n is_platform_windows,\n)\nfrom pandas.compat.numpy import np_version_lt1p23\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.interchange.column import PandasColumn\nfrom pandas.core.interchange.dataframe_protocol import (\n ColumnNullType,\n DtypeKind,\n)\nfrom pandas.core.interchange.from_dataframe import from_dataframe\nfrom pandas.core.interchange.utils import ArrowCTypes\n\n\n@pytest.fixture\ndef data_categorical():\n return {\n "ordered": pd.Categorical(list("testdata") * 30, ordered=True),\n "unordered": pd.Categorical(list("testdata") * 30, ordered=False),\n }\n\n\n@pytest.fixture\ndef string_data():\n return {\n "separator data": [\n "abC|DeF,Hik",\n "234,3245.67",\n "gSaf,qWer|Gre",\n "asd3,4sad|",\n np.nan,\n ]\n }\n\n\n@pytest.mark.parametrize("data", [("ordered", True), ("unordered", False)])\ndef test_categorical_dtype(data, data_categorical):\n df = pd.DataFrame({"A": (data_categorical[data[0]])})\n\n col = df.__dataframe__().get_column_by_name("A")\n assert col.dtype[0] == DtypeKind.CATEGORICAL\n assert col.null_count == 0\n assert col.describe_null == (ColumnNullType.USE_SENTINEL, -1)\n assert col.num_chunks() == 1\n desc_cat = col.describe_categorical\n assert desc_cat["is_ordered"] == data[1]\n assert desc_cat["is_dictionary"] is True\n assert isinstance(desc_cat["categories"], PandasColumn)\n tm.assert_series_equal(\n desc_cat["categories"]._col, pd.Series(["a", "d", "e", "s", "t"])\n )\n\n tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))\n\n\ndef test_categorical_pyarrow():\n # GH 49889\n pa = pytest.importorskip("pyarrow", "11.0.0")\n\n arr = ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", "Sun"]\n table = pa.table({"weekday": pa.array(arr).dictionary_encode()})\n exchange_df = table.__dataframe__()\n result = from_dataframe(exchange_df)\n weekday = pd.Categorical(\n arr, categories=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]\n )\n expected = pd.DataFrame({"weekday": weekday})\n tm.assert_frame_equal(result, expected)\n\n\ndef test_empty_categorical_pyarrow():\n # https://github.com/pandas-dev/pandas/issues/53077\n pa = pytest.importorskip("pyarrow", "11.0.0")\n\n arr = [None]\n table = pa.table({"arr": pa.array(arr, "float64").dictionary_encode()})\n exchange_df = table.__dataframe__()\n result = pd.api.interchange.from_dataframe(exchange_df)\n expected = pd.DataFrame({"arr": pd.Categorical([np.nan])})\n tm.assert_frame_equal(result, expected)\n\n\ndef test_large_string_pyarrow():\n # GH 52795\n pa = pytest.importorskip("pyarrow", "11.0.0")\n\n arr = ["Mon", "Tue"]\n table = pa.table({"weekday": pa.array(arr, "large_string")})\n exchange_df = table.__dataframe__()\n result = from_dataframe(exchange_df)\n expected = pd.DataFrame({"weekday": ["Mon", "Tue"]})\n tm.assert_frame_equal(result, expected)\n\n # check round-trip\n assert pa.Table.equals(pa.interchange.from_dataframe(result), table)\n\n\n@pytest.mark.parametrize(\n ("offset", "length", "expected_values"),\n [\n (0, None, [3.3, float("nan"), 2.1]),\n (1, None, [float("nan"), 2.1]),\n (2, None, [2.1]),\n (0, 2, [3.3, float("nan")]),\n (0, 1, [3.3]),\n (1, 1, [float("nan")]),\n ],\n)\ndef test_bitmasks_pyarrow(offset, length, expected_values):\n # GH 52795\n pa = pytest.importorskip("pyarrow", "11.0.0")\n\n arr = [3.3, None, 2.1]\n table = pa.table({"arr": arr}).slice(offset, length)\n exchange_df = table.__dataframe__()\n result = from_dataframe(exchange_df)\n expected = pd.DataFrame({"arr": expected_values})\n tm.assert_frame_equal(result, expected)\n\n # check round-trip\n assert pa.Table.equals(pa.interchange.from_dataframe(result), table)\n\n\n@pytest.mark.parametrize(\n "data",\n [\n lambda: np.random.default_rng(2).integers(-100, 100),\n lambda: np.random.default_rng(2).integers(1, 100),\n lambda: np.random.default_rng(2).random(),\n lambda: np.random.default_rng(2).choice([True, False]),\n lambda: datetime(\n year=np.random.default_rng(2).integers(1900, 2100),\n month=np.random.default_rng(2).integers(1, 12),\n day=np.random.default_rng(2).integers(1, 20),\n ),\n ],\n)\ndef test_dataframe(data):\n NCOLS, NROWS = 10, 20\n data = {\n f"col{int((i - NCOLS / 2) % NCOLS + 1)}": [data() for _ in range(NROWS)]\n for i in range(NCOLS)\n }\n df = pd.DataFrame(data)\n\n df2 = df.__dataframe__()\n\n assert df2.num_columns() == NCOLS\n assert df2.num_rows() == NROWS\n\n assert list(df2.column_names()) == list(data.keys())\n\n indices = (0, 2)\n names = tuple(list(data.keys())[idx] for idx in indices)\n\n result = from_dataframe(df2.select_columns(indices))\n expected = from_dataframe(df2.select_columns_by_name(names))\n tm.assert_frame_equal(result, expected)\n\n assert isinstance(result.attrs["_INTERCHANGE_PROTOCOL_BUFFERS"], list)\n assert isinstance(expected.attrs["_INTERCHANGE_PROTOCOL_BUFFERS"], list)\n\n\ndef test_missing_from_masked():\n df = pd.DataFrame(\n {\n "x": np.array([1.0, 2.0, 3.0, 4.0, 0.0]),\n "y": np.array([1.5, 2.5, 3.5, 4.5, 0]),\n "z": np.array([1.0, 0.0, 1.0, 1.0, 1.0]),\n }\n )\n\n rng = np.random.default_rng(2)\n dict_null = {col: rng.integers(low=0, high=len(df)) for col in df.columns}\n for col, num_nulls in dict_null.items():\n null_idx = df.index[\n rng.choice(np.arange(len(df)), size=num_nulls, replace=False)\n ]\n df.loc[null_idx, col] = None\n\n df2 = df.__dataframe__()\n\n assert df2.get_column_by_name("x").null_count == dict_null["x"]\n assert df2.get_column_by_name("y").null_count == dict_null["y"]\n assert df2.get_column_by_name("z").null_count == dict_null["z"]\n\n\n@pytest.mark.parametrize(\n "data",\n [\n {"x": [1.5, 2.5, 3.5], "y": [9.2, 10.5, 11.8]},\n {"x": [1, 2, 0], "y": [9.2, 10.5, 11.8]},\n {\n "x": np.array([True, True, False]),\n "y": np.array([1, 2, 0]),\n "z": np.array([9.2, 10.5, 11.8]),\n },\n ],\n)\ndef test_mixed_data(data):\n df = pd.DataFrame(data)\n df2 = df.__dataframe__()\n\n for col_name in df.columns:\n assert df2.get_column_by_name(col_name).null_count == 0\n\n\ndef test_mixed_missing():\n df = pd.DataFrame(\n {\n "x": np.array([True, None, False, None, True]),\n "y": np.array([None, 2, None, 1, 2]),\n "z": np.array([9.2, 10.5, None, 11.8, None]),\n }\n )\n\n df2 = df.__dataframe__()\n\n for col_name in df.columns:\n assert df2.get_column_by_name(col_name).null_count == 2\n\n\ndef test_string(string_data):\n test_str_data = string_data["separator data"] + [""]\n df = pd.DataFrame({"A": test_str_data})\n col = df.__dataframe__().get_column_by_name("A")\n\n assert col.size() == 6\n assert col.null_count == 1\n assert col.dtype[0] == DtypeKind.STRING\n assert col.describe_null == (ColumnNullType.USE_BYTEMASK, 0)\n\n df_sliced = df[1:]\n col = df_sliced.__dataframe__().get_column_by_name("A")\n assert col.size() == 5\n assert col.null_count == 1\n assert col.dtype[0] == DtypeKind.STRING\n assert col.describe_null == (ColumnNullType.USE_BYTEMASK, 0)\n\n\ndef test_nonstring_object():\n df = pd.DataFrame({"A": ["a", 10, 1.0, ()]})\n col = df.__dataframe__().get_column_by_name("A")\n with pytest.raises(NotImplementedError, match="not supported yet"):\n col.dtype\n\n\ndef test_datetime():\n df = pd.DataFrame({"A": [pd.Timestamp("2022-01-01"), pd.NaT]})\n col = df.__dataframe__().get_column_by_name("A")\n\n assert col.size() == 2\n assert col.null_count == 1\n assert col.dtype[0] == DtypeKind.DATETIME\n assert col.describe_null == (ColumnNullType.USE_SENTINEL, iNaT)\n\n tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))\n\n\n@pytest.mark.skipif(np_version_lt1p23, reason="Numpy > 1.23 required")\ndef test_categorical_to_numpy_dlpack():\n # https://github.com/pandas-dev/pandas/issues/48393\n df = pd.DataFrame({"A": pd.Categorical(["a", "b", "a"])})\n col = df.__dataframe__().get_column_by_name("A")\n result = np.from_dlpack(col.get_buffers()["data"][0])\n expected = np.array([0, 1, 0], dtype="int8")\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("data", [{}, {"a": []}])\ndef test_empty_pyarrow(data):\n # GH 53155\n pytest.importorskip("pyarrow", "11.0.0")\n from pyarrow.interchange import from_dataframe as pa_from_dataframe\n\n expected = pd.DataFrame(data)\n arrow_df = pa_from_dataframe(expected)\n result = from_dataframe(arrow_df)\n tm.assert_frame_equal(result, expected, check_column_type=False)\n\n\ndef test_multi_chunk_pyarrow() -> None:\n pa = pytest.importorskip("pyarrow", "11.0.0")\n n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]])\n names = ["n_legs"]\n table = pa.table([n_legs], names=names)\n with pytest.raises(\n RuntimeError,\n match="Cannot do zero copy conversion into multi-column DataFrame block",\n ):\n pd.api.interchange.from_dataframe(table, allow_copy=False)\n\n\ndef test_multi_chunk_column() -> None:\n pytest.importorskip("pyarrow", "11.0.0")\n ser = pd.Series([1, 2, None], dtype="Int64[pyarrow]")\n df = pd.concat([ser, ser], ignore_index=True).to_frame("a")\n df_orig = df.copy()\n with pytest.raises(\n RuntimeError, match="Found multi-chunk pyarrow array, but `allow_copy` is False"\n ):\n pd.api.interchange.from_dataframe(df.__dataframe__(allow_copy=False))\n result = pd.api.interchange.from_dataframe(df.__dataframe__(allow_copy=True))\n # Interchange protocol defaults to creating numpy-backed columns, so currently this\n # is 'float64'.\n expected = pd.DataFrame({"a": [1.0, 2.0, None, 1.0, 2.0, None]}, dtype="float64")\n tm.assert_frame_equal(result, expected)\n\n # Check that the rechunking we did didn't modify the original DataFrame.\n tm.assert_frame_equal(df, df_orig)\n assert len(df["a"].array._pa_array.chunks) == 2\n assert len(df_orig["a"].array._pa_array.chunks) == 2\n\n\ndef test_timestamp_ns_pyarrow():\n # GH 56712\n pytest.importorskip("pyarrow", "11.0.0")\n timestamp_args = {\n "year": 2000,\n "month": 1,\n "day": 1,\n "hour": 1,\n "minute": 1,\n "second": 1,\n }\n df = pd.Series(\n [datetime(**timestamp_args)],\n dtype="timestamp[ns][pyarrow]",\n name="col0",\n ).to_frame()\n\n dfi = df.__dataframe__()\n result = pd.api.interchange.from_dataframe(dfi)["col0"].item()\n\n expected = pd.Timestamp(**timestamp_args)\n assert result == expected\n\n\n@pytest.mark.parametrize("tz", ["UTC", "US/Pacific"])\n@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])\ndef test_datetimetzdtype(tz, unit):\n # GH 54239\n tz_data = (\n pd.date_range("2018-01-01", periods=5, freq="D").tz_localize(tz).as_unit(unit)\n )\n df = pd.DataFrame({"ts_tz": tz_data})\n tm.assert_frame_equal(df, from_dataframe(df.__dataframe__()))\n\n\ndef test_interchange_from_non_pandas_tz_aware(request):\n # GH 54239, 54287\n pa = pytest.importorskip("pyarrow", "11.0.0")\n import pyarrow.compute as pc\n\n if is_platform_windows() and is_ci_environment():\n mark = pytest.mark.xfail(\n raises=pa.ArrowInvalid,\n reason=(\n "TODO: Set ARROW_TIMEZONE_DATABASE environment variable "\n "on CI to path to the tzdata for pyarrow."\n ),\n )\n request.applymarker(mark)\n\n arr = pa.array([datetime(2020, 1, 1), None, datetime(2020, 1, 2)])\n arr = pc.assume_timezone(arr, "Asia/Kathmandu")\n table = pa.table({"arr": arr})\n exchange_df = table.__dataframe__()\n result = from_dataframe(exchange_df)\n\n expected = pd.DataFrame(\n ["2020-01-01 00:00:00+05:45", "NaT", "2020-01-02 00:00:00+05:45"],\n columns=["arr"],\n dtype="datetime64[us, Asia/Kathmandu]",\n )\n tm.assert_frame_equal(expected, result)\n\n\ndef test_interchange_from_corrected_buffer_dtypes(monkeypatch) -> None:\n # https://github.com/pandas-dev/pandas/issues/54781\n df = pd.DataFrame({"a": ["foo", "bar"]}).__dataframe__()\n interchange = df.__dataframe__()\n column = interchange.get_column_by_name("a")\n buffers = column.get_buffers()\n buffers_data = buffers["data"]\n buffer_dtype = buffers_data[1]\n buffer_dtype = (\n DtypeKind.UINT,\n 8,\n ArrowCTypes.UINT8,\n buffer_dtype[3],\n )\n buffers["data"] = (buffers_data[0], buffer_dtype)\n column.get_buffers = lambda: buffers\n interchange.get_column_by_name = lambda _: column\n monkeypatch.setattr(df, "__dataframe__", lambda allow_copy: interchange)\n pd.api.interchange.from_dataframe(df)\n\n\ndef test_empty_string_column():\n # https://github.com/pandas-dev/pandas/issues/56703\n df = pd.DataFrame({"a": []}, dtype=str)\n df2 = df.__dataframe__()\n result = pd.api.interchange.from_dataframe(df2)\n tm.assert_frame_equal(df, result)\n\n\ndef test_large_string():\n # GH#56702\n pytest.importorskip("pyarrow")\n df = pd.DataFrame({"a": ["x"]}, dtype="large_string[pyarrow]")\n result = pd.api.interchange.from_dataframe(df.__dataframe__())\n expected = pd.DataFrame({"a": ["x"]}, dtype="str")\n tm.assert_frame_equal(result, expected)\n\n\ndef test_non_str_names():\n # https://github.com/pandas-dev/pandas/issues/56701\n df = pd.Series([1, 2, 3], name=0).to_frame()\n names = df.__dataframe__().column_names()\n assert names == ["0"]\n\n\ndef test_non_str_names_w_duplicates():\n # https://github.com/pandas-dev/pandas/issues/56701\n df = pd.DataFrame({"0": [1, 2, 3], 0: [4, 5, 6]})\n dfi = df.__dataframe__()\n with pytest.raises(\n TypeError,\n match=(\n "Expected a Series, got a DataFrame. This likely happened because you "\n "called __dataframe__ on a DataFrame which, after converting column "\n r"names to string, resulted in duplicated names: Index\(\['0', '0'\], "\n r"dtype='(str|object)'\). Please rename these columns before using the "\n "interchange protocol."\n ),\n ):\n pd.api.interchange.from_dataframe(dfi, allow_copy=False)\n\n\n@pytest.mark.parametrize(\n ("data", "dtype", "expected_dtype"),\n [\n ([1, 2, None], "Int64", "int64"),\n ([1, 2, None], "Int64[pyarrow]", "int64"),\n ([1, 2, None], "Int8", "int8"),\n ([1, 2, None], "Int8[pyarrow]", "int8"),\n (\n [1, 2, None],\n "UInt64",\n "uint64",\n ),\n (\n [1, 2, None],\n "UInt64[pyarrow]",\n "uint64",\n ),\n ([1.0, 2.25, None], "Float32", "float32"),\n ([1.0, 2.25, None], "Float32[pyarrow]", "float32"),\n ([True, False, None], "boolean", "bool"),\n ([True, False, None], "boolean[pyarrow]", "bool"),\n (["much ado", "about", None], pd.StringDtype(na_value=np.nan), "large_string"),\n (["much ado", "about", None], "string[pyarrow]", "large_string"),\n (\n [datetime(2020, 1, 1), datetime(2020, 1, 2), None],\n "timestamp[ns][pyarrow]",\n "timestamp[ns]",\n ),\n (\n [datetime(2020, 1, 1), datetime(2020, 1, 2), None],\n "timestamp[us][pyarrow]",\n "timestamp[us]",\n ),\n (\n [\n datetime(2020, 1, 1, tzinfo=timezone.utc),\n datetime(2020, 1, 2, tzinfo=timezone.utc),\n None,\n ],\n "timestamp[us, Asia/Kathmandu][pyarrow]",\n "timestamp[us, tz=Asia/Kathmandu]",\n ),\n ],\n)\ndef test_pandas_nullable_with_missing_values(\n data: list, dtype: str, expected_dtype: str\n) -> None:\n # https://github.com/pandas-dev/pandas/issues/57643\n # https://github.com/pandas-dev/pandas/issues/57664\n pa = pytest.importorskip("pyarrow", "11.0.0")\n import pyarrow.interchange as pai\n\n if expected_dtype == "timestamp[us, tz=Asia/Kathmandu]":\n expected_dtype = pa.timestamp("us", "Asia/Kathmandu")\n\n df = pd.DataFrame({"a": data}, dtype=dtype)\n result = pai.from_dataframe(df.__dataframe__())["a"]\n assert result.type == expected_dtype\n assert result[0].as_py() == data[0]\n assert result[1].as_py() == data[1]\n assert result[2].as_py() is None\n\n\n@pytest.mark.parametrize(\n ("data", "dtype", "expected_dtype"),\n [\n ([1, 2, 3], "Int64", "int64"),\n ([1, 2, 3], "Int64[pyarrow]", "int64"),\n ([1, 2, 3], "Int8", "int8"),\n ([1, 2, 3], "Int8[pyarrow]", "int8"),\n (\n [1, 2, 3],\n "UInt64",\n "uint64",\n ),\n (\n [1, 2, 3],\n "UInt64[pyarrow]",\n "uint64",\n ),\n ([1.0, 2.25, 5.0], "Float32", "float32"),\n ([1.0, 2.25, 5.0], "Float32[pyarrow]", "float32"),\n ([True, False, False], "boolean", "bool"),\n ([True, False, False], "boolean[pyarrow]", "bool"),\n (\n ["much ado", "about", "nothing"],\n pd.StringDtype(na_value=np.nan),\n "large_string",\n ),\n (["much ado", "about", "nothing"], "string[pyarrow]", "large_string"),\n (\n [datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3)],\n "timestamp[ns][pyarrow]",\n "timestamp[ns]",\n ),\n (\n [datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3)],\n "timestamp[us][pyarrow]",\n "timestamp[us]",\n ),\n (\n [\n datetime(2020, 1, 1, tzinfo=timezone.utc),\n datetime(2020, 1, 2, tzinfo=timezone.utc),\n datetime(2020, 1, 3, tzinfo=timezone.utc),\n ],\n "timestamp[us, Asia/Kathmandu][pyarrow]",\n "timestamp[us, tz=Asia/Kathmandu]",\n ),\n ],\n)\ndef test_pandas_nullable_without_missing_values(\n data: list, dtype: str, expected_dtype: str\n) -> None:\n # https://github.com/pandas-dev/pandas/issues/57643\n pa = pytest.importorskip("pyarrow", "11.0.0")\n import pyarrow.interchange as pai\n\n if expected_dtype == "timestamp[us, tz=Asia/Kathmandu]":\n expected_dtype = pa.timestamp("us", "Asia/Kathmandu")\n\n df = pd.DataFrame({"a": data}, dtype=dtype)\n result = pai.from_dataframe(df.__dataframe__())["a"]\n assert result.type == expected_dtype\n assert result[0].as_py() == data[0]\n assert result[1].as_py() == data[1]\n assert result[2].as_py() == data[2]\n\n\ndef test_string_validity_buffer() -> None:\n # https://github.com/pandas-dev/pandas/issues/57761\n pytest.importorskip("pyarrow", "11.0.0")\n df = pd.DataFrame({"a": ["x"]}, dtype="large_string[pyarrow]")\n result = df.__dataframe__().get_column_by_name("a").get_buffers()["validity"]\n assert result is None\n\n\ndef test_string_validity_buffer_no_missing() -> None:\n # https://github.com/pandas-dev/pandas/issues/57762\n pytest.importorskip("pyarrow", "11.0.0")\n df = pd.DataFrame({"a": ["x", None]}, dtype="large_string[pyarrow]")\n validity = df.__dataframe__().get_column_by_name("a").get_buffers()["validity"]\n assert validity is not None\n result = validity[1]\n expected = (DtypeKind.BOOL, 1, ArrowCTypes.BOOL, "=")\n assert result == expected\n\n\ndef test_empty_dataframe():\n # https://github.com/pandas-dev/pandas/issues/56700\n df = pd.DataFrame({"a": []}, dtype="int8")\n dfi = df.__dataframe__()\n result = pd.api.interchange.from_dataframe(dfi, allow_copy=False)\n expected = pd.DataFrame({"a": []}, dtype="int8")\n tm.assert_frame_equal(result, expected)\n\n\ndef test_from_dataframe_list_dtype():\n pa = pytest.importorskip("pyarrow", "14.0.0")\n data = {"a": [[1, 2], [4, 5, 6]]}\n tbl = pa.table(data)\n result = from_dataframe(tbl)\n expected = pd.DataFrame(data)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\interchange\test_impl.py
test_impl.py
Python
20,214
0.95
0.069805
0.048638
react-lib
266
2024-03-15T05:37:20.595356
BSD-3-Clause
true
4f13470ed848965c79217a6f45c5b41e
"""\nA verbatim copy (vendored) of the spec tests.\nTaken from https://github.com/data-apis/dataframe-api\n"""\nimport ctypes\nimport math\n\nimport pytest\n\nimport pandas as pd\n\n\n@pytest.fixture\ndef df_from_dict():\n def maker(dct, is_categorical=False):\n df = pd.DataFrame(dct)\n return df.astype("category") if is_categorical else df\n\n return maker\n\n\n@pytest.mark.parametrize(\n "test_data",\n [\n {"a": ["foo", "bar"], "b": ["baz", "qux"]},\n {"a": [1.5, 2.5, 3.5], "b": [9.2, 10.5, 11.8]},\n {"A": [1, 2, 3, 4], "B": [1, 2, 3, 4]},\n ],\n ids=["str_data", "float_data", "int_data"],\n)\ndef test_only_one_dtype(test_data, df_from_dict):\n columns = list(test_data.keys())\n df = df_from_dict(test_data)\n dfX = df.__dataframe__()\n\n column_size = len(test_data[columns[0]])\n for column in columns:\n null_count = dfX.get_column_by_name(column).null_count\n assert null_count == 0\n assert isinstance(null_count, int)\n assert dfX.get_column_by_name(column).size() == column_size\n assert dfX.get_column_by_name(column).offset == 0\n\n\ndef test_mixed_dtypes(df_from_dict):\n df = df_from_dict(\n {\n "a": [1, 2, 3], # dtype kind INT = 0\n "b": [3, 4, 5], # dtype kind INT = 0\n "c": [1.5, 2.5, 3.5], # dtype kind FLOAT = 2\n "d": [9, 10, 11], # dtype kind INT = 0\n "e": [True, False, True], # dtype kind BOOLEAN = 20\n "f": ["a", "", "c"], # dtype kind STRING = 21\n }\n )\n dfX = df.__dataframe__()\n # for meanings of dtype[0] see the spec; we cannot import the spec here as this\n # file is expected to be vendored *anywhere*;\n # values for dtype[0] are explained above\n columns = {"a": 0, "b": 0, "c": 2, "d": 0, "e": 20, "f": 21}\n\n for column, kind in columns.items():\n colX = dfX.get_column_by_name(column)\n assert colX.null_count == 0\n assert isinstance(colX.null_count, int)\n assert colX.size() == 3\n assert colX.offset == 0\n\n assert colX.dtype[0] == kind\n\n assert dfX.get_column_by_name("c").dtype[1] == 64\n\n\ndef test_na_float(df_from_dict):\n df = df_from_dict({"a": [1.0, math.nan, 2.0]})\n dfX = df.__dataframe__()\n colX = dfX.get_column_by_name("a")\n assert colX.null_count == 1\n assert isinstance(colX.null_count, int)\n\n\ndef test_noncategorical(df_from_dict):\n df = df_from_dict({"a": [1, 2, 3]})\n dfX = df.__dataframe__()\n colX = dfX.get_column_by_name("a")\n with pytest.raises(TypeError, match=".*categorical.*"):\n colX.describe_categorical\n\n\ndef test_categorical(df_from_dict):\n df = df_from_dict(\n {"weekday": ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", "Sun"]},\n is_categorical=True,\n )\n\n colX = df.__dataframe__().get_column_by_name("weekday")\n categorical = colX.describe_categorical\n assert isinstance(categorical["is_ordered"], bool)\n assert isinstance(categorical["is_dictionary"], bool)\n\n\ndef test_dataframe(df_from_dict):\n df = df_from_dict(\n {"x": [True, True, False], "y": [1, 2, 0], "z": [9.2, 10.5, 11.8]}\n )\n dfX = df.__dataframe__()\n\n assert dfX.num_columns() == 3\n assert dfX.num_rows() == 3\n assert dfX.num_chunks() == 1\n assert list(dfX.column_names()) == ["x", "y", "z"]\n assert list(dfX.select_columns((0, 2)).column_names()) == list(\n dfX.select_columns_by_name(("x", "z")).column_names()\n )\n\n\n@pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])\ndef test_df_get_chunks(size, n_chunks, df_from_dict):\n df = df_from_dict({"x": list(range(size))})\n dfX = df.__dataframe__()\n chunks = list(dfX.get_chunks(n_chunks))\n assert len(chunks) == n_chunks\n assert sum(chunk.num_rows() for chunk in chunks) == size\n\n\n@pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])\ndef test_column_get_chunks(size, n_chunks, df_from_dict):\n df = df_from_dict({"x": list(range(size))})\n dfX = df.__dataframe__()\n chunks = list(dfX.get_column(0).get_chunks(n_chunks))\n assert len(chunks) == n_chunks\n assert sum(chunk.size() for chunk in chunks) == size\n\n\ndef test_get_columns(df_from_dict):\n df = df_from_dict({"a": [0, 1], "b": [2.5, 3.5]})\n dfX = df.__dataframe__()\n for colX in dfX.get_columns():\n assert colX.size() == 2\n assert colX.num_chunks() == 1\n # for meanings of dtype[0] see the spec; we cannot import the spec here as this\n # file is expected to be vendored *anywhere*\n assert dfX.get_column(0).dtype[0] == 0 # INT\n assert dfX.get_column(1).dtype[0] == 2 # FLOAT\n\n\ndef test_buffer(df_from_dict):\n arr = [0, 1, -1]\n df = df_from_dict({"a": arr})\n dfX = df.__dataframe__()\n colX = dfX.get_column(0)\n bufX = colX.get_buffers()\n\n dataBuf, dataDtype = bufX["data"]\n\n assert dataBuf.bufsize > 0\n assert dataBuf.ptr != 0\n device, _ = dataBuf.__dlpack_device__()\n\n # for meanings of dtype[0] see the spec; we cannot import the spec here as this\n # file is expected to be vendored *anywhere*\n assert dataDtype[0] == 0 # INT\n\n if device == 1: # CPU-only as we're going to directly read memory here\n bitwidth = dataDtype[1]\n ctype = {\n 8: ctypes.c_int8,\n 16: ctypes.c_int16,\n 32: ctypes.c_int32,\n 64: ctypes.c_int64,\n }[bitwidth]\n\n for idx, truth in enumerate(arr):\n val = ctype.from_address(dataBuf.ptr + idx * (bitwidth // 8)).value\n assert val == truth, f"Buffer at index {idx} mismatch"\n
.venv\Lib\site-packages\pandas\tests\interchange\test_spec_conformance.py
test_spec_conformance.py
Python
5,593
0.95
0.137143
0.05036
node-utils
113
2023-07-16T13:55:18.730365
Apache-2.0
true
cc654fbc0ac89c972eeebc8ba2ecce69
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas.core.interchange.utils import dtype_to_arrow_c_fmt\n\n# TODO: use ArrowSchema to get reference C-string.\n# At the time, there is no way to access ArrowSchema holding a type format string\n# from python. The only way to access it is to export the structure to a C-pointer,\n# see DataType._export_to_c() method defined in\n# https://github.com/apache/arrow/blob/master/python/pyarrow/types.pxi\n\n\n@pytest.mark.parametrize(\n "pandas_dtype, c_string",\n [\n (np.dtype("bool"), "b"),\n (np.dtype("int8"), "c"),\n (np.dtype("uint8"), "C"),\n (np.dtype("int16"), "s"),\n (np.dtype("uint16"), "S"),\n (np.dtype("int32"), "i"),\n (np.dtype("uint32"), "I"),\n (np.dtype("int64"), "l"),\n (np.dtype("uint64"), "L"),\n (np.dtype("float16"), "e"),\n (np.dtype("float32"), "f"),\n (np.dtype("float64"), "g"),\n (pd.Series(["a"]).dtype, "u"),\n (\n pd.Series([0]).astype("datetime64[ns]").dtype,\n "tsn:",\n ),\n (pd.CategoricalDtype(["a"]), "l"),\n (np.dtype("O"), "u"),\n ],\n)\ndef test_dtype_to_arrow_c_fmt(pandas_dtype, c_string): # PR01\n """Test ``dtype_to_arrow_c_fmt`` utility function."""\n assert dtype_to_arrow_c_fmt(pandas_dtype) == c_string\n\n\n@pytest.mark.parametrize(\n "pa_dtype, args_kwargs, c_string",\n [\n ["null", {}, "n"],\n ["bool_", {}, "b"],\n ["uint8", {}, "C"],\n ["uint16", {}, "S"],\n ["uint32", {}, "I"],\n ["uint64", {}, "L"],\n ["int8", {}, "c"],\n ["int16", {}, "S"],\n ["int32", {}, "i"],\n ["int64", {}, "l"],\n ["float16", {}, "e"],\n ["float32", {}, "f"],\n ["float64", {}, "g"],\n ["string", {}, "u"],\n ["binary", {}, "z"],\n ["time32", ("s",), "tts"],\n ["time32", ("ms",), "ttm"],\n ["time64", ("us",), "ttu"],\n ["time64", ("ns",), "ttn"],\n ["date32", {}, "tdD"],\n ["date64", {}, "tdm"],\n ["timestamp", {"unit": "s"}, "tss:"],\n ["timestamp", {"unit": "ms"}, "tsm:"],\n ["timestamp", {"unit": "us"}, "tsu:"],\n ["timestamp", {"unit": "ns"}, "tsn:"],\n ["timestamp", {"unit": "ns", "tz": "UTC"}, "tsn:UTC"],\n ["duration", ("s",), "tDs"],\n ["duration", ("ms",), "tDm"],\n ["duration", ("us",), "tDu"],\n ["duration", ("ns",), "tDn"],\n ["decimal128", {"precision": 4, "scale": 2}, "d:4,2"],\n ],\n)\ndef test_dtype_to_arrow_c_fmt_arrowdtype(pa_dtype, args_kwargs, c_string):\n # GH 52323\n pa = pytest.importorskip("pyarrow")\n if not args_kwargs:\n pa_type = getattr(pa, pa_dtype)()\n elif isinstance(args_kwargs, tuple):\n pa_type = getattr(pa, pa_dtype)(*args_kwargs)\n else:\n pa_type = getattr(pa, pa_dtype)(**args_kwargs)\n arrow_type = pd.ArrowDtype(pa_type)\n assert dtype_to_arrow_c_fmt(arrow_type) == c_string\n
.venv\Lib\site-packages\pandas\tests\interchange\test_utils.py
test_utils.py
Python
2,965
0.95
0.044944
0.072289
react-lib
687
2025-01-13T19:00:52.747917
Apache-2.0
true
4996e7e8f143ec037acb3555a39b5c8f
\n\n
.venv\Lib\site-packages\pandas\tests\interchange\__pycache__\test_impl.cpython-313.pyc
test_impl.cpython-313.pyc
Other
32,885
0.95
0.002551
0.008596
react-lib
953
2024-12-10T10:46:51.282304
MIT
true
d30d3025a868ebf6318d5314e4bccabb
\n\n
.venv\Lib\site-packages\pandas\tests\interchange\__pycache__\test_spec_conformance.cpython-313.pyc
test_spec_conformance.cpython-313.pyc
Other
9,436
0.8
0
0
node-utils
540
2024-03-15T03:41:56.391873
GPL-3.0
true
b880dfc34323e398d3cb3a9dc0098f0a
\n\n
.venv\Lib\site-packages\pandas\tests\interchange\__pycache__\test_utils.cpython-313.pyc
test_utils.cpython-313.pyc
Other
3,861
0.95
0.022727
0
python-kit
998
2023-11-17T00:55:33.416583
BSD-3-Clause
true
9eb735574a33d5fcda26e94d209c8cc3
\n\n
.venv\Lib\site-packages\pandas\tests\interchange\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
199
0.7
0
0
python-kit
253
2025-02-14T09:10:41.554366
GPL-3.0
true
f14589a1309a3a729dac9431f5f47efb
"""\nTests for the pseudo-public API implemented in internals/api.py and exposed\nin core.internals\n"""\n\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core import internals\nfrom pandas.core.internals import api\n\n\ndef test_internals_api():\n assert internals.make_block is api.make_block\n\n\ndef test_namespace():\n # SUBJECT TO CHANGE\n\n modules = [\n "blocks",\n "concat",\n "managers",\n "construction",\n "array_manager",\n "base",\n "api",\n "ops",\n ]\n expected = [\n "make_block",\n "DataManager",\n "ArrayManager",\n "BlockManager",\n "SingleDataManager",\n "SingleBlockManager",\n "SingleArrayManager",\n "concatenate_managers",\n ]\n\n result = [x for x in dir(internals) if not x.startswith("__")]\n assert set(result) == set(expected + modules)\n\n\n@pytest.mark.parametrize(\n "name",\n [\n "NumericBlock",\n "ObjectBlock",\n "Block",\n "ExtensionBlock",\n "DatetimeTZBlock",\n ],\n)\ndef test_deprecations(name):\n # GH#55139\n msg = f"{name} is deprecated.* Use public APIs instead"\n with tm.assert_produces_warning(DeprecationWarning, match=msg):\n getattr(internals, name)\n\n if name not in ["NumericBlock", "ObjectBlock"]:\n # NumericBlock and ObjectBlock are not in the internals.api namespace\n with tm.assert_produces_warning(DeprecationWarning, match=msg):\n getattr(api, name)\n\n\ndef test_make_block_2d_with_dti():\n # GH#41168\n dti = pd.date_range("2012", periods=3, tz="UTC")\n blk = api.make_block(dti, placement=[0])\n\n assert blk.shape == (1, 3)\n assert blk.values.shape == (1, 3)\n\n\ndef test_create_block_manager_from_blocks_deprecated():\n # GH#33892\n # If they must, downstream packages should get this from internals.api,\n # not internals.\n msg = (\n "create_block_manager_from_blocks is deprecated and will be "\n "removed in a future version. Use public APIs instead"\n )\n with tm.assert_produces_warning(DeprecationWarning, match=msg):\n internals.create_block_manager_from_blocks\n
.venv\Lib\site-packages\pandas\tests\internals\test_api.py
test_api.py
Python
2,166
0.95
0.104651
0.1
react-lib
720
2024-11-20T20:48:43.528344
Apache-2.0
true
1fae637c79dfab278879c6575ce6fe90
from datetime import (\n date,\n datetime,\n)\nimport itertools\nimport re\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.internals import BlockPlacement\nfrom pandas.compat import IS64\nimport pandas.util._test_decorators as td\n\nfrom pandas.core.dtypes.common import is_scalar\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n DatetimeIndex,\n Index,\n IntervalIndex,\n Series,\n Timedelta,\n Timestamp,\n period_range,\n)\nimport pandas._testing as tm\nimport pandas.core.algorithms as algos\nfrom pandas.core.arrays import (\n DatetimeArray,\n SparseArray,\n TimedeltaArray,\n)\nfrom pandas.core.internals import (\n BlockManager,\n SingleBlockManager,\n make_block,\n)\nfrom pandas.core.internals.blocks import (\n ensure_block_shape,\n maybe_coerce_values,\n new_block,\n)\n\n# this file contains BlockManager specific tests\n# TODO(ArrayManager) factor out interleave_dtype tests\npytestmark = td.skip_array_manager_invalid_test\n\n\n@pytest.fixture(params=[new_block, make_block])\ndef block_maker(request):\n """\n Fixture to test both the internal new_block and pseudo-public make_block.\n """\n return request.param\n\n\n@pytest.fixture\ndef mgr():\n return create_mgr(\n "a: f8; b: object; c: f8; d: object; e: f8;"\n "f: bool; g: i8; h: complex; i: datetime-1; j: datetime-2;"\n "k: M8[ns, US/Eastern]; l: M8[ns, CET];"\n )\n\n\ndef assert_block_equal(left, right):\n tm.assert_numpy_array_equal(left.values, right.values)\n assert left.dtype == right.dtype\n assert isinstance(left.mgr_locs, BlockPlacement)\n assert isinstance(right.mgr_locs, BlockPlacement)\n tm.assert_numpy_array_equal(left.mgr_locs.as_array, right.mgr_locs.as_array)\n\n\ndef get_numeric_mat(shape):\n arr = np.arange(shape[0])\n return np.lib.stride_tricks.as_strided(\n x=arr, shape=shape, strides=(arr.itemsize,) + (0,) * (len(shape) - 1)\n ).copy()\n\n\nN = 10\n\n\ndef create_block(typestr, placement, item_shape=None, num_offset=0, maker=new_block):\n """\n Supported typestr:\n\n * float, f8, f4, f2\n * int, i8, i4, i2, i1\n * uint, u8, u4, u2, u1\n * complex, c16, c8\n * bool\n * object, string, O\n * datetime, dt, M8[ns], M8[ns, tz]\n * timedelta, td, m8[ns]\n * sparse (SparseArray with fill_value=0.0)\n * sparse_na (SparseArray with fill_value=np.nan)\n * category, category2\n\n """\n placement = BlockPlacement(placement)\n num_items = len(placement)\n\n if item_shape is None:\n item_shape = (N,)\n\n shape = (num_items,) + item_shape\n\n mat = get_numeric_mat(shape)\n\n if typestr in (\n "float",\n "f8",\n "f4",\n "f2",\n "int",\n "i8",\n "i4",\n "i2",\n "i1",\n "uint",\n "u8",\n "u4",\n "u2",\n "u1",\n ):\n values = mat.astype(typestr) + num_offset\n elif typestr in ("complex", "c16", "c8"):\n values = 1.0j * (mat.astype(typestr) + num_offset)\n elif typestr in ("object", "string", "O"):\n values = np.reshape([f"A{i:d}" for i in mat.ravel() + num_offset], shape)\n elif typestr in ("b", "bool"):\n values = np.ones(shape, dtype=np.bool_)\n elif typestr in ("datetime", "dt", "M8[ns]"):\n values = (mat * 1e9).astype("M8[ns]")\n elif typestr.startswith("M8[ns"):\n # datetime with tz\n m = re.search(r"M8\[ns,\s*(\w+\/?\w*)\]", typestr)\n assert m is not None, f"incompatible typestr -> {typestr}"\n tz = m.groups()[0]\n assert num_items == 1, "must have only 1 num items for a tz-aware"\n values = DatetimeIndex(np.arange(N) * 10**9, tz=tz)._data\n values = ensure_block_shape(values, ndim=len(shape))\n elif typestr in ("timedelta", "td", "m8[ns]"):\n values = (mat * 1).astype("m8[ns]")\n elif typestr in ("category",):\n values = Categorical([1, 1, 2, 2, 3, 3, 3, 3, 4, 4])\n elif typestr in ("category2",):\n values = Categorical(["a", "a", "a", "a", "b", "b", "c", "c", "c", "d"])\n elif typestr in ("sparse", "sparse_na"):\n if shape[-1] != 10:\n # We also are implicitly assuming this in the category cases above\n raise NotImplementedError\n\n assert all(s == 1 for s in shape[:-1])\n if typestr.endswith("_na"):\n fill_value = np.nan\n else:\n fill_value = 0.0\n values = SparseArray(\n [fill_value, fill_value, 1, 2, 3, fill_value, 4, 5, fill_value, 6],\n fill_value=fill_value,\n )\n arr = values.sp_values.view()\n arr += num_offset - 1\n else:\n raise ValueError(f'Unsupported typestr: "{typestr}"')\n\n values = maybe_coerce_values(values)\n return maker(values, placement=placement, ndim=len(shape))\n\n\ndef create_single_mgr(typestr, num_rows=None):\n if num_rows is None:\n num_rows = N\n\n return SingleBlockManager(\n create_block(typestr, placement=slice(0, num_rows), item_shape=()),\n Index(np.arange(num_rows)),\n )\n\n\ndef create_mgr(descr, item_shape=None):\n """\n Construct BlockManager from string description.\n\n String description syntax looks similar to np.matrix initializer. It looks\n like this::\n\n a,b,c: f8; d,e,f: i8\n\n Rules are rather simple:\n\n * see list of supported datatypes in `create_block` method\n * components are semicolon-separated\n * each component is `NAME,NAME,NAME: DTYPE_ID`\n * whitespace around colons & semicolons are removed\n * components with same DTYPE_ID are combined into single block\n * to force multiple blocks with same dtype, use '-SUFFIX'::\n\n 'a:f8-1; b:f8-2; c:f8-foobar'\n\n """\n if item_shape is None:\n item_shape = (N,)\n\n offset = 0\n mgr_items = []\n block_placements = {}\n for d in descr.split(";"):\n d = d.strip()\n if not len(d):\n continue\n names, blockstr = d.partition(":")[::2]\n blockstr = blockstr.strip()\n names = names.strip().split(",")\n\n mgr_items.extend(names)\n placement = list(np.arange(len(names)) + offset)\n try:\n block_placements[blockstr].extend(placement)\n except KeyError:\n block_placements[blockstr] = placement\n offset += len(names)\n\n mgr_items = Index(mgr_items)\n\n blocks = []\n num_offset = 0\n for blockstr, placement in block_placements.items():\n typestr = blockstr.split("-")[0]\n blocks.append(\n create_block(\n typestr, placement, item_shape=item_shape, num_offset=num_offset\n )\n )\n num_offset += len(placement)\n\n sblocks = sorted(blocks, key=lambda b: b.mgr_locs[0])\n return BlockManager(\n tuple(sblocks),\n [mgr_items] + [Index(np.arange(n)) for n in item_shape],\n )\n\n\n@pytest.fixture\ndef fblock():\n return create_block("float", [0, 2, 4])\n\n\nclass TestBlock:\n def test_constructor(self):\n int32block = create_block("i4", [0])\n assert int32block.dtype == np.int32\n\n @pytest.mark.parametrize(\n "typ, data",\n [\n ["float", [0, 2, 4]],\n ["complex", [7]],\n ["object", [1, 3]],\n ["bool", [5]],\n ],\n )\n def test_pickle(self, typ, data):\n blk = create_block(typ, data)\n assert_block_equal(tm.round_trip_pickle(blk), blk)\n\n def test_mgr_locs(self, fblock):\n assert isinstance(fblock.mgr_locs, BlockPlacement)\n tm.assert_numpy_array_equal(\n fblock.mgr_locs.as_array, np.array([0, 2, 4], dtype=np.intp)\n )\n\n def test_attrs(self, fblock):\n assert fblock.shape == fblock.values.shape\n assert fblock.dtype == fblock.values.dtype\n assert len(fblock) == len(fblock.values)\n\n def test_copy(self, fblock):\n cop = fblock.copy()\n assert cop is not fblock\n assert_block_equal(fblock, cop)\n\n def test_delete(self, fblock):\n newb = fblock.copy()\n locs = newb.mgr_locs\n nb = newb.delete(0)[0]\n assert newb.mgr_locs is locs\n\n assert nb is not newb\n\n tm.assert_numpy_array_equal(\n nb.mgr_locs.as_array, np.array([2, 4], dtype=np.intp)\n )\n assert not (newb.values[0] == 1).all()\n assert (nb.values[0] == 1).all()\n\n newb = fblock.copy()\n locs = newb.mgr_locs\n nb = newb.delete(1)\n assert len(nb) == 2\n assert newb.mgr_locs is locs\n\n tm.assert_numpy_array_equal(\n nb[0].mgr_locs.as_array, np.array([0], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n nb[1].mgr_locs.as_array, np.array([4], dtype=np.intp)\n )\n assert not (newb.values[1] == 2).all()\n assert (nb[1].values[0] == 2).all()\n\n newb = fblock.copy()\n nb = newb.delete(2)\n assert len(nb) == 1\n tm.assert_numpy_array_equal(\n nb[0].mgr_locs.as_array, np.array([0, 2], dtype=np.intp)\n )\n assert (nb[0].values[1] == 1).all()\n\n newb = fblock.copy()\n\n with pytest.raises(IndexError, match=None):\n newb.delete(3)\n\n def test_delete_datetimelike(self):\n # dont use np.delete on values, as that will coerce from DTA/TDA to ndarray\n arr = np.arange(20, dtype="i8").reshape(5, 4).view("m8[ns]")\n df = DataFrame(arr)\n blk = df._mgr.blocks[0]\n assert isinstance(blk.values, TimedeltaArray)\n\n nb = blk.delete(1)\n assert len(nb) == 2\n assert isinstance(nb[0].values, TimedeltaArray)\n assert isinstance(nb[1].values, TimedeltaArray)\n\n df = DataFrame(arr.view("M8[ns]"))\n blk = df._mgr.blocks[0]\n assert isinstance(blk.values, DatetimeArray)\n\n nb = blk.delete([1, 3])\n assert len(nb) == 2\n assert isinstance(nb[0].values, DatetimeArray)\n assert isinstance(nb[1].values, DatetimeArray)\n\n def test_split(self):\n # GH#37799\n values = np.random.default_rng(2).standard_normal((3, 4))\n blk = new_block(values, placement=BlockPlacement([3, 1, 6]), ndim=2)\n result = blk._split()\n\n # check that we get views, not copies\n values[:] = -9999\n assert (blk.values == -9999).all()\n\n assert len(result) == 3\n expected = [\n new_block(values[[0]], placement=BlockPlacement([3]), ndim=2),\n new_block(values[[1]], placement=BlockPlacement([1]), ndim=2),\n new_block(values[[2]], placement=BlockPlacement([6]), ndim=2),\n ]\n for res, exp in zip(result, expected):\n assert_block_equal(res, exp)\n\n\nclass TestBlockManager:\n def test_attrs(self):\n mgr = create_mgr("a,b,c: f8-1; d,e,f: f8-2")\n assert mgr.nblocks == 2\n assert len(mgr) == 6\n\n def test_duplicate_ref_loc_failure(self):\n tmp_mgr = create_mgr("a:bool; a: f8")\n\n axes, blocks = tmp_mgr.axes, tmp_mgr.blocks\n\n blocks[0].mgr_locs = BlockPlacement(np.array([0]))\n blocks[1].mgr_locs = BlockPlacement(np.array([0]))\n\n # test trying to create block manager with overlapping ref locs\n\n msg = "Gaps in blk ref_locs"\n\n with pytest.raises(AssertionError, match=msg):\n mgr = BlockManager(blocks, axes)\n mgr._rebuild_blknos_and_blklocs()\n\n blocks[0].mgr_locs = BlockPlacement(np.array([0]))\n blocks[1].mgr_locs = BlockPlacement(np.array([1]))\n mgr = BlockManager(blocks, axes)\n mgr.iget(1)\n\n def test_pickle(self, mgr):\n mgr2 = tm.round_trip_pickle(mgr)\n tm.assert_frame_equal(\n DataFrame._from_mgr(mgr, axes=mgr.axes),\n DataFrame._from_mgr(mgr2, axes=mgr2.axes),\n )\n\n # GH2431\n assert hasattr(mgr2, "_is_consolidated")\n assert hasattr(mgr2, "_known_consolidated")\n\n # reset to False on load\n assert not mgr2._is_consolidated\n assert not mgr2._known_consolidated\n\n @pytest.mark.parametrize("mgr_string", ["a,a,a:f8", "a: f8; a: i8"])\n def test_non_unique_pickle(self, mgr_string):\n mgr = create_mgr(mgr_string)\n mgr2 = tm.round_trip_pickle(mgr)\n tm.assert_frame_equal(\n DataFrame._from_mgr(mgr, axes=mgr.axes),\n DataFrame._from_mgr(mgr2, axes=mgr2.axes),\n )\n\n def test_categorical_block_pickle(self):\n mgr = create_mgr("a: category")\n mgr2 = tm.round_trip_pickle(mgr)\n tm.assert_frame_equal(\n DataFrame._from_mgr(mgr, axes=mgr.axes),\n DataFrame._from_mgr(mgr2, axes=mgr2.axes),\n )\n\n smgr = create_single_mgr("category")\n smgr2 = tm.round_trip_pickle(smgr)\n tm.assert_series_equal(\n Series()._constructor_from_mgr(smgr, axes=smgr.axes),\n Series()._constructor_from_mgr(smgr2, axes=smgr2.axes),\n )\n\n def test_iget(self):\n cols = Index(list("abc"))\n values = np.random.default_rng(2).random((3, 3))\n block = new_block(\n values=values.copy(),\n placement=BlockPlacement(np.arange(3, dtype=np.intp)),\n ndim=values.ndim,\n )\n mgr = BlockManager(blocks=(block,), axes=[cols, Index(np.arange(3))])\n\n tm.assert_almost_equal(mgr.iget(0).internal_values(), values[0])\n tm.assert_almost_equal(mgr.iget(1).internal_values(), values[1])\n tm.assert_almost_equal(mgr.iget(2).internal_values(), values[2])\n\n def test_set(self):\n mgr = create_mgr("a,b,c: int", item_shape=(3,))\n\n mgr.insert(len(mgr.items), "d", np.array(["foo"] * 3))\n mgr.iset(1, np.array(["bar"] * 3))\n tm.assert_numpy_array_equal(mgr.iget(0).internal_values(), np.array([0] * 3))\n tm.assert_numpy_array_equal(\n mgr.iget(1).internal_values(), np.array(["bar"] * 3, dtype=np.object_)\n )\n tm.assert_numpy_array_equal(mgr.iget(2).internal_values(), np.array([2] * 3))\n tm.assert_numpy_array_equal(\n mgr.iget(3).internal_values(), np.array(["foo"] * 3, dtype=np.object_)\n )\n\n def test_set_change_dtype(self, mgr):\n mgr.insert(len(mgr.items), "baz", np.zeros(N, dtype=bool))\n\n mgr.iset(mgr.items.get_loc("baz"), np.repeat("foo", N))\n idx = mgr.items.get_loc("baz")\n assert mgr.iget(idx).dtype == np.object_\n\n mgr2 = mgr.consolidate()\n mgr2.iset(mgr2.items.get_loc("baz"), np.repeat("foo", N))\n idx = mgr2.items.get_loc("baz")\n assert mgr2.iget(idx).dtype == np.object_\n\n mgr2.insert(\n len(mgr2.items),\n "quux",\n np.random.default_rng(2).standard_normal(N).astype(int),\n )\n idx = mgr2.items.get_loc("quux")\n assert mgr2.iget(idx).dtype == np.dtype(int)\n\n mgr2.iset(\n mgr2.items.get_loc("quux"), np.random.default_rng(2).standard_normal(N)\n )\n assert mgr2.iget(idx).dtype == np.float64\n\n def test_copy(self, mgr):\n cp = mgr.copy(deep=False)\n for blk, cp_blk in zip(mgr.blocks, cp.blocks):\n # view assertion\n tm.assert_equal(cp_blk.values, blk.values)\n if isinstance(blk.values, np.ndarray):\n assert cp_blk.values.base is blk.values.base\n else:\n # DatetimeTZBlock has DatetimeIndex values\n assert cp_blk.values._ndarray.base is blk.values._ndarray.base\n\n # copy(deep=True) consolidates, so the block-wise assertions will\n # fail is mgr is not consolidated\n mgr._consolidate_inplace()\n cp = mgr.copy(deep=True)\n for blk, cp_blk in zip(mgr.blocks, cp.blocks):\n bvals = blk.values\n cpvals = cp_blk.values\n\n tm.assert_equal(cpvals, bvals)\n\n if isinstance(cpvals, np.ndarray):\n lbase = cpvals.base\n rbase = bvals.base\n else:\n lbase = cpvals._ndarray.base\n rbase = bvals._ndarray.base\n\n # copy assertion we either have a None for a base or in case of\n # some blocks it is an array (e.g. datetimetz), but was copied\n if isinstance(cpvals, DatetimeArray):\n assert (lbase is None and rbase is None) or (lbase is not rbase)\n elif not isinstance(cpvals, np.ndarray):\n assert lbase is not rbase\n else:\n assert lbase is None and rbase is None\n\n def test_sparse(self):\n mgr = create_mgr("a: sparse-1; b: sparse-2")\n assert mgr.as_array().dtype == np.float64\n\n def test_sparse_mixed(self):\n mgr = create_mgr("a: sparse-1; b: sparse-2; c: f8")\n assert len(mgr.blocks) == 3\n assert isinstance(mgr, BlockManager)\n\n @pytest.mark.parametrize(\n "mgr_string, dtype",\n [("c: f4; d: f2", np.float32), ("c: f4; d: f2; e: f8", np.float64)],\n )\n def test_as_array_float(self, mgr_string, dtype):\n mgr = create_mgr(mgr_string)\n assert mgr.as_array().dtype == dtype\n\n @pytest.mark.parametrize(\n "mgr_string, dtype",\n [\n ("a: bool-1; b: bool-2", np.bool_),\n ("a: i8-1; b: i8-2; c: i4; d: i2; e: u1", np.int64),\n ("c: i4; d: i2; e: u1", np.int32),\n ],\n )\n def test_as_array_int_bool(self, mgr_string, dtype):\n mgr = create_mgr(mgr_string)\n assert mgr.as_array().dtype == dtype\n\n def test_as_array_datetime(self):\n mgr = create_mgr("h: datetime-1; g: datetime-2")\n assert mgr.as_array().dtype == "M8[ns]"\n\n def test_as_array_datetime_tz(self):\n mgr = create_mgr("h: M8[ns, US/Eastern]; g: M8[ns, CET]")\n assert mgr.iget(0).dtype == "datetime64[ns, US/Eastern]"\n assert mgr.iget(1).dtype == "datetime64[ns, CET]"\n assert mgr.as_array().dtype == "object"\n\n @pytest.mark.parametrize("t", ["float16", "float32", "float64", "int32", "int64"])\n def test_astype(self, t):\n # coerce all\n mgr = create_mgr("c: f4; d: f2; e: f8")\n\n t = np.dtype(t)\n tmgr = mgr.astype(t)\n assert tmgr.iget(0).dtype.type == t\n assert tmgr.iget(1).dtype.type == t\n assert tmgr.iget(2).dtype.type == t\n\n # mixed\n mgr = create_mgr("a,b: object; c: bool; d: datetime; e: f4; f: f2; g: f8")\n\n t = np.dtype(t)\n tmgr = mgr.astype(t, errors="ignore")\n assert tmgr.iget(2).dtype.type == t\n assert tmgr.iget(4).dtype.type == t\n assert tmgr.iget(5).dtype.type == t\n assert tmgr.iget(6).dtype.type == t\n\n assert tmgr.iget(0).dtype.type == np.object_\n assert tmgr.iget(1).dtype.type == np.object_\n if t != np.int64:\n assert tmgr.iget(3).dtype.type == np.datetime64\n else:\n assert tmgr.iget(3).dtype.type == t\n\n def test_convert(self, using_infer_string):\n def _compare(old_mgr, new_mgr):\n """compare the blocks, numeric compare ==, object don't"""\n old_blocks = set(old_mgr.blocks)\n new_blocks = set(new_mgr.blocks)\n assert len(old_blocks) == len(new_blocks)\n\n # compare non-numeric\n for b in old_blocks:\n found = False\n for nb in new_blocks:\n if (b.values == nb.values).all():\n found = True\n break\n assert found\n\n for b in new_blocks:\n found = False\n for ob in old_blocks:\n if (b.values == ob.values).all():\n found = True\n break\n assert found\n\n # noops\n mgr = create_mgr("f: i8; g: f8")\n new_mgr = mgr.convert(copy=True)\n _compare(mgr, new_mgr)\n\n # convert\n mgr = create_mgr("a,b,foo: object; f: i8; g: f8")\n mgr.iset(0, np.array(["1"] * N, dtype=np.object_))\n mgr.iset(1, np.array(["2."] * N, dtype=np.object_))\n mgr.iset(2, np.array(["foo."] * N, dtype=np.object_))\n new_mgr = mgr.convert(copy=True)\n dtype = "str" if using_infer_string else np.object_\n assert new_mgr.iget(0).dtype == dtype\n assert new_mgr.iget(1).dtype == dtype\n assert new_mgr.iget(2).dtype == dtype\n assert new_mgr.iget(3).dtype == np.int64\n assert new_mgr.iget(4).dtype == np.float64\n\n mgr = create_mgr(\n "a,b,foo: object; f: i4; bool: bool; dt: datetime; i: i8; g: f8; h: f2"\n )\n mgr.iset(0, np.array(["1"] * N, dtype=np.object_))\n mgr.iset(1, np.array(["2."] * N, dtype=np.object_))\n mgr.iset(2, np.array(["foo."] * N, dtype=np.object_))\n new_mgr = mgr.convert(copy=True)\n assert new_mgr.iget(0).dtype == dtype\n assert new_mgr.iget(1).dtype == dtype\n assert new_mgr.iget(2).dtype == dtype\n assert new_mgr.iget(3).dtype == np.int32\n assert new_mgr.iget(4).dtype == np.bool_\n assert new_mgr.iget(5).dtype.type, np.datetime64\n assert new_mgr.iget(6).dtype == np.int64\n assert new_mgr.iget(7).dtype == np.float64\n assert new_mgr.iget(8).dtype == np.float16\n\n def test_interleave(self):\n # self\n for dtype in ["f8", "i8", "object", "bool", "complex", "M8[ns]", "m8[ns]"]:\n mgr = create_mgr(f"a: {dtype}")\n assert mgr.as_array().dtype == dtype\n mgr = create_mgr(f"a: {dtype}; b: {dtype}")\n assert mgr.as_array().dtype == dtype\n\n @pytest.mark.parametrize(\n "mgr_string, dtype",\n [\n ("a: category", "i8"),\n ("a: category; b: category", "i8"),\n ("a: category; b: category2", "object"),\n ("a: category2", "object"),\n ("a: category2; b: category2", "object"),\n ("a: f8", "f8"),\n ("a: f8; b: i8", "f8"),\n ("a: f4; b: i8", "f8"),\n ("a: f4; b: i8; d: object", "object"),\n ("a: bool; b: i8", "object"),\n ("a: complex", "complex"),\n ("a: f8; b: category", "object"),\n ("a: M8[ns]; b: category", "object"),\n ("a: M8[ns]; b: bool", "object"),\n ("a: M8[ns]; b: i8", "object"),\n ("a: m8[ns]; b: bool", "object"),\n ("a: m8[ns]; b: i8", "object"),\n ("a: M8[ns]; b: m8[ns]", "object"),\n ],\n )\n def test_interleave_dtype(self, mgr_string, dtype):\n # will be converted according the actual dtype of the underlying\n mgr = create_mgr("a: category")\n assert mgr.as_array().dtype == "i8"\n mgr = create_mgr("a: category; b: category2")\n assert mgr.as_array().dtype == "object"\n mgr = create_mgr("a: category2")\n assert mgr.as_array().dtype == "object"\n\n # combinations\n mgr = create_mgr("a: f8")\n assert mgr.as_array().dtype == "f8"\n mgr = create_mgr("a: f8; b: i8")\n assert mgr.as_array().dtype == "f8"\n mgr = create_mgr("a: f4; b: i8")\n assert mgr.as_array().dtype == "f8"\n mgr = create_mgr("a: f4; b: i8; d: object")\n assert mgr.as_array().dtype == "object"\n mgr = create_mgr("a: bool; b: i8")\n assert mgr.as_array().dtype == "object"\n mgr = create_mgr("a: complex")\n assert mgr.as_array().dtype == "complex"\n mgr = create_mgr("a: f8; b: category")\n assert mgr.as_array().dtype == "f8"\n mgr = create_mgr("a: M8[ns]; b: category")\n assert mgr.as_array().dtype == "object"\n mgr = create_mgr("a: M8[ns]; b: bool")\n assert mgr.as_array().dtype == "object"\n mgr = create_mgr("a: M8[ns]; b: i8")\n assert mgr.as_array().dtype == "object"\n mgr = create_mgr("a: m8[ns]; b: bool")\n assert mgr.as_array().dtype == "object"\n mgr = create_mgr("a: m8[ns]; b: i8")\n assert mgr.as_array().dtype == "object"\n mgr = create_mgr("a: M8[ns]; b: m8[ns]")\n assert mgr.as_array().dtype == "object"\n\n def test_consolidate_ordering_issues(self, mgr):\n mgr.iset(mgr.items.get_loc("f"), np.random.default_rng(2).standard_normal(N))\n mgr.iset(mgr.items.get_loc("d"), np.random.default_rng(2).standard_normal(N))\n mgr.iset(mgr.items.get_loc("b"), np.random.default_rng(2).standard_normal(N))\n mgr.iset(mgr.items.get_loc("g"), np.random.default_rng(2).standard_normal(N))\n mgr.iset(mgr.items.get_loc("h"), np.random.default_rng(2).standard_normal(N))\n\n # we have datetime/tz blocks in mgr\n cons = mgr.consolidate()\n assert cons.nblocks == 4\n cons = mgr.consolidate().get_numeric_data()\n assert cons.nblocks == 1\n assert isinstance(cons.blocks[0].mgr_locs, BlockPlacement)\n tm.assert_numpy_array_equal(\n cons.blocks[0].mgr_locs.as_array, np.arange(len(cons.items), dtype=np.intp)\n )\n\n def test_reindex_items(self):\n # mgr is not consolidated, f8 & f8-2 blocks\n mgr = create_mgr("a: f8; b: i8; c: f8; d: i8; e: f8; f: bool; g: f8-2")\n\n reindexed = mgr.reindex_axis(["g", "c", "a", "d"], axis=0)\n # reindex_axis does not consolidate_inplace, as that risks failing to\n # invalidate _item_cache\n assert not reindexed.is_consolidated()\n\n tm.assert_index_equal(reindexed.items, Index(["g", "c", "a", "d"]))\n tm.assert_almost_equal(\n mgr.iget(6).internal_values(), reindexed.iget(0).internal_values()\n )\n tm.assert_almost_equal(\n mgr.iget(2).internal_values(), reindexed.iget(1).internal_values()\n )\n tm.assert_almost_equal(\n mgr.iget(0).internal_values(), reindexed.iget(2).internal_values()\n )\n tm.assert_almost_equal(\n mgr.iget(3).internal_values(), reindexed.iget(3).internal_values()\n )\n\n def test_get_numeric_data(self, using_copy_on_write):\n mgr = create_mgr(\n "int: int; float: float; complex: complex;"\n "str: object; bool: bool; obj: object; dt: datetime",\n item_shape=(3,),\n )\n mgr.iset(5, np.array([1, 2, 3], dtype=np.object_))\n\n numeric = mgr.get_numeric_data()\n tm.assert_index_equal(numeric.items, Index(["int", "float", "complex", "bool"]))\n tm.assert_almost_equal(\n mgr.iget(mgr.items.get_loc("float")).internal_values(),\n numeric.iget(numeric.items.get_loc("float")).internal_values(),\n )\n\n # Check sharing\n numeric.iset(\n numeric.items.get_loc("float"),\n np.array([100.0, 200.0, 300.0]),\n inplace=True,\n )\n if using_copy_on_write:\n tm.assert_almost_equal(\n mgr.iget(mgr.items.get_loc("float")).internal_values(),\n np.array([1.0, 1.0, 1.0]),\n )\n else:\n tm.assert_almost_equal(\n mgr.iget(mgr.items.get_loc("float")).internal_values(),\n np.array([100.0, 200.0, 300.0]),\n )\n\n def test_get_bool_data(self, using_copy_on_write):\n mgr = create_mgr(\n "int: int; float: float; complex: complex;"\n "str: object; bool: bool; obj: object; dt: datetime",\n item_shape=(3,),\n )\n mgr.iset(6, np.array([True, False, True], dtype=np.object_))\n\n bools = mgr.get_bool_data()\n tm.assert_index_equal(bools.items, Index(["bool"]))\n tm.assert_almost_equal(\n mgr.iget(mgr.items.get_loc("bool")).internal_values(),\n bools.iget(bools.items.get_loc("bool")).internal_values(),\n )\n\n bools.iset(0, np.array([True, False, True]), inplace=True)\n if using_copy_on_write:\n tm.assert_numpy_array_equal(\n mgr.iget(mgr.items.get_loc("bool")).internal_values(),\n np.array([True, True, True]),\n )\n else:\n tm.assert_numpy_array_equal(\n mgr.iget(mgr.items.get_loc("bool")).internal_values(),\n np.array([True, False, True]),\n )\n\n def test_unicode_repr_doesnt_raise(self):\n repr(create_mgr("b,\u05d0: object"))\n\n @pytest.mark.parametrize(\n "mgr_string", ["a,b,c: i8-1; d,e,f: i8-2", "a,a,a: i8-1; b,b,b: i8-2"]\n )\n def test_equals(self, mgr_string):\n # unique items\n bm1 = create_mgr(mgr_string)\n bm2 = BlockManager(bm1.blocks[::-1], bm1.axes)\n assert bm1.equals(bm2)\n\n @pytest.mark.parametrize(\n "mgr_string",\n [\n "a:i8;b:f8", # basic case\n "a:i8;b:f8;c:c8;d:b", # many types\n "a:i8;e:dt;f:td;g:string", # more types\n "a:i8;b:category;c:category2", # categories\n "c:sparse;d:sparse_na;b:f8", # sparse\n ],\n )\n def test_equals_block_order_different_dtypes(self, mgr_string):\n # GH 9330\n bm = create_mgr(mgr_string)\n block_perms = itertools.permutations(bm.blocks)\n for bm_perm in block_perms:\n bm_this = BlockManager(tuple(bm_perm), bm.axes)\n assert bm.equals(bm_this)\n assert bm_this.equals(bm)\n\n def test_single_mgr_ctor(self):\n mgr = create_single_mgr("f8", num_rows=5)\n assert mgr.external_values().tolist() == [0.0, 1.0, 2.0, 3.0, 4.0]\n\n @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])\n def test_validate_bool_args(self, value):\n bm1 = create_mgr("a,b,c: i8-1; d,e,f: i8-2")\n\n msg = (\n 'For argument "inplace" expected type bool, '\n f"received type {type(value).__name__}."\n )\n with pytest.raises(ValueError, match=msg):\n bm1.replace_list([1], [2], inplace=value)\n\n def test_iset_split_block(self):\n bm = create_mgr("a,b,c: i8; d: f8")\n bm._iset_split_block(0, np.array([0]))\n tm.assert_numpy_array_equal(\n bm.blklocs, np.array([0, 0, 1, 0], dtype="int64" if IS64 else "int32")\n )\n # First indexer currently does not have a block associated with it in case\n tm.assert_numpy_array_equal(\n bm.blknos, np.array([0, 0, 0, 1], dtype="int64" if IS64 else "int32")\n )\n assert len(bm.blocks) == 2\n\n def test_iset_split_block_values(self):\n bm = create_mgr("a,b,c: i8; d: f8")\n bm._iset_split_block(0, np.array([0]), np.array([list(range(10))]))\n tm.assert_numpy_array_equal(\n bm.blklocs, np.array([0, 0, 1, 0], dtype="int64" if IS64 else "int32")\n )\n # First indexer currently does not have a block associated with it in case\n tm.assert_numpy_array_equal(\n bm.blknos, np.array([0, 2, 2, 1], dtype="int64" if IS64 else "int32")\n )\n assert len(bm.blocks) == 3\n\n\ndef _as_array(mgr):\n if mgr.ndim == 1:\n return mgr.external_values()\n return mgr.as_array().T\n\n\nclass TestIndexing:\n # Nosetests-style data-driven tests.\n #\n # This test applies different indexing routines to block managers and\n # compares the outcome to the result of same operations on np.ndarray.\n #\n # NOTE: sparse (SparseBlock with fill_value != np.nan) fail a lot of tests\n # and are disabled.\n\n MANAGERS = [\n create_single_mgr("f8", N),\n create_single_mgr("i8", N),\n # 2-dim\n create_mgr("a,b,c,d,e,f: f8", item_shape=(N,)),\n create_mgr("a,b,c,d,e,f: i8", item_shape=(N,)),\n create_mgr("a,b: f8; c,d: i8; e,f: string", item_shape=(N,)),\n create_mgr("a,b: f8; c,d: i8; e,f: f8", item_shape=(N,)),\n ]\n\n @pytest.mark.parametrize("mgr", MANAGERS)\n def test_get_slice(self, mgr):\n def assert_slice_ok(mgr, axis, slobj):\n mat = _as_array(mgr)\n\n # we maybe using an ndarray to test slicing and\n # might not be the full length of the axis\n if isinstance(slobj, np.ndarray):\n ax = mgr.axes[axis]\n if len(ax) and len(slobj) and len(slobj) != len(ax):\n slobj = np.concatenate(\n [slobj, np.zeros(len(ax) - len(slobj), dtype=bool)]\n )\n\n if isinstance(slobj, slice):\n sliced = mgr.get_slice(slobj, axis=axis)\n elif (\n mgr.ndim == 1\n and axis == 0\n and isinstance(slobj, np.ndarray)\n and slobj.dtype == bool\n ):\n sliced = mgr.get_rows_with_mask(slobj)\n else:\n # BlockManager doesn't support non-slice, SingleBlockManager\n # doesn't support axis > 0\n raise TypeError(slobj)\n\n mat_slobj = (slice(None),) * axis + (slobj,)\n tm.assert_numpy_array_equal(\n mat[mat_slobj], _as_array(sliced), check_dtype=False\n )\n tm.assert_index_equal(mgr.axes[axis][slobj], sliced.axes[axis])\n\n assert mgr.ndim <= 2, mgr.ndim\n for ax in range(mgr.ndim):\n # slice\n assert_slice_ok(mgr, ax, slice(None))\n assert_slice_ok(mgr, ax, slice(3))\n assert_slice_ok(mgr, ax, slice(100))\n assert_slice_ok(mgr, ax, slice(1, 4))\n assert_slice_ok(mgr, ax, slice(3, 0, -2))\n\n if mgr.ndim < 2:\n # 2D only support slice objects\n\n # boolean mask\n assert_slice_ok(mgr, ax, np.ones(mgr.shape[ax], dtype=np.bool_))\n assert_slice_ok(mgr, ax, np.zeros(mgr.shape[ax], dtype=np.bool_))\n\n if mgr.shape[ax] >= 3:\n assert_slice_ok(mgr, ax, np.arange(mgr.shape[ax]) % 3 == 0)\n assert_slice_ok(\n mgr, ax, np.array([True, True, False], dtype=np.bool_)\n )\n\n @pytest.mark.parametrize("mgr", MANAGERS)\n def test_take(self, mgr):\n def assert_take_ok(mgr, axis, indexer):\n mat = _as_array(mgr)\n taken = mgr.take(indexer, axis)\n tm.assert_numpy_array_equal(\n np.take(mat, indexer, axis), _as_array(taken), check_dtype=False\n )\n tm.assert_index_equal(mgr.axes[axis].take(indexer), taken.axes[axis])\n\n for ax in range(mgr.ndim):\n # take/fancy indexer\n assert_take_ok(mgr, ax, indexer=np.array([], dtype=np.intp))\n assert_take_ok(mgr, ax, indexer=np.array([0, 0, 0], dtype=np.intp))\n assert_take_ok(\n mgr, ax, indexer=np.array(list(range(mgr.shape[ax])), dtype=np.intp)\n )\n\n if mgr.shape[ax] >= 3:\n assert_take_ok(mgr, ax, indexer=np.array([0, 1, 2], dtype=np.intp))\n assert_take_ok(mgr, ax, indexer=np.array([-1, -2, -3], dtype=np.intp))\n\n @pytest.mark.parametrize("mgr", MANAGERS)\n @pytest.mark.parametrize("fill_value", [None, np.nan, 100.0])\n def test_reindex_axis(self, fill_value, mgr):\n def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value):\n mat = _as_array(mgr)\n indexer = mgr.axes[axis].get_indexer_for(new_labels)\n\n reindexed = mgr.reindex_axis(new_labels, axis, fill_value=fill_value)\n tm.assert_numpy_array_equal(\n algos.take_nd(mat, indexer, axis, fill_value=fill_value),\n _as_array(reindexed),\n check_dtype=False,\n )\n tm.assert_index_equal(reindexed.axes[axis], new_labels)\n\n for ax in range(mgr.ndim):\n assert_reindex_axis_is_ok(mgr, ax, Index([]), fill_value)\n assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax], fill_value)\n assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][[0, 0, 0]], fill_value)\n assert_reindex_axis_is_ok(mgr, ax, Index(["foo", "bar", "baz"]), fill_value)\n assert_reindex_axis_is_ok(\n mgr, ax, Index(["foo", mgr.axes[ax][0], "baz"]), fill_value\n )\n\n if mgr.shape[ax] >= 3:\n assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][:-3], fill_value)\n assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][-3::-1], fill_value)\n assert_reindex_axis_is_ok(\n mgr, ax, mgr.axes[ax][[0, 1, 2, 0, 1, 2]], fill_value\n )\n\n @pytest.mark.parametrize("mgr", MANAGERS)\n @pytest.mark.parametrize("fill_value", [None, np.nan, 100.0])\n def test_reindex_indexer(self, fill_value, mgr):\n def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value):\n mat = _as_array(mgr)\n reindexed_mat = algos.take_nd(mat, indexer, axis, fill_value=fill_value)\n reindexed = mgr.reindex_indexer(\n new_labels, indexer, axis, fill_value=fill_value\n )\n tm.assert_numpy_array_equal(\n reindexed_mat, _as_array(reindexed), check_dtype=False\n )\n tm.assert_index_equal(reindexed.axes[axis], new_labels)\n\n for ax in range(mgr.ndim):\n assert_reindex_indexer_is_ok(\n mgr, ax, Index([]), np.array([], dtype=np.intp), fill_value\n )\n assert_reindex_indexer_is_ok(\n mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax]), fill_value\n )\n assert_reindex_indexer_is_ok(\n mgr,\n ax,\n Index(["foo"] * mgr.shape[ax]),\n np.arange(mgr.shape[ax]),\n fill_value,\n )\n assert_reindex_indexer_is_ok(\n mgr, ax, mgr.axes[ax][::-1], np.arange(mgr.shape[ax]), fill_value\n )\n assert_reindex_indexer_is_ok(\n mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax])[::-1], fill_value\n )\n assert_reindex_indexer_is_ok(\n mgr, ax, Index(["foo", "bar", "baz"]), np.array([0, 0, 0]), fill_value\n )\n assert_reindex_indexer_is_ok(\n mgr, ax, Index(["foo", "bar", "baz"]), np.array([-1, 0, -1]), fill_value\n )\n assert_reindex_indexer_is_ok(\n mgr,\n ax,\n Index(["foo", mgr.axes[ax][0], "baz"]),\n np.array([-1, -1, -1]),\n fill_value,\n )\n\n if mgr.shape[ax] >= 3:\n assert_reindex_indexer_is_ok(\n mgr,\n ax,\n Index(["foo", "bar", "baz"]),\n np.array([0, 1, 2]),\n fill_value,\n )\n\n\nclass TestBlockPlacement:\n @pytest.mark.parametrize(\n "slc, expected",\n [\n (slice(0, 4), 4),\n (slice(0, 4, 2), 2),\n (slice(0, 3, 2), 2),\n (slice(0, 1, 2), 1),\n (slice(1, 0, -1), 1),\n ],\n )\n def test_slice_len(self, slc, expected):\n assert len(BlockPlacement(slc)) == expected\n\n @pytest.mark.parametrize("slc", [slice(1, 1, 0), slice(1, 2, 0)])\n def test_zero_step_raises(self, slc):\n msg = "slice step cannot be zero"\n with pytest.raises(ValueError, match=msg):\n BlockPlacement(slc)\n\n def test_slice_canonize_negative_stop(self):\n # GH#37524 negative stop is OK with negative step and positive start\n slc = slice(3, -1, -2)\n\n bp = BlockPlacement(slc)\n assert bp.indexer == slice(3, None, -2)\n\n @pytest.mark.parametrize(\n "slc",\n [\n slice(None, None),\n slice(10, None),\n slice(None, None, -1),\n slice(None, 10, -1),\n # These are "unbounded" because negative index will\n # change depending on container shape.\n slice(-1, None),\n slice(None, -1),\n slice(-1, -1),\n slice(-1, None, -1),\n slice(None, -1, -1),\n slice(-1, -1, -1),\n ],\n )\n def test_unbounded_slice_raises(self, slc):\n msg = "unbounded slice"\n with pytest.raises(ValueError, match=msg):\n BlockPlacement(slc)\n\n @pytest.mark.parametrize(\n "slc",\n [\n slice(0, 0),\n slice(100, 0),\n slice(100, 100),\n slice(100, 100, -1),\n slice(0, 100, -1),\n ],\n )\n def test_not_slice_like_slices(self, slc):\n assert not BlockPlacement(slc).is_slice_like\n\n @pytest.mark.parametrize(\n "arr, slc",\n [\n ([0], slice(0, 1, 1)),\n ([100], slice(100, 101, 1)),\n ([0, 1, 2], slice(0, 3, 1)),\n ([0, 5, 10], slice(0, 15, 5)),\n ([0, 100], slice(0, 200, 100)),\n ([2, 1], slice(2, 0, -1)),\n ],\n )\n def test_array_to_slice_conversion(self, arr, slc):\n assert BlockPlacement(arr).as_slice == slc\n\n @pytest.mark.parametrize(\n "arr",\n [\n [],\n [-1],\n [-1, -2, -3],\n [-10],\n [-1],\n [-1, 0, 1, 2],\n [-2, 0, 2, 4],\n [1, 0, -1],\n [1, 1, 1],\n ],\n )\n def test_not_slice_like_arrays(self, arr):\n assert not BlockPlacement(arr).is_slice_like\n\n @pytest.mark.parametrize(\n "slc, expected",\n [(slice(0, 3), [0, 1, 2]), (slice(0, 0), []), (slice(3, 0), [])],\n )\n def test_slice_iter(self, slc, expected):\n assert list(BlockPlacement(slc)) == expected\n\n @pytest.mark.parametrize(\n "slc, arr",\n [\n (slice(0, 3), [0, 1, 2]),\n (slice(0, 0), []),\n (slice(3, 0), []),\n (slice(3, 0, -1), [3, 2, 1]),\n ],\n )\n def test_slice_to_array_conversion(self, slc, arr):\n tm.assert_numpy_array_equal(\n BlockPlacement(slc).as_array, np.asarray(arr, dtype=np.intp)\n )\n\n def test_blockplacement_add(self):\n bpl = BlockPlacement(slice(0, 5))\n assert bpl.add(1).as_slice == slice(1, 6, 1)\n assert bpl.add(np.arange(5)).as_slice == slice(0, 10, 2)\n assert list(bpl.add(np.arange(5, 0, -1))) == [5, 5, 5, 5, 5]\n\n @pytest.mark.parametrize(\n "val, inc, expected",\n [\n (slice(0, 0), 0, []),\n (slice(1, 4), 0, [1, 2, 3]),\n (slice(3, 0, -1), 0, [3, 2, 1]),\n ([1, 2, 4], 0, [1, 2, 4]),\n (slice(0, 0), 10, []),\n (slice(1, 4), 10, [11, 12, 13]),\n (slice(3, 0, -1), 10, [13, 12, 11]),\n ([1, 2, 4], 10, [11, 12, 14]),\n (slice(0, 0), -1, []),\n (slice(1, 4), -1, [0, 1, 2]),\n ([1, 2, 4], -1, [0, 1, 3]),\n ],\n )\n def test_blockplacement_add_int(self, val, inc, expected):\n assert list(BlockPlacement(val).add(inc)) == expected\n\n @pytest.mark.parametrize("val", [slice(1, 4), [1, 2, 4]])\n def test_blockplacement_add_int_raises(self, val):\n msg = "iadd causes length change"\n with pytest.raises(ValueError, match=msg):\n BlockPlacement(val).add(-10)\n\n\nclass TestCanHoldElement:\n @pytest.fixture(\n params=[\n lambda x: x,\n lambda x: x.to_series(),\n lambda x: x._data,\n lambda x: list(x),\n lambda x: x.astype(object),\n lambda x: np.asarray(x),\n lambda x: x[0],\n lambda x: x[:0],\n ]\n )\n def element(self, request):\n """\n Functions that take an Index and return an element that should have\n blk._can_hold_element(element) for a Block with this index's dtype.\n """\n return request.param\n\n def test_datetime_block_can_hold_element(self):\n block = create_block("datetime", [0])\n\n assert block._can_hold_element([])\n\n # We will check that block._can_hold_element iff arr.__setitem__ works\n arr = pd.array(block.values.ravel())\n\n # coerce None\n assert block._can_hold_element(None)\n arr[0] = None\n assert arr[0] is pd.NaT\n\n # coerce different types of datetime objects\n vals = [np.datetime64("2010-10-10"), datetime(2010, 10, 10)]\n for val in vals:\n assert block._can_hold_element(val)\n arr[0] = val\n\n val = date(2010, 10, 10)\n assert not block._can_hold_element(val)\n\n msg = (\n "value should be a 'Timestamp', 'NaT', "\n "or array of those. Got 'date' instead."\n )\n with pytest.raises(TypeError, match=msg):\n arr[0] = val\n\n @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])\n def test_interval_can_hold_element_emptylist(self, dtype, element):\n arr = np.array([1, 3, 4], dtype=dtype)\n ii = IntervalIndex.from_breaks(arr)\n blk = new_block(ii._data, BlockPlacement([1]), ndim=2)\n\n assert blk._can_hold_element([])\n # TODO: check this holds for all blocks\n\n @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64])\n def test_interval_can_hold_element(self, dtype, element):\n arr = np.array([1, 3, 4, 9], dtype=dtype)\n ii = IntervalIndex.from_breaks(arr)\n blk = new_block(ii._data, BlockPlacement([1]), ndim=2)\n\n elem = element(ii)\n self.check_series_setitem(elem, ii, True)\n assert blk._can_hold_element(elem)\n\n # Careful: to get the expected Series-inplace behavior we need\n # `elem` to not have the same length as `arr`\n ii2 = IntervalIndex.from_breaks(arr[:-1], closed="neither")\n elem = element(ii2)\n with tm.assert_produces_warning(FutureWarning):\n self.check_series_setitem(elem, ii, False)\n assert not blk._can_hold_element(elem)\n\n ii3 = IntervalIndex.from_breaks([Timestamp(1), Timestamp(3), Timestamp(4)])\n elem = element(ii3)\n with tm.assert_produces_warning(FutureWarning):\n self.check_series_setitem(elem, ii, False)\n assert not blk._can_hold_element(elem)\n\n ii4 = IntervalIndex.from_breaks([Timedelta(1), Timedelta(3), Timedelta(4)])\n elem = element(ii4)\n with tm.assert_produces_warning(FutureWarning):\n self.check_series_setitem(elem, ii, False)\n assert not blk._can_hold_element(elem)\n\n def test_period_can_hold_element_emptylist(self):\n pi = period_range("2016", periods=3, freq="Y")\n blk = new_block(pi._data.reshape(1, 3), BlockPlacement([1]), ndim=2)\n\n assert blk._can_hold_element([])\n\n def test_period_can_hold_element(self, element):\n pi = period_range("2016", periods=3, freq="Y")\n\n elem = element(pi)\n self.check_series_setitem(elem, pi, True)\n\n # Careful: to get the expected Series-inplace behavior we need\n # `elem` to not have the same length as `arr`\n pi2 = pi.asfreq("D")[:-1]\n elem = element(pi2)\n with tm.assert_produces_warning(FutureWarning):\n self.check_series_setitem(elem, pi, False)\n\n dti = pi.to_timestamp("s")[:-1]\n elem = element(dti)\n with tm.assert_produces_warning(FutureWarning):\n self.check_series_setitem(elem, pi, False)\n\n def check_can_hold_element(self, obj, elem, inplace: bool):\n blk = obj._mgr.blocks[0]\n if inplace:\n assert blk._can_hold_element(elem)\n else:\n assert not blk._can_hold_element(elem)\n\n def check_series_setitem(self, elem, index: Index, inplace: bool):\n arr = index._data.copy()\n ser = Series(arr, copy=False)\n\n self.check_can_hold_element(ser, elem, inplace)\n\n if is_scalar(elem):\n ser[0] = elem\n else:\n ser[: len(elem)] = elem\n\n if inplace:\n assert ser.array is arr # i.e. setting was done inplace\n else:\n assert ser.dtype == object\n\n\nclass TestShouldStore:\n def test_should_store_categorical(self):\n cat = Categorical(["A", "B", "C"])\n df = DataFrame(cat)\n blk = df._mgr.blocks[0]\n\n # matching dtype\n assert blk.should_store(cat)\n assert blk.should_store(cat[:-1])\n\n # different dtype\n assert not blk.should_store(cat.as_ordered())\n\n # ndarray instead of Categorical\n assert not blk.should_store(np.asarray(cat))\n\n\ndef test_validate_ndim():\n values = np.array([1.0, 2.0])\n placement = BlockPlacement(slice(2))\n msg = r"Wrong number of dimensions. values.ndim != ndim \[1 != 2\]"\n\n with pytest.raises(ValueError, match=msg):\n make_block(values, placement, ndim=2)\n\n\ndef test_block_shape():\n idx = Index([0, 1, 2, 3, 4])\n a = Series([1, 2, 3]).reindex(idx)\n b = Series(Categorical([1, 2, 3])).reindex(idx)\n\n assert a._mgr.blocks[0].mgr_locs.indexer == b._mgr.blocks[0].mgr_locs.indexer\n\n\ndef test_make_block_no_pandas_array(block_maker):\n # https://github.com/pandas-dev/pandas/pull/24866\n arr = pd.arrays.NumpyExtensionArray(np.array([1, 2]))\n\n # NumpyExtensionArray, no dtype\n result = block_maker(arr, BlockPlacement(slice(len(arr))), ndim=arr.ndim)\n assert result.dtype.kind in ["i", "u"]\n\n if block_maker is make_block:\n # new_block requires caller to unwrap NumpyExtensionArray\n assert result.is_extension is False\n\n # NumpyExtensionArray, NumpyEADtype\n result = block_maker(arr, slice(len(arr)), dtype=arr.dtype, ndim=arr.ndim)\n assert result.dtype.kind in ["i", "u"]\n assert result.is_extension is False\n\n # new_block no longer taked dtype keyword\n # ndarray, NumpyEADtype\n result = block_maker(\n arr.to_numpy(), slice(len(arr)), dtype=arr.dtype, ndim=arr.ndim\n )\n assert result.dtype.kind in ["i", "u"]\n assert result.is_extension is False\n
.venv\Lib\site-packages\pandas\tests\internals\test_internals.py
test_internals.py
Python
49,639
0.95
0.100563
0.071133
awesome-app
917
2023-09-08T15:59:50.016325
Apache-2.0
true
c283f5a7301a4bdfb8f4184796aa61da
"""\nTesting interaction between the different managers (BlockManager, ArrayManager)\n"""\nimport os\nimport subprocess\nimport sys\n\nimport pytest\n\nfrom pandas.core.dtypes.missing import array_equivalent\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.internals import (\n ArrayManager,\n BlockManager,\n SingleArrayManager,\n SingleBlockManager,\n)\n\n\ndef test_dataframe_creation():\n msg = "data_manager option is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with pd.option_context("mode.data_manager", "block"):\n df_block = pd.DataFrame(\n {"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]}\n )\n assert isinstance(df_block._mgr, BlockManager)\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with pd.option_context("mode.data_manager", "array"):\n df_array = pd.DataFrame(\n {"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]}\n )\n assert isinstance(df_array._mgr, ArrayManager)\n\n # also ensure both are seen as equal\n tm.assert_frame_equal(df_block, df_array)\n\n # conversion from one manager to the other\n result = df_block._as_manager("block")\n assert isinstance(result._mgr, BlockManager)\n result = df_block._as_manager("array")\n assert isinstance(result._mgr, ArrayManager)\n tm.assert_frame_equal(result, df_block)\n assert all(\n array_equivalent(left, right)\n for left, right in zip(result._mgr.arrays, df_array._mgr.arrays)\n )\n\n result = df_array._as_manager("array")\n assert isinstance(result._mgr, ArrayManager)\n result = df_array._as_manager("block")\n assert isinstance(result._mgr, BlockManager)\n tm.assert_frame_equal(result, df_array)\n assert len(result._mgr.blocks) == 2\n\n\ndef test_series_creation():\n msg = "data_manager option is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with pd.option_context("mode.data_manager", "block"):\n s_block = pd.Series([1, 2, 3], name="A", index=["a", "b", "c"])\n assert isinstance(s_block._mgr, SingleBlockManager)\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with pd.option_context("mode.data_manager", "array"):\n s_array = pd.Series([1, 2, 3], name="A", index=["a", "b", "c"])\n assert isinstance(s_array._mgr, SingleArrayManager)\n\n # also ensure both are seen as equal\n tm.assert_series_equal(s_block, s_array)\n\n # conversion from one manager to the other\n result = s_block._as_manager("block")\n assert isinstance(result._mgr, SingleBlockManager)\n result = s_block._as_manager("array")\n assert isinstance(result._mgr, SingleArrayManager)\n tm.assert_series_equal(result, s_block)\n\n result = s_array._as_manager("array")\n assert isinstance(result._mgr, SingleArrayManager)\n result = s_array._as_manager("block")\n assert isinstance(result._mgr, SingleBlockManager)\n tm.assert_series_equal(result, s_array)\n\n\n@pytest.mark.single_cpu\n@pytest.mark.parametrize("manager", ["block", "array"])\ndef test_array_manager_depr_env_var(manager):\n # GH#55043\n test_env = os.environ.copy()\n test_env["PANDAS_DATA_MANAGER"] = manager\n response = subprocess.run(\n [sys.executable, "-c", "import pandas"],\n capture_output=True,\n env=test_env,\n check=True,\n )\n msg = "FutureWarning: The env variable PANDAS_DATA_MANAGER is set"\n stderr_msg = response.stderr.decode("utf-8")\n assert msg in stderr_msg, stderr_msg\n
.venv\Lib\site-packages\pandas\tests\internals\test_managers.py
test_managers.py
Python
3,556
0.95
0.038835
0.05814
vue-tools
561
2025-03-11T03:41:42.542844
MIT
true
e2092c89e189055dfd41dd4c85db4c61
\n\n
.venv\Lib\site-packages\pandas\tests\internals\__pycache__\test_api.cpython-313.pyc
test_api.cpython-313.pyc
Other
3,247
0.8
0.02381
0.025
node-utils
295
2023-12-12T14:24:22.441404
GPL-3.0
true
0149c5b2d9b41e41a0c938105e08b131
\n\n
.venv\Lib\site-packages\pandas\tests\internals\__pycache__\test_internals.cpython-313.pyc
test_internals.cpython-313.pyc
Other
81,609
0.6
0.00274
0.030568
react-lib
906
2025-06-22T23:11:24.391131
MIT
true
b94f559637e00258770016ab0cd832a8
\n\n
.venv\Lib\site-packages\pandas\tests\internals\__pycache__\test_managers.cpython-313.pyc
test_managers.cpython-313.pyc
Other
6,254
0.95
0
0.038835
vue-tools
526
2024-06-12T13:20:03.077277
BSD-3-Clause
true
2baa79102fc69aeae4a799dbead1926b
\n\n
.venv\Lib\site-packages\pandas\tests\internals\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
197
0.7
0
0
react-lib
790
2025-04-02T13:03:46.725640
MIT
true
ba799e9c89edba35fcafc54b3562da28
import shlex\nimport subprocess\nimport time\nimport uuid\n\nimport pytest\n\nfrom pandas.compat import (\n is_ci_environment,\n is_platform_arm,\n is_platform_mac,\n is_platform_windows,\n)\nimport pandas.util._test_decorators as td\n\nimport pandas.io.common as icom\nfrom pandas.io.parsers import read_csv\n\n\n@pytest.fixture\ndef compression_to_extension():\n return {value: key for key, value in icom.extension_to_compression.items()}\n\n\n@pytest.fixture\ndef tips_file(datapath):\n """Path to the tips dataset"""\n return datapath("io", "data", "csv", "tips.csv")\n\n\n@pytest.fixture\ndef jsonl_file(datapath):\n """Path to a JSONL dataset"""\n return datapath("io", "parser", "data", "items.jsonl")\n\n\n@pytest.fixture\ndef salaries_table(datapath):\n """DataFrame with the salaries dataset"""\n return read_csv(datapath("io", "parser", "data", "salaries.csv"), sep="\t")\n\n\n@pytest.fixture\ndef feather_file(datapath):\n return datapath("io", "data", "feather", "feather-0_3_1.feather")\n\n\n@pytest.fixture\ndef xml_file(datapath):\n return datapath("io", "data", "xml", "books.xml")\n\n\n@pytest.fixture\ndef s3_base(worker_id, monkeypatch):\n """\n Fixture for mocking S3 interaction.\n\n Sets up moto server in separate process locally\n Return url for motoserver/moto CI service\n """\n pytest.importorskip("s3fs")\n pytest.importorskip("boto3")\n\n # temporary workaround as moto fails for botocore >= 1.11 otherwise,\n # see https://github.com/spulec/moto/issues/1924 & 1952\n monkeypatch.setenv("AWS_ACCESS_KEY_ID", "foobar_key")\n monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "foobar_secret")\n if is_ci_environment():\n if is_platform_arm() or is_platform_mac() or is_platform_windows():\n # NOT RUN on Windows/macOS, only Ubuntu\n # - subprocess in CI can cause timeouts\n # - GitHub Actions do not support\n # container services for the above OSs\n pytest.skip(\n "S3 tests do not have a corresponding service on "\n "Windows or macOS platforms"\n )\n else:\n # set in .github/workflows/unit-tests.yml\n yield "http://localhost:5000"\n else:\n requests = pytest.importorskip("requests")\n pytest.importorskip("moto")\n pytest.importorskip("flask") # server mode needs flask too\n\n # Launching moto in server mode, i.e., as a separate process\n # with an S3 endpoint on localhost\n\n worker_id = "5" if worker_id == "master" else worker_id.lstrip("gw")\n endpoint_port = f"555{worker_id}"\n endpoint_uri = f"http://127.0.0.1:{endpoint_port}/"\n\n # pipe to null to avoid logging in terminal\n with subprocess.Popen(\n shlex.split(f"moto_server s3 -p {endpoint_port}"),\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n ) as proc:\n timeout = 5\n while timeout > 0:\n try:\n # OK to go once server is accepting connections\n r = requests.get(endpoint_uri)\n if r.ok:\n break\n except Exception:\n pass\n timeout -= 0.1\n time.sleep(0.1)\n yield endpoint_uri\n\n proc.terminate()\n\n\n@pytest.fixture\ndef s3so(s3_base):\n return {"client_kwargs": {"endpoint_url": s3_base}}\n\n\n@pytest.fixture\ndef s3_resource(s3_base):\n import boto3\n\n s3 = boto3.resource("s3", endpoint_url=s3_base)\n return s3\n\n\n@pytest.fixture\ndef s3_public_bucket(s3_resource):\n bucket = s3_resource.Bucket(f"pandas-test-{uuid.uuid4()}")\n bucket.create()\n yield bucket\n bucket.objects.delete()\n bucket.delete()\n\n\n@pytest.fixture\ndef s3_public_bucket_with_data(\n s3_public_bucket, tips_file, jsonl_file, feather_file, xml_file\n):\n """\n The following datasets\n are loaded.\n\n - tips.csv\n - tips.csv.gz\n - tips.csv.bz2\n - items.jsonl\n """\n test_s3_files = [\n ("tips#1.csv", tips_file),\n ("tips.csv", tips_file),\n ("tips.csv.gz", tips_file + ".gz"),\n ("tips.csv.bz2", tips_file + ".bz2"),\n ("items.jsonl", jsonl_file),\n ("simple_dataset.feather", feather_file),\n ("books.xml", xml_file),\n ]\n for s3_key, file_name in test_s3_files:\n with open(file_name, "rb") as f:\n s3_public_bucket.put_object(Key=s3_key, Body=f)\n return s3_public_bucket\n\n\n@pytest.fixture\ndef s3_private_bucket(s3_resource):\n bucket = s3_resource.Bucket(f"cant_get_it-{uuid.uuid4()}")\n bucket.create(ACL="private")\n yield bucket\n bucket.objects.delete()\n bucket.delete()\n\n\n@pytest.fixture\ndef s3_private_bucket_with_data(\n s3_private_bucket, tips_file, jsonl_file, feather_file, xml_file\n):\n """\n The following datasets\n are loaded.\n\n - tips.csv\n - tips.csv.gz\n - tips.csv.bz2\n - items.jsonl\n """\n test_s3_files = [\n ("tips#1.csv", tips_file),\n ("tips.csv", tips_file),\n ("tips.csv.gz", tips_file + ".gz"),\n ("tips.csv.bz2", tips_file + ".bz2"),\n ("items.jsonl", jsonl_file),\n ("simple_dataset.feather", feather_file),\n ("books.xml", xml_file),\n ]\n for s3_key, file_name in test_s3_files:\n with open(file_name, "rb") as f:\n s3_private_bucket.put_object(Key=s3_key, Body=f)\n return s3_private_bucket\n\n\n_compression_formats_params = [\n (".no_compress", None),\n ("", None),\n (".gz", "gzip"),\n (".GZ", "gzip"),\n (".bz2", "bz2"),\n (".BZ2", "bz2"),\n (".zip", "zip"),\n (".ZIP", "zip"),\n (".xz", "xz"),\n (".XZ", "xz"),\n pytest.param((".zst", "zstd"), marks=td.skip_if_no("zstandard")),\n pytest.param((".ZST", "zstd"), marks=td.skip_if_no("zstandard")),\n]\n\n\n@pytest.fixture(params=_compression_formats_params[1:])\ndef compression_format(request):\n return request.param\n\n\n@pytest.fixture(params=_compression_formats_params)\ndef compression_ext(request):\n return request.param[0]\n
.venv\Lib\site-packages\pandas\tests\io\conftest.py
conftest.py
Python
6,041
0.95
0.124444
0.060773
python-kit
108
2023-10-08T13:22:48.917930
MIT
true
5433baff48fa0ef0b01633a59a658cef
"""\nself-contained to write legacy storage pickle files\n\nTo use this script. Create an environment where you want\ngenerate pickles, say its for 0.20.3, with your pandas clone\nin ~/pandas\n\n. activate pandas_0.20.3\ncd ~/pandas/pandas\n\n$ python -m tests.io.generate_legacy_storage_files \\n tests/io/data/legacy_pickle/0.20.3/ pickle\n\nThis script generates a storage file for the current arch, system,\nand python version\n pandas version: 0.20.3\n output dir : pandas/pandas/tests/io/data/legacy_pickle/0.20.3/\n storage format: pickle\ncreated pickle file: 0.20.3_x86_64_darwin_3.5.2.pickle\n\nThe idea here is you are using the *current* version of the\ngenerate_legacy_storage_files with an *older* version of pandas to\ngenerate a pickle file. We will then check this file into a current\nbranch, and test using test_pickle.py. This will load the *older*\npickles and test versus the current data that is generated\n(with main). These are then compared.\n\nIf we have cases where we changed the signature (e.g. we renamed\noffset -> freq in Timestamp). Then we have to conditionally execute\nin the generate_legacy_storage_files.py to make it\nrun under the older AND the newer version.\n\n"""\n\nfrom datetime import timedelta\nimport os\nimport pickle\nimport platform as pl\nimport sys\n\n# Remove script directory from path, otherwise Python will try to\n# import the JSON test directory as the json module\nsys.path.pop(0)\n\nimport numpy as np\n\nimport pandas\nfrom pandas import (\n Categorical,\n DataFrame,\n Index,\n MultiIndex,\n NaT,\n Period,\n RangeIndex,\n Series,\n Timestamp,\n bdate_range,\n date_range,\n interval_range,\n period_range,\n timedelta_range,\n)\nfrom pandas.arrays import SparseArray\n\nfrom pandas.tseries.offsets import (\n FY5253,\n BusinessDay,\n BusinessHour,\n CustomBusinessDay,\n DateOffset,\n Day,\n Easter,\n Hour,\n LastWeekOfMonth,\n Minute,\n MonthBegin,\n MonthEnd,\n QuarterBegin,\n QuarterEnd,\n SemiMonthBegin,\n SemiMonthEnd,\n Week,\n WeekOfMonth,\n YearBegin,\n YearEnd,\n)\n\n\ndef _create_sp_series():\n nan = np.nan\n\n # nan-based\n arr = np.arange(15, dtype=np.float64)\n arr[7:12] = nan\n arr[-1:] = nan\n\n bseries = Series(SparseArray(arr, kind="block"))\n bseries.name = "bseries"\n return bseries\n\n\ndef _create_sp_tsseries():\n nan = np.nan\n\n # nan-based\n arr = np.arange(15, dtype=np.float64)\n arr[7:12] = nan\n arr[-1:] = nan\n\n date_index = bdate_range("1/1/2011", periods=len(arr))\n bseries = Series(SparseArray(arr, kind="block"), index=date_index)\n bseries.name = "btsseries"\n return bseries\n\n\ndef _create_sp_frame():\n nan = np.nan\n\n data = {\n "A": [nan, nan, nan, 0, 1, 2, 3, 4, 5, 6],\n "B": [0, 1, 2, nan, nan, nan, 3, 4, 5, 6],\n "C": np.arange(10).astype(np.int64),\n "D": [0, 1, 2, 3, 4, 5, nan, nan, nan, nan],\n }\n\n dates = bdate_range("1/1/2011", periods=10)\n return DataFrame(data, index=dates).apply(SparseArray)\n\n\ndef create_pickle_data():\n """create the pickle data"""\n data = {\n "A": [0.0, 1.0, 2.0, 3.0, np.nan],\n "B": [0, 1, 0, 1, 0],\n "C": ["foo1", "foo2", "foo3", "foo4", "foo5"],\n "D": date_range("1/1/2009", periods=5),\n "E": [0.0, 1, Timestamp("20100101"), "foo", 2.0],\n }\n\n scalars = {"timestamp": Timestamp("20130101"), "period": Period("2012", "M")}\n\n index = {\n "int": Index(np.arange(10)),\n "date": date_range("20130101", periods=10),\n "period": period_range("2013-01-01", freq="M", periods=10),\n "float": Index(np.arange(10, dtype=np.float64)),\n "uint": Index(np.arange(10, dtype=np.uint64)),\n "timedelta": timedelta_range("00:00:00", freq="30min", periods=10),\n }\n\n index["range"] = RangeIndex(10)\n\n index["interval"] = interval_range(0, periods=10)\n\n mi = {\n "reg2": MultiIndex.from_tuples(\n tuple(\n zip(\n *[\n ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n )\n ),\n names=["first", "second"],\n )\n }\n\n series = {\n "float": Series(data["A"]),\n "int": Series(data["B"]),\n "mixed": Series(data["E"]),\n "ts": Series(\n np.arange(10).astype(np.int64), index=date_range("20130101", periods=10)\n ),\n "mi": Series(\n np.arange(5).astype(np.float64),\n index=MultiIndex.from_tuples(\n tuple(zip(*[[1, 1, 2, 2, 2], [3, 4, 3, 4, 5]])), names=["one", "two"]\n ),\n ),\n "dup": Series(np.arange(5).astype(np.float64), index=["A", "B", "C", "D", "A"]),\n "cat": Series(Categorical(["foo", "bar", "baz"])),\n "dt": Series(date_range("20130101", periods=5)),\n "dt_tz": Series(date_range("20130101", periods=5, tz="US/Eastern")),\n "period": Series([Period("2000Q1")] * 5),\n }\n\n mixed_dup_df = DataFrame(data)\n mixed_dup_df.columns = list("ABCDA")\n frame = {\n "float": DataFrame({"A": series["float"], "B": series["float"] + 1}),\n "int": DataFrame({"A": series["int"], "B": series["int"] + 1}),\n "mixed": DataFrame({k: data[k] for k in ["A", "B", "C", "D"]}),\n "mi": DataFrame(\n {"A": np.arange(5).astype(np.float64), "B": np.arange(5).astype(np.int64)},\n index=MultiIndex.from_tuples(\n tuple(\n zip(\n *[\n ["bar", "bar", "baz", "baz", "baz"],\n ["one", "two", "one", "two", "three"],\n ]\n )\n ),\n names=["first", "second"],\n ),\n ),\n "dup": DataFrame(\n np.arange(15).reshape(5, 3).astype(np.float64), columns=["A", "B", "A"]\n ),\n "cat_onecol": DataFrame({"A": Categorical(["foo", "bar"])}),\n "cat_and_float": DataFrame(\n {\n "A": Categorical(["foo", "bar", "baz"]),\n "B": np.arange(3).astype(np.int64),\n }\n ),\n "mixed_dup": mixed_dup_df,\n "dt_mixed_tzs": DataFrame(\n {\n "A": Timestamp("20130102", tz="US/Eastern"),\n "B": Timestamp("20130603", tz="CET"),\n },\n index=range(5),\n ),\n "dt_mixed2_tzs": DataFrame(\n {\n "A": Timestamp("20130102", tz="US/Eastern"),\n "B": Timestamp("20130603", tz="CET"),\n "C": Timestamp("20130603", tz="UTC"),\n },\n index=range(5),\n ),\n }\n\n cat = {\n "int8": Categorical(list("abcdefg")),\n "int16": Categorical(np.arange(1000)),\n "int32": Categorical(np.arange(10000)),\n }\n\n timestamp = {\n "normal": Timestamp("2011-01-01"),\n "nat": NaT,\n "tz": Timestamp("2011-01-01", tz="US/Eastern"),\n }\n\n off = {\n "DateOffset": DateOffset(years=1),\n "DateOffset_h_ns": DateOffset(hour=6, nanoseconds=5824),\n "BusinessDay": BusinessDay(offset=timedelta(seconds=9)),\n "BusinessHour": BusinessHour(normalize=True, n=6, end="15:14"),\n "CustomBusinessDay": CustomBusinessDay(weekmask="Mon Fri"),\n "SemiMonthBegin": SemiMonthBegin(day_of_month=9),\n "SemiMonthEnd": SemiMonthEnd(day_of_month=24),\n "MonthBegin": MonthBegin(1),\n "MonthEnd": MonthEnd(1),\n "QuarterBegin": QuarterBegin(1),\n "QuarterEnd": QuarterEnd(1),\n "Day": Day(1),\n "YearBegin": YearBegin(1),\n "YearEnd": YearEnd(1),\n "Week": Week(1),\n "Week_Tues": Week(2, normalize=False, weekday=1),\n "WeekOfMonth": WeekOfMonth(week=3, weekday=4),\n "LastWeekOfMonth": LastWeekOfMonth(n=1, weekday=3),\n "FY5253": FY5253(n=2, weekday=6, startingMonth=7, variation="last"),\n "Easter": Easter(),\n "Hour": Hour(1),\n "Minute": Minute(1),\n }\n\n return {\n "series": series,\n "frame": frame,\n "index": index,\n "scalars": scalars,\n "mi": mi,\n "sp_series": {"float": _create_sp_series(), "ts": _create_sp_tsseries()},\n "sp_frame": {"float": _create_sp_frame()},\n "cat": cat,\n "timestamp": timestamp,\n "offsets": off,\n }\n\n\ndef platform_name():\n return "_".join(\n [\n str(pandas.__version__),\n str(pl.machine()),\n str(pl.system().lower()),\n str(pl.python_version()),\n ]\n )\n\n\ndef write_legacy_pickles(output_dir):\n version = pandas.__version__\n\n print(\n "This script generates a storage file for the current arch, system, "\n "and python version"\n )\n print(f" pandas version: {version}")\n print(f" output dir : {output_dir}")\n print(" storage format: pickle")\n\n pth = f"{platform_name()}.pickle"\n\n with open(os.path.join(output_dir, pth), "wb") as fh:\n pickle.dump(create_pickle_data(), fh, pickle.DEFAULT_PROTOCOL)\n\n print(f"created pickle file: {pth}")\n\n\ndef write_legacy_file():\n # force our cwd to be the first searched\n sys.path.insert(0, "")\n\n if not 3 <= len(sys.argv) <= 4:\n sys.exit(\n "Specify output directory and storage type: generate_legacy_"\n "storage_files.py <output_dir> <storage_type> "\n )\n\n output_dir = str(sys.argv[1])\n storage_type = str(sys.argv[2])\n\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n\n if storage_type == "pickle":\n write_legacy_pickles(output_dir=output_dir)\n else:\n sys.exit("storage_type must be one of {'pickle'}")\n\n\nif __name__ == "__main__":\n write_legacy_file()\n
.venv\Lib\site-packages\pandas\tests\io\generate_legacy_storage_files.py
generate_legacy_storage_files.py
Python
9,853
0.95
0.046784
0.024221
vue-tools
833
2024-02-16T04:48:20.495634
GPL-3.0
true
76d87c20538e7d5546cece303876eaf2
from textwrap import dedent\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import (\n PyperclipException,\n PyperclipWindowsException,\n)\n\nimport pandas as pd\nfrom pandas import (\n NA,\n DataFrame,\n Series,\n get_option,\n read_clipboard,\n)\nimport pandas._testing as tm\n\nfrom pandas.io.clipboard import (\n CheckedCall,\n _stringifyText,\n init_qt_clipboard,\n)\n\n\ndef build_kwargs(sep, excel):\n kwargs = {}\n if excel != "default":\n kwargs["excel"] = excel\n if sep != "default":\n kwargs["sep"] = sep\n return kwargs\n\n\n@pytest.fixture(\n params=[\n "delims",\n "utf8",\n "utf16",\n "string",\n "long",\n "nonascii",\n "colwidth",\n "mixed",\n "float",\n "int",\n ]\n)\ndef df(request):\n data_type = request.param\n\n if data_type == "delims":\n return DataFrame({"a": ['"a,\t"b|c', "d\tef`"], "b": ["hi'j", "k''lm"]})\n elif data_type == "utf8":\n return DataFrame({"a": ["µasd", "Ωœ∑`"], "b": ["øπ∆˚¬", "œ∑`®"]})\n elif data_type == "utf16":\n return DataFrame(\n {"a": ["\U0001f44d\U0001f44d", "\U0001f44d\U0001f44d"], "b": ["abc", "def"]}\n )\n elif data_type == "string":\n return DataFrame(\n np.array([f"i-{i}" for i in range(15)]).reshape(5, 3), columns=list("abc")\n )\n elif data_type == "long":\n max_rows = get_option("display.max_rows")\n return DataFrame(\n np.random.default_rng(2).integers(0, 10, size=(max_rows + 1, 3)),\n columns=list("abc"),\n )\n elif data_type == "nonascii":\n return DataFrame({"en": "in English".split(), "es": "en español".split()})\n elif data_type == "colwidth":\n _cw = get_option("display.max_colwidth") + 1\n return DataFrame(\n np.array(["x" * _cw for _ in range(15)]).reshape(5, 3), columns=list("abc")\n )\n elif data_type == "mixed":\n return DataFrame(\n {\n "a": np.arange(1.0, 6.0) + 0.01,\n "b": np.arange(1, 6).astype(np.int64),\n "c": list("abcde"),\n }\n )\n elif data_type == "float":\n return DataFrame(np.random.default_rng(2).random((5, 3)), columns=list("abc"))\n elif data_type == "int":\n return DataFrame(\n np.random.default_rng(2).integers(0, 10, (5, 3)), columns=list("abc")\n )\n else:\n raise ValueError\n\n\n@pytest.fixture\ndef mock_ctypes(monkeypatch):\n """\n Mocks WinError to help with testing the clipboard.\n """\n\n def _mock_win_error():\n return "Window Error"\n\n # Set raising to False because WinError won't exist on non-windows platforms\n with monkeypatch.context() as m:\n m.setattr("ctypes.WinError", _mock_win_error, raising=False)\n yield\n\n\n@pytest.mark.usefixtures("mock_ctypes")\ndef test_checked_call_with_bad_call(monkeypatch):\n """\n Give CheckCall a function that returns a falsey value and\n mock get_errno so it returns false so an exception is raised.\n """\n\n def _return_false():\n return False\n\n monkeypatch.setattr("pandas.io.clipboard.get_errno", lambda: True)\n msg = f"Error calling {_return_false.__name__} \\(Window Error\\)"\n\n with pytest.raises(PyperclipWindowsException, match=msg):\n CheckedCall(_return_false)()\n\n\n@pytest.mark.usefixtures("mock_ctypes")\ndef test_checked_call_with_valid_call(monkeypatch):\n """\n Give CheckCall a function that returns a truthy value and\n mock get_errno so it returns true so an exception is not raised.\n The function should return the results from _return_true.\n """\n\n def _return_true():\n return True\n\n monkeypatch.setattr("pandas.io.clipboard.get_errno", lambda: False)\n\n # Give CheckedCall a callable that returns a truthy value s\n checked_call = CheckedCall(_return_true)\n assert checked_call() is True\n\n\n@pytest.mark.parametrize(\n "text",\n [\n "String_test",\n True,\n 1,\n 1.0,\n 1j,\n ],\n)\ndef test_stringify_text(text):\n valid_types = (str, int, float, bool)\n\n if isinstance(text, valid_types):\n result = _stringifyText(text)\n assert result == str(text)\n else:\n msg = (\n "only str, int, float, and bool values "\n f"can be copied to the clipboard, not {type(text).__name__}"\n )\n with pytest.raises(PyperclipException, match=msg):\n _stringifyText(text)\n\n\n@pytest.fixture\ndef set_pyqt_clipboard(monkeypatch):\n qt_cut, qt_paste = init_qt_clipboard()\n with monkeypatch.context() as m:\n m.setattr(pd.io.clipboard, "clipboard_set", qt_cut)\n m.setattr(pd.io.clipboard, "clipboard_get", qt_paste)\n yield\n\n\n@pytest.fixture\ndef clipboard(qapp):\n clip = qapp.clipboard()\n yield clip\n clip.clear()\n\n\n@pytest.mark.single_cpu\n@pytest.mark.clipboard\n@pytest.mark.usefixtures("set_pyqt_clipboard")\n@pytest.mark.usefixtures("clipboard")\nclass TestClipboard:\n # Test that default arguments copy as tab delimited\n # Test that explicit delimiters are respected\n @pytest.mark.parametrize("sep", [None, "\t", ",", "|"])\n @pytest.mark.parametrize("encoding", [None, "UTF-8", "utf-8", "utf8"])\n def test_round_trip_frame_sep(self, df, sep, encoding):\n df.to_clipboard(excel=None, sep=sep, encoding=encoding)\n result = read_clipboard(sep=sep or "\t", index_col=0, encoding=encoding)\n tm.assert_frame_equal(df, result)\n\n # Test white space separator\n def test_round_trip_frame_string(self, df):\n df.to_clipboard(excel=False, sep=None)\n result = read_clipboard()\n assert df.to_string() == result.to_string()\n assert df.shape == result.shape\n\n # Two character separator is not supported in to_clipboard\n # Test that multi-character separators are not silently passed\n def test_excel_sep_warning(self, df):\n with tm.assert_produces_warning(\n UserWarning,\n match="to_clipboard in excel mode requires a single character separator.",\n check_stacklevel=False,\n ):\n df.to_clipboard(excel=True, sep=r"\t")\n\n # Separator is ignored when excel=False and should produce a warning\n def test_copy_delim_warning(self, df):\n with tm.assert_produces_warning():\n df.to_clipboard(excel=False, sep="\t")\n\n # Tests that the default behavior of to_clipboard is tab\n # delimited and excel="True"\n @pytest.mark.parametrize("sep", ["\t", None, "default"])\n @pytest.mark.parametrize("excel", [True, None, "default"])\n def test_clipboard_copy_tabs_default(self, sep, excel, df, clipboard):\n kwargs = build_kwargs(sep, excel)\n df.to_clipboard(**kwargs)\n assert clipboard.text() == df.to_csv(sep="\t")\n\n # Tests reading of white space separated tables\n @pytest.mark.parametrize("sep", [None, "default"])\n def test_clipboard_copy_strings(self, sep, df):\n kwargs = build_kwargs(sep, False)\n df.to_clipboard(**kwargs)\n result = read_clipboard(sep=r"\s+")\n assert result.to_string() == df.to_string()\n assert df.shape == result.shape\n\n def test_read_clipboard_infer_excel(self, clipboard):\n # gh-19010: avoid warnings\n clip_kwargs = {"engine": "python"}\n\n text = dedent(\n """\n John James\tCharlie Mingus\n 1\t2\n 4\tHarry Carney\n """.strip()\n )\n clipboard.setText(text)\n df = read_clipboard(**clip_kwargs)\n\n # excel data is parsed correctly\n assert df.iloc[1, 1] == "Harry Carney"\n\n # having diff tab counts doesn't trigger it\n text = dedent(\n """\n a\t b\n 1 2\n 3 4\n """.strip()\n )\n clipboard.setText(text)\n res = read_clipboard(**clip_kwargs)\n\n text = dedent(\n """\n a b\n 1 2\n 3 4\n """.strip()\n )\n clipboard.setText(text)\n exp = read_clipboard(**clip_kwargs)\n\n tm.assert_frame_equal(res, exp)\n\n def test_infer_excel_with_nulls(self, clipboard):\n # GH41108\n text = "col1\tcol2\n1\tred\n\tblue\n2\tgreen"\n\n clipboard.setText(text)\n df = read_clipboard()\n df_expected = DataFrame(\n data={"col1": [1, None, 2], "col2": ["red", "blue", "green"]}\n )\n\n # excel data is parsed correctly\n tm.assert_frame_equal(df, df_expected)\n\n @pytest.mark.parametrize(\n "multiindex",\n [\n ( # Can't use `dedent` here as it will remove the leading `\t`\n "\n".join(\n [\n "\t\t\tcol1\tcol2",\n "A\t0\tTrue\t1\tred",\n "A\t1\tTrue\t\tblue",\n "B\t0\tFalse\t2\tgreen",\n ]\n ),\n [["A", "A", "B"], [0, 1, 0], [True, True, False]],\n ),\n (\n "\n".join(\n ["\t\tcol1\tcol2", "A\t0\t1\tred", "A\t1\t\tblue", "B\t0\t2\tgreen"]\n ),\n [["A", "A", "B"], [0, 1, 0]],\n ),\n ],\n )\n def test_infer_excel_with_multiindex(self, clipboard, multiindex):\n # GH41108\n\n clipboard.setText(multiindex[0])\n df = read_clipboard()\n df_expected = DataFrame(\n data={"col1": [1, None, 2], "col2": ["red", "blue", "green"]},\n index=multiindex[1],\n )\n\n # excel data is parsed correctly\n tm.assert_frame_equal(df, df_expected)\n\n def test_invalid_encoding(self, df):\n msg = "clipboard only supports utf-8 encoding"\n # test case for testing invalid encoding\n with pytest.raises(ValueError, match=msg):\n df.to_clipboard(encoding="ascii")\n with pytest.raises(NotImplementedError, match=msg):\n read_clipboard(encoding="ascii")\n\n @pytest.mark.parametrize("data", ["\U0001f44d...", "Ωœ∑`...", "abcd..."])\n def test_raw_roundtrip(self, data):\n # PR #25040 wide unicode wasn't copied correctly on PY3 on windows\n df = DataFrame({"data": [data]})\n df.to_clipboard()\n result = read_clipboard()\n tm.assert_frame_equal(df, result)\n\n @pytest.mark.parametrize("engine", ["c", "python"])\n def test_read_clipboard_dtype_backend(\n self, clipboard, string_storage, dtype_backend, engine, using_infer_string\n ):\n # GH#50502\n if dtype_backend == "pyarrow":\n pa = pytest.importorskip("pyarrow")\n if engine == "c" and string_storage == "pyarrow":\n # TODO avoid this exception?\n string_dtype = pd.ArrowDtype(pa.large_string())\n else:\n string_dtype = pd.ArrowDtype(pa.string())\n else:\n string_dtype = pd.StringDtype(string_storage)\n\n text = """a,b,c,d,e,f,g,h,i\nx,1,4.0,x,2,4.0,,True,False\ny,2,5.0,,,,,False,"""\n clipboard.setText(text)\n\n with pd.option_context("mode.string_storage", string_storage):\n result = read_clipboard(sep=",", dtype_backend=dtype_backend, engine=engine)\n\n expected = DataFrame(\n {\n "a": Series(["x", "y"], dtype=string_dtype),\n "b": Series([1, 2], dtype="Int64"),\n "c": Series([4.0, 5.0], dtype="Float64"),\n "d": Series(["x", None], dtype=string_dtype),\n "e": Series([2, NA], dtype="Int64"),\n "f": Series([4.0, NA], dtype="Float64"),\n "g": Series([NA, NA], dtype="Int64"),\n "h": Series([True, False], dtype="boolean"),\n "i": Series([False, NA], dtype="boolean"),\n }\n )\n if dtype_backend == "pyarrow":\n from pandas.arrays import ArrowExtensionArray\n\n expected = DataFrame(\n {\n col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))\n for col in expected.columns\n }\n )\n expected["g"] = ArrowExtensionArray(pa.array([None, None]))\n\n if using_infer_string:\n expected.columns = expected.columns.astype(\n pd.StringDtype(string_storage, na_value=np.nan)\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_invalid_dtype_backend(self):\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 read_clipboard(dtype_backend="numpy")\n\n def test_to_clipboard_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_clipboard "\n r"will be keyword-only."\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n df.to_clipboard(True, None)\n
.venv\Lib\site-packages\pandas\tests\io\test_clipboard.py
test_clipboard.py
Python
13,092
0.95
0.100962
0.064607
awesome-app
601
2025-02-06T00:20:46.481833
MIT
true
5704dfbd7d9d3cdac544a4fba517ba8c
"""\nTests for the pandas.io.common functionalities\n"""\nimport codecs\nimport errno\nfrom functools import partial\nfrom io import (\n BytesIO,\n StringIO,\n UnsupportedOperation,\n)\nimport mmap\nimport os\nfrom pathlib import Path\nimport pickle\nimport tempfile\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\nfrom pandas.compat.pyarrow import pa_version_under19p0\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nimport pandas._testing as tm\n\nimport pandas.io.common as icom\n\npytestmark = pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n)\n\n\nclass CustomFSPath:\n """For testing fspath on unknown objects"""\n\n def __init__(self, path) -> None:\n self.path = path\n\n def __fspath__(self):\n return self.path\n\n\n# Functions that consume a string path and return a string or path-like object\npath_types = [str, CustomFSPath, Path]\n\ntry:\n from py.path import local as LocalPath\n\n path_types.append(LocalPath)\nexcept ImportError:\n pass\n\nHERE = os.path.abspath(os.path.dirname(__file__))\n\n\n# https://github.com/cython/cython/issues/1720\nclass TestCommonIOCapabilities:\n data1 = """index,A,B,C,D\nfoo,2,3,4,5\nbar,7,8,9,10\nbaz,12,13,14,15\nqux,12,13,14,15\nfoo2,12,13,14,15\nbar2,12,13,14,15\n"""\n\n def test_expand_user(self):\n filename = "~/sometest"\n expanded_name = icom._expand_user(filename)\n\n assert expanded_name != filename\n assert os.path.isabs(expanded_name)\n assert os.path.expanduser(filename) == expanded_name\n\n def test_expand_user_normal_path(self):\n filename = "/somefolder/sometest"\n expanded_name = icom._expand_user(filename)\n\n assert expanded_name == filename\n assert os.path.expanduser(filename) == expanded_name\n\n def test_stringify_path_pathlib(self):\n rel_path = icom.stringify_path(Path("."))\n assert rel_path == "."\n redundant_path = icom.stringify_path(Path("foo//bar"))\n assert redundant_path == os.path.join("foo", "bar")\n\n @td.skip_if_no("py.path")\n def test_stringify_path_localpath(self):\n path = os.path.join("foo", "bar")\n abs_path = os.path.abspath(path)\n lpath = LocalPath(path)\n assert icom.stringify_path(lpath) == abs_path\n\n def test_stringify_path_fspath(self):\n p = CustomFSPath("foo/bar.csv")\n result = icom.stringify_path(p)\n assert result == "foo/bar.csv"\n\n def test_stringify_file_and_path_like(self):\n # GH 38125: do not stringify file objects that are also path-like\n fsspec = pytest.importorskip("fsspec")\n with tm.ensure_clean() as path:\n with fsspec.open(f"file://{path}", mode="wb") as fsspec_obj:\n assert fsspec_obj == icom.stringify_path(fsspec_obj)\n\n @pytest.mark.parametrize("path_type", path_types)\n def test_infer_compression_from_path(self, compression_format, path_type):\n extension, expected = compression_format\n path = path_type("foo/bar.csv" + extension)\n compression = icom.infer_compression(path, compression="infer")\n assert compression == expected\n\n @pytest.mark.parametrize("path_type", [str, CustomFSPath, Path])\n def test_get_handle_with_path(self, path_type):\n # ignore LocalPath: it creates strange paths: /absolute/~/sometest\n with tempfile.TemporaryDirectory(dir=Path.home()) as tmp:\n filename = path_type("~/" + Path(tmp).name + "/sometest")\n with icom.get_handle(filename, "w") as handles:\n assert Path(handles.handle.name).is_absolute()\n assert os.path.expanduser(filename) == handles.handle.name\n\n def test_get_handle_with_buffer(self):\n with StringIO() as input_buffer:\n with icom.get_handle(input_buffer, "r") as handles:\n assert handles.handle == input_buffer\n assert not input_buffer.closed\n assert input_buffer.closed\n\n # Test that BytesIOWrapper(get_handle) returns correct amount of bytes every time\n def test_bytesiowrapper_returns_correct_bytes(self):\n # Test latin1, ucs-2, and ucs-4 chars\n data = """a,b,c\n1,2,3\n©,®,®\nLook,a snake,🐍"""\n with icom.get_handle(StringIO(data), "rb", is_text=False) as handles:\n result = b""\n chunksize = 5\n while True:\n chunk = handles.handle.read(chunksize)\n # Make sure each chunk is correct amount of bytes\n assert len(chunk) <= chunksize\n if len(chunk) < chunksize:\n # Can be less amount of bytes, but only at EOF\n # which happens when read returns empty\n assert len(handles.handle.read()) == 0\n result += chunk\n break\n result += chunk\n assert result == data.encode("utf-8")\n\n # Test that pyarrow can handle a file opened with get_handle\n def test_get_handle_pyarrow_compat(self):\n pa_csv = pytest.importorskip("pyarrow.csv")\n\n # Test latin1, ucs-2, and ucs-4 chars\n data = """a,b,c\n1,2,3\n©,®,®\nLook,a snake,🐍"""\n expected = pd.DataFrame(\n {"a": ["1", "©", "Look"], "b": ["2", "®", "a snake"], "c": ["3", "®", "🐍"]}\n )\n s = StringIO(data)\n with icom.get_handle(s, "rb", is_text=False) as handles:\n df = pa_csv.read_csv(handles.handle).to_pandas()\n if pa_version_under19p0:\n expected = expected.astype("object")\n tm.assert_frame_equal(df, expected)\n assert not s.closed\n\n def test_iterator(self):\n with pd.read_csv(StringIO(self.data1), chunksize=1) as reader:\n result = pd.concat(reader, ignore_index=True)\n expected = pd.read_csv(StringIO(self.data1))\n tm.assert_frame_equal(result, expected)\n\n # GH12153\n with pd.read_csv(StringIO(self.data1), chunksize=1) as it:\n first = next(it)\n tm.assert_frame_equal(first, expected.iloc[[0]])\n tm.assert_frame_equal(pd.concat(it), expected.iloc[1:])\n\n @pytest.mark.parametrize(\n "reader, module, error_class, fn_ext",\n [\n (pd.read_csv, "os", FileNotFoundError, "csv"),\n (pd.read_fwf, "os", FileNotFoundError, "txt"),\n (pd.read_excel, "xlrd", FileNotFoundError, "xlsx"),\n (pd.read_feather, "pyarrow", OSError, "feather"),\n (pd.read_hdf, "tables", FileNotFoundError, "h5"),\n (pd.read_stata, "os", FileNotFoundError, "dta"),\n (pd.read_sas, "os", FileNotFoundError, "sas7bdat"),\n (pd.read_json, "os", FileNotFoundError, "json"),\n (pd.read_pickle, "os", FileNotFoundError, "pickle"),\n ],\n )\n def test_read_non_existent(self, reader, module, error_class, fn_ext):\n pytest.importorskip(module)\n\n path = os.path.join(HERE, "data", "does_not_exist." + fn_ext)\n msg1 = rf"File (b')?.+does_not_exist\.{fn_ext}'? does not exist"\n msg2 = rf"\[Errno 2\] No such file or directory: '.+does_not_exist\.{fn_ext}'"\n msg3 = "Expected object or value"\n msg4 = "path_or_buf needs to be a string file path or file-like"\n msg5 = (\n rf"\[Errno 2\] File .+does_not_exist\.{fn_ext} does not exist: "\n rf"'.+does_not_exist\.{fn_ext}'"\n )\n msg6 = rf"\[Errno 2\] 没有那个文件或目录: '.+does_not_exist\.{fn_ext}'"\n msg7 = (\n rf"\[Errno 2\] File o directory non esistente: '.+does_not_exist\.{fn_ext}'"\n )\n msg8 = rf"Failed to open local file.+does_not_exist\.{fn_ext}"\n\n with pytest.raises(\n error_class,\n match=rf"({msg1}|{msg2}|{msg3}|{msg4}|{msg5}|{msg6}|{msg7}|{msg8})",\n ):\n reader(path)\n\n @pytest.mark.parametrize(\n "method, module, error_class, fn_ext",\n [\n (pd.DataFrame.to_csv, "os", OSError, "csv"),\n (pd.DataFrame.to_html, "os", OSError, "html"),\n (pd.DataFrame.to_excel, "xlrd", OSError, "xlsx"),\n (pd.DataFrame.to_feather, "pyarrow", OSError, "feather"),\n (pd.DataFrame.to_parquet, "pyarrow", OSError, "parquet"),\n (pd.DataFrame.to_stata, "os", OSError, "dta"),\n (pd.DataFrame.to_json, "os", OSError, "json"),\n (pd.DataFrame.to_pickle, "os", OSError, "pickle"),\n ],\n )\n # NOTE: Missing parent directory for pd.DataFrame.to_hdf is handled by PyTables\n def test_write_missing_parent_directory(self, method, module, error_class, fn_ext):\n pytest.importorskip(module)\n\n dummy_frame = pd.DataFrame({"a": [1, 2, 3], "b": [2, 3, 4], "c": [3, 4, 5]})\n\n path = os.path.join(HERE, "data", "missing_folder", "does_not_exist." + fn_ext)\n\n with pytest.raises(\n error_class,\n match=r"Cannot save file into a non-existent directory: .*missing_folder",\n ):\n method(dummy_frame, path)\n\n @pytest.mark.parametrize(\n "reader, module, error_class, fn_ext",\n [\n (pd.read_csv, "os", FileNotFoundError, "csv"),\n (pd.read_table, "os", FileNotFoundError, "csv"),\n (pd.read_fwf, "os", FileNotFoundError, "txt"),\n (pd.read_excel, "xlrd", FileNotFoundError, "xlsx"),\n (pd.read_feather, "pyarrow", OSError, "feather"),\n (pd.read_hdf, "tables", FileNotFoundError, "h5"),\n (pd.read_stata, "os", FileNotFoundError, "dta"),\n (pd.read_sas, "os", FileNotFoundError, "sas7bdat"),\n (pd.read_json, "os", FileNotFoundError, "json"),\n (pd.read_pickle, "os", FileNotFoundError, "pickle"),\n ],\n )\n def test_read_expands_user_home_dir(\n self, reader, module, error_class, fn_ext, monkeypatch\n ):\n pytest.importorskip(module)\n\n path = os.path.join("~", "does_not_exist." + fn_ext)\n monkeypatch.setattr(icom, "_expand_user", lambda x: os.path.join("foo", x))\n\n msg1 = rf"File (b')?.+does_not_exist\.{fn_ext}'? does not exist"\n msg2 = rf"\[Errno 2\] No such file or directory: '.+does_not_exist\.{fn_ext}'"\n msg3 = "Unexpected character found when decoding 'false'"\n msg4 = "path_or_buf needs to be a string file path or file-like"\n msg5 = (\n rf"\[Errno 2\] File .+does_not_exist\.{fn_ext} does not exist: "\n rf"'.+does_not_exist\.{fn_ext}'"\n )\n msg6 = rf"\[Errno 2\] 没有那个文件或目录: '.+does_not_exist\.{fn_ext}'"\n msg7 = (\n rf"\[Errno 2\] File o directory non esistente: '.+does_not_exist\.{fn_ext}'"\n )\n msg8 = rf"Failed to open local file.+does_not_exist\.{fn_ext}"\n\n with pytest.raises(\n error_class,\n match=rf"({msg1}|{msg2}|{msg3}|{msg4}|{msg5}|{msg6}|{msg7}|{msg8})",\n ):\n reader(path)\n\n @pytest.mark.parametrize(\n "reader, module, path",\n [\n (pd.read_csv, "os", ("io", "data", "csv", "iris.csv")),\n (pd.read_table, "os", ("io", "data", "csv", "iris.csv")),\n (\n pd.read_fwf,\n "os",\n ("io", "data", "fixed_width", "fixed_width_format.txt"),\n ),\n (pd.read_excel, "xlrd", ("io", "data", "excel", "test1.xlsx")),\n (\n pd.read_feather,\n "pyarrow",\n ("io", "data", "feather", "feather-0_3_1.feather"),\n ),\n pytest.param(\n pd.read_hdf,\n "tables",\n ("io", "data", "legacy_hdf", "datetimetz_object.h5"),\n # cleaned-up in https://github.com/pandas-dev/pandas/pull/57387 on main\n marks=pytest.mark.xfail(reason="TODO(infer_string)", strict=False),\n ),\n (pd.read_stata, "os", ("io", "data", "stata", "stata10_115.dta")),\n (pd.read_sas, "os", ("io", "sas", "data", "test1.sas7bdat")),\n (pd.read_json, "os", ("io", "json", "data", "tsframe_v012.json")),\n (\n pd.read_pickle,\n "os",\n ("io", "data", "pickle", "categorical.0.25.0.pickle"),\n ),\n ],\n )\n def test_read_fspath_all(self, reader, module, path, datapath):\n pytest.importorskip(module)\n path = datapath(*path)\n\n mypath = CustomFSPath(path)\n result = reader(mypath)\n expected = reader(path)\n\n if path.endswith(".pickle"):\n # categorical\n tm.assert_categorical_equal(result, expected)\n else:\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "writer_name, writer_kwargs, module",\n [\n ("to_csv", {}, "os"),\n ("to_excel", {"engine": "openpyxl"}, "openpyxl"),\n ("to_feather", {}, "pyarrow"),\n ("to_html", {}, "os"),\n ("to_json", {}, "os"),\n ("to_latex", {}, "os"),\n ("to_pickle", {}, "os"),\n ("to_stata", {"time_stamp": pd.to_datetime("2019-01-01 00:00")}, "os"),\n ],\n )\n def test_write_fspath_all(self, writer_name, writer_kwargs, module):\n if writer_name in ["to_latex"]: # uses Styler implementation\n pytest.importorskip("jinja2")\n p1 = tm.ensure_clean("string")\n p2 = tm.ensure_clean("fspath")\n df = pd.DataFrame({"A": [1, 2]})\n\n with p1 as string, p2 as fspath:\n pytest.importorskip(module)\n mypath = CustomFSPath(fspath)\n writer = getattr(df, writer_name)\n\n writer(string, **writer_kwargs)\n writer(mypath, **writer_kwargs)\n with open(string, "rb") as f_str, open(fspath, "rb") as f_path:\n if writer_name == "to_excel":\n # binary representation of excel contains time creation\n # data that causes flaky CI failures\n result = pd.read_excel(f_str, **writer_kwargs)\n expected = pd.read_excel(f_path, **writer_kwargs)\n tm.assert_frame_equal(result, expected)\n else:\n result = f_str.read()\n expected = f_path.read()\n assert result == expected\n\n def test_write_fspath_hdf5(self):\n # Same test as write_fspath_all, except HDF5 files aren't\n # necessarily byte-for-byte identical for a given dataframe, so we'll\n # have to read and compare equality\n pytest.importorskip("tables")\n\n df = pd.DataFrame({"A": [1, 2]})\n p1 = tm.ensure_clean("string")\n p2 = tm.ensure_clean("fspath")\n\n with p1 as string, p2 as fspath:\n mypath = CustomFSPath(fspath)\n df.to_hdf(mypath, key="bar")\n df.to_hdf(string, key="bar")\n\n result = pd.read_hdf(fspath, key="bar")\n expected = pd.read_hdf(string, key="bar")\n\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.fixture\ndef mmap_file(datapath):\n return datapath("io", "data", "csv", "test_mmap.csv")\n\n\nclass TestMMapWrapper:\n def test_constructor_bad_file(self, mmap_file):\n non_file = StringIO("I am not a file")\n non_file.fileno = lambda: -1\n\n # the error raised is different on Windows\n if is_platform_windows():\n msg = "The parameter is incorrect"\n err = OSError\n else:\n msg = "[Errno 22]"\n err = mmap.error\n\n with pytest.raises(err, match=msg):\n icom._maybe_memory_map(non_file, True)\n\n with open(mmap_file, encoding="utf-8") as target:\n pass\n\n msg = "I/O operation on closed file"\n with pytest.raises(ValueError, match=msg):\n icom._maybe_memory_map(target, True)\n\n def test_next(self, mmap_file):\n with open(mmap_file, encoding="utf-8") as target:\n lines = target.readlines()\n\n with icom.get_handle(\n target, "r", is_text=True, memory_map=True\n ) as wrappers:\n wrapper = wrappers.handle\n assert isinstance(wrapper.buffer.buffer, mmap.mmap)\n\n for line in lines:\n next_line = next(wrapper)\n assert next_line.strip() == line.strip()\n\n with pytest.raises(StopIteration, match=r"^$"):\n next(wrapper)\n\n def test_unknown_engine(self):\n with tm.ensure_clean() as path:\n df = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n df.to_csv(path)\n with pytest.raises(ValueError, match="Unknown engine"):\n pd.read_csv(path, engine="pyt")\n\n def test_binary_mode(self):\n """\n 'encoding' shouldn't be passed to 'open' in binary mode.\n\n GH 35058\n """\n with tm.ensure_clean() as path:\n df = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n df.to_csv(path, mode="w+b")\n tm.assert_frame_equal(df, pd.read_csv(path, index_col=0))\n\n @pytest.mark.parametrize("encoding", ["utf-16", "utf-32"])\n @pytest.mark.parametrize("compression_", ["bz2", "xz"])\n def test_warning_missing_utf_bom(self, encoding, compression_):\n """\n bz2 and xz do not write the byte order mark (BOM) for utf-16/32.\n\n https://stackoverflow.com/questions/55171439\n\n GH 35681\n """\n df = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n with tm.ensure_clean() as path:\n with tm.assert_produces_warning(UnicodeWarning):\n df.to_csv(path, compression=compression_, encoding=encoding)\n\n # reading should fail (otherwise we wouldn't need the warning)\n msg = (\n r"UTF-\d+ stream does not start with BOM|"\n r"'utf-\d+' codec can't decode byte"\n )\n with pytest.raises(UnicodeError, match=msg):\n pd.read_csv(path, compression=compression_, encoding=encoding)\n\n\ndef test_is_fsspec_url():\n assert icom.is_fsspec_url("gcs://pandas/somethingelse.com")\n assert icom.is_fsspec_url("gs://pandas/somethingelse.com")\n # the following is the only remote URL that is handled without fsspec\n assert not icom.is_fsspec_url("http://pandas/somethingelse.com")\n assert not icom.is_fsspec_url("random:pandas/somethingelse.com")\n assert not icom.is_fsspec_url("/local/path")\n assert not icom.is_fsspec_url("relative/local/path")\n # fsspec URL in string should not be recognized\n assert not icom.is_fsspec_url("this is not fsspec://url")\n assert not icom.is_fsspec_url("{'url': 'gs://pandas/somethingelse.com'}")\n # accept everything that conforms to RFC 3986 schema\n assert icom.is_fsspec_url("RFC-3986+compliant.spec://something")\n\n\n@pytest.mark.parametrize("encoding", [None, "utf-8"])\n@pytest.mark.parametrize("format", ["csv", "json"])\ndef test_codecs_encoding(encoding, format):\n # GH39247\n expected = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n with tm.ensure_clean() as path:\n with codecs.open(path, mode="w", encoding=encoding) as handle:\n getattr(expected, f"to_{format}")(handle)\n with codecs.open(path, mode="r", encoding=encoding) as handle:\n if format == "csv":\n df = pd.read_csv(handle, index_col=0)\n else:\n df = pd.read_json(handle)\n tm.assert_frame_equal(expected, df)\n\n\ndef test_codecs_get_writer_reader():\n # GH39247\n expected = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n with tm.ensure_clean() as path:\n with open(path, "wb") as handle:\n with codecs.getwriter("utf-8")(handle) as encoded:\n expected.to_csv(encoded)\n with open(path, "rb") as handle:\n with codecs.getreader("utf-8")(handle) as encoded:\n df = pd.read_csv(encoded, index_col=0)\n tm.assert_frame_equal(expected, df)\n\n\n@pytest.mark.parametrize(\n "io_class,mode,msg",\n [\n (BytesIO, "t", "a bytes-like object is required, not 'str'"),\n (StringIO, "b", "string argument expected, got 'bytes'"),\n ],\n)\ndef test_explicit_encoding(io_class, mode, msg):\n # GH39247; this test makes sure that if a user provides mode="*t" or "*b",\n # it is used. In the case of this test it leads to an error as intentionally the\n # wrong mode is requested\n expected = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n with io_class() as buffer:\n with pytest.raises(TypeError, match=msg):\n expected.to_csv(buffer, mode=f"w{mode}")\n\n\n@pytest.mark.parametrize("encoding_errors", [None, "strict", "replace"])\n@pytest.mark.parametrize("format", ["csv", "json"])\ndef test_encoding_errors(encoding_errors, format):\n # GH39450\n msg = "'utf-8' codec can't decode byte"\n bad_encoding = b"\xe4"\n\n if format == "csv":\n content = b"," + bad_encoding + b"\n" + bad_encoding * 2 + b"," + bad_encoding\n reader = partial(pd.read_csv, index_col=0)\n else:\n content = (\n b'{"'\n + bad_encoding * 2\n + b'": {"'\n + bad_encoding\n + b'":"'\n + bad_encoding\n + b'"}}'\n )\n reader = partial(pd.read_json, orient="index")\n with tm.ensure_clean() as path:\n file = Path(path)\n file.write_bytes(content)\n\n if encoding_errors != "replace":\n with pytest.raises(UnicodeDecodeError, match=msg):\n reader(path, encoding_errors=encoding_errors)\n else:\n df = reader(path, encoding_errors=encoding_errors)\n decoded = bad_encoding.decode(errors=encoding_errors)\n expected = pd.DataFrame({decoded: [decoded]}, index=[decoded * 2])\n tm.assert_frame_equal(df, expected)\n\n\ndef test_bad_encdoing_errors():\n # GH 39777\n with tm.ensure_clean() as path:\n with pytest.raises(LookupError, match="unknown error handler name"):\n icom.get_handle(path, "w", errors="bad")\n\n\ndef test_errno_attribute():\n # GH 13872\n with pytest.raises(FileNotFoundError, match="\\[Errno 2\\]") as err:\n pd.read_csv("doesnt_exist")\n assert err.errno == errno.ENOENT\n\n\ndef test_fail_mmap():\n with pytest.raises(UnsupportedOperation, match="fileno"):\n with BytesIO() as buffer:\n icom.get_handle(buffer, "rb", memory_map=True)\n\n\ndef test_close_on_error():\n # GH 47136\n class TestError:\n def close(self):\n raise OSError("test")\n\n with pytest.raises(OSError, match="test"):\n with BytesIO() as buffer:\n with icom.get_handle(buffer, "rb") as handles:\n handles.created_handles.append(TestError())\n\n\n@pytest.mark.parametrize(\n "reader",\n [\n pd.read_csv,\n pd.read_fwf,\n pd.read_excel,\n pd.read_feather,\n pd.read_hdf,\n pd.read_stata,\n pd.read_sas,\n pd.read_json,\n pd.read_pickle,\n ],\n)\ndef test_pickle_reader(reader):\n # GH 22265\n with BytesIO() as buffer:\n pickle.dump(reader, buffer)\n
.venv\Lib\site-packages\pandas\tests\io\test_common.py
test_common.py
Python
23,939
0.95
0.098784
0.062278
python-kit
748
2023-08-03T02:43:01.740044
MIT
true
a124850cde91d3c79217e569bf0de2bc
import gzip\nimport io\nimport os\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport tarfile\nimport textwrap\nimport time\nimport zipfile\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\n\nimport pandas as pd\nimport pandas._testing as tm\n\nimport pandas.io.common as icom\n\n\n@pytest.mark.parametrize(\n "obj",\n [\n pd.DataFrame(\n 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],\n columns=["X", "Y", "Z"],\n ),\n pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),\n ],\n)\n@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"])\ndef test_compression_size(obj, method, compression_only):\n if compression_only == "tar":\n compression_only = {"method": "tar", "mode": "w:gz"}\n\n with tm.ensure_clean() as path:\n getattr(obj, method)(path, compression=compression_only)\n compressed_size = os.path.getsize(path)\n getattr(obj, method)(path, compression=None)\n uncompressed_size = os.path.getsize(path)\n assert uncompressed_size > compressed_size\n\n\n@pytest.mark.parametrize(\n "obj",\n [\n pd.DataFrame(\n 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],\n columns=["X", "Y", "Z"],\n ),\n pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),\n ],\n)\n@pytest.mark.parametrize("method", ["to_csv", "to_json"])\ndef test_compression_size_fh(obj, method, compression_only):\n with tm.ensure_clean() as path:\n with icom.get_handle(\n path,\n "w:gz" if compression_only == "tar" else "w",\n compression=compression_only,\n ) as handles:\n getattr(obj, method)(handles.handle)\n assert not handles.handle.closed\n compressed_size = os.path.getsize(path)\n with tm.ensure_clean() as path:\n with icom.get_handle(path, "w", compression=None) as handles:\n getattr(obj, method)(handles.handle)\n assert not handles.handle.closed\n uncompressed_size = os.path.getsize(path)\n assert uncompressed_size > compressed_size\n\n\n@pytest.mark.parametrize(\n "write_method, write_kwargs, read_method",\n [\n ("to_csv", {"index": False}, pd.read_csv),\n ("to_json", {}, pd.read_json),\n ("to_pickle", {}, pd.read_pickle),\n ],\n)\ndef test_dataframe_compression_defaults_to_infer(\n write_method, write_kwargs, read_method, compression_only, compression_to_extension\n):\n # GH22004\n input = pd.DataFrame([[1.0, 0, -4], [3.4, 5, 2]], columns=["X", "Y", "Z"])\n extension = compression_to_extension[compression_only]\n with tm.ensure_clean("compressed" + extension) as path:\n getattr(input, write_method)(path, **write_kwargs)\n output = read_method(path, compression=compression_only)\n tm.assert_frame_equal(output, input)\n\n\n@pytest.mark.parametrize(\n "write_method,write_kwargs,read_method,read_kwargs",\n [\n ("to_csv", {"index": False, "header": True}, pd.read_csv, {"squeeze": True}),\n ("to_json", {}, pd.read_json, {"typ": "series"}),\n ("to_pickle", {}, pd.read_pickle, {}),\n ],\n)\ndef test_series_compression_defaults_to_infer(\n write_method,\n write_kwargs,\n read_method,\n read_kwargs,\n compression_only,\n compression_to_extension,\n):\n # GH22004\n input = pd.Series([0, 5, -2, 10], name="X")\n extension = compression_to_extension[compression_only]\n with tm.ensure_clean("compressed" + extension) as path:\n getattr(input, write_method)(path, **write_kwargs)\n if "squeeze" in read_kwargs:\n kwargs = read_kwargs.copy()\n del kwargs["squeeze"]\n output = read_method(path, compression=compression_only, **kwargs).squeeze(\n "columns"\n )\n else:\n output = read_method(path, compression=compression_only, **read_kwargs)\n tm.assert_series_equal(output, input, check_names=False)\n\n\ndef test_compression_warning(compression_only):\n # Assert that passing a file object to to_csv while explicitly specifying a\n # compression protocol triggers a RuntimeWarning, as per GH21227.\n df = pd.DataFrame(\n 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],\n columns=["X", "Y", "Z"],\n )\n with tm.ensure_clean() as path:\n with icom.get_handle(path, "w", compression=compression_only) as handles:\n with tm.assert_produces_warning(RuntimeWarning):\n df.to_csv(handles.handle, compression=compression_only)\n\n\ndef test_compression_binary(compression_only):\n """\n Binary file handles support compression.\n\n GH22555\n """\n df = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n\n # with a file\n with tm.ensure_clean() as path:\n with open(path, mode="wb") as file:\n df.to_csv(file, mode="wb", compression=compression_only)\n file.seek(0) # file shouldn't be closed\n tm.assert_frame_equal(\n df, pd.read_csv(path, index_col=0, compression=compression_only)\n )\n\n # with BytesIO\n file = io.BytesIO()\n df.to_csv(file, mode="wb", compression=compression_only)\n file.seek(0) # file shouldn't be closed\n tm.assert_frame_equal(\n df, pd.read_csv(file, index_col=0, compression=compression_only)\n )\n\n\ndef test_gzip_reproducibility_file_name():\n """\n Gzip should create reproducible archives with mtime.\n\n Note: Archives created with different filenames will still be different!\n\n GH 28103\n """\n df = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n compression_options = {"method": "gzip", "mtime": 1}\n\n # test for filename\n with tm.ensure_clean() as path:\n path = Path(path)\n df.to_csv(path, compression=compression_options)\n time.sleep(0.1)\n output = path.read_bytes()\n df.to_csv(path, compression=compression_options)\n assert output == path.read_bytes()\n\n\ndef test_gzip_reproducibility_file_object():\n """\n Gzip should create reproducible archives with mtime.\n\n GH 28103\n """\n df = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n compression_options = {"method": "gzip", "mtime": 1}\n\n # test for file object\n buffer = io.BytesIO()\n df.to_csv(buffer, compression=compression_options, mode="wb")\n output = buffer.getvalue()\n time.sleep(0.1)\n buffer = io.BytesIO()\n df.to_csv(buffer, compression=compression_options, mode="wb")\n assert output == buffer.getvalue()\n\n\n@pytest.mark.single_cpu\ndef test_with_missing_lzma():\n """Tests if import pandas works when lzma is not present."""\n # https://github.com/pandas-dev/pandas/issues/27575\n code = textwrap.dedent(\n """\\n import sys\n sys.modules['lzma'] = None\n import pandas\n """\n )\n subprocess.check_output([sys.executable, "-c", code], stderr=subprocess.PIPE)\n\n\n@pytest.mark.single_cpu\ndef test_with_missing_lzma_runtime():\n """Tests if RuntimeError is hit when calling lzma without\n having the module available.\n """\n code = textwrap.dedent(\n """\n import sys\n import pytest\n sys.modules['lzma'] = None\n import pandas as pd\n df = pd.DataFrame()\n with pytest.raises(RuntimeError, match='lzma module'):\n df.to_csv('foo.csv', compression='xz')\n """\n )\n subprocess.check_output([sys.executable, "-c", code], stderr=subprocess.PIPE)\n\n\n@pytest.mark.parametrize(\n "obj",\n [\n pd.DataFrame(\n 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],\n columns=["X", "Y", "Z"],\n ),\n pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),\n ],\n)\n@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"])\ndef test_gzip_compression_level(obj, method):\n # GH33196\n with tm.ensure_clean() as path:\n getattr(obj, method)(path, compression="gzip")\n compressed_size_default = os.path.getsize(path)\n getattr(obj, method)(path, compression={"method": "gzip", "compresslevel": 1})\n compressed_size_fast = os.path.getsize(path)\n assert compressed_size_default < compressed_size_fast\n\n\n@pytest.mark.parametrize(\n "obj",\n [\n pd.DataFrame(\n 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],\n columns=["X", "Y", "Z"],\n ),\n pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),\n ],\n)\n@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"])\ndef test_xz_compression_level_read(obj, method):\n with tm.ensure_clean() as path:\n getattr(obj, method)(path, compression="xz")\n compressed_size_default = os.path.getsize(path)\n getattr(obj, method)(path, compression={"method": "xz", "preset": 1})\n compressed_size_fast = os.path.getsize(path)\n assert compressed_size_default < compressed_size_fast\n if method == "to_csv":\n pd.read_csv(path, compression="xz")\n\n\n@pytest.mark.parametrize(\n "obj",\n [\n pd.DataFrame(\n 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],\n columns=["X", "Y", "Z"],\n ),\n pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"),\n ],\n)\n@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"])\ndef test_bzip_compression_level(obj, method):\n """GH33196 bzip needs file size > 100k to show a size difference between\n compression levels, so here we just check if the call works when\n compression is passed as a dict.\n """\n with tm.ensure_clean() as path:\n getattr(obj, method)(path, compression={"method": "bz2", "compresslevel": 1})\n\n\n@pytest.mark.parametrize(\n "suffix,archive",\n [\n (".zip", zipfile.ZipFile),\n (".tar", tarfile.TarFile),\n ],\n)\ndef test_empty_archive_zip(suffix, archive):\n with tm.ensure_clean(filename=suffix) as path:\n with archive(path, "w"):\n pass\n with pytest.raises(ValueError, match="Zero files found"):\n pd.read_csv(path)\n\n\ndef test_ambiguous_archive_zip():\n with tm.ensure_clean(filename=".zip") as path:\n with zipfile.ZipFile(path, "w") as file:\n file.writestr("a.csv", "foo,bar")\n file.writestr("b.csv", "foo,bar")\n with pytest.raises(ValueError, match="Multiple files found in ZIP file"):\n pd.read_csv(path)\n\n\ndef test_ambiguous_archive_tar(tmp_path):\n csvAPath = tmp_path / "a.csv"\n with open(csvAPath, "w", encoding="utf-8") as a:\n a.write("foo,bar\n")\n csvBPath = tmp_path / "b.csv"\n with open(csvBPath, "w", encoding="utf-8") as b:\n b.write("foo,bar\n")\n\n tarpath = tmp_path / "archive.tar"\n with tarfile.TarFile(tarpath, "w") as tar:\n tar.add(csvAPath, "a.csv")\n tar.add(csvBPath, "b.csv")\n\n with pytest.raises(ValueError, match="Multiple files found in TAR archive"):\n pd.read_csv(tarpath)\n\n\ndef test_tar_gz_to_different_filename():\n with tm.ensure_clean(filename=".foo") as file:\n pd.DataFrame(\n [["1", "2"]],\n columns=["foo", "bar"],\n ).to_csv(file, compression={"method": "tar", "mode": "w:gz"}, index=False)\n with gzip.open(file) as uncompressed:\n with tarfile.TarFile(fileobj=uncompressed) as archive:\n members = archive.getmembers()\n assert len(members) == 1\n content = archive.extractfile(members[0]).read().decode("utf8")\n\n if is_platform_windows():\n expected = "foo,bar\r\n1,2\r\n"\n else:\n expected = "foo,bar\n1,2\n"\n\n assert content == expected\n\n\ndef test_tar_no_error_on_close():\n with io.BytesIO() as buffer:\n with icom._BytesTarFile(fileobj=buffer, mode="w"):\n pass\n
.venv\Lib\site-packages\pandas\tests\io\test_compression.py
test_compression.py
Python
12,259
0.95
0.084656
0.030769
python-kit
717
2023-08-24T20:54:01.495111
BSD-3-Clause
true
41471e1cfb46842ac3bb76cabd5602b0
""" test feather-format compat """\nimport numpy as np\nimport pytest\n\nfrom pandas.compat.pyarrow import (\n pa_version_under18p0,\n pa_version_under19p0,\n)\n\nimport pandas as pd\nimport pandas._testing as tm\n\nfrom pandas.io.feather_format import read_feather, to_feather # isort:skip\n\npytestmark = pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n)\n\n\npa = pytest.importorskip("pyarrow")\n\n\n@pytest.mark.single_cpu\nclass TestFeather:\n def check_error_on_write(self, df, exc, err_msg):\n # check that we are raising the exception\n # on writing\n\n with pytest.raises(exc, match=err_msg):\n with tm.ensure_clean() as path:\n to_feather(df, path)\n\n def check_external_error_on_write(self, df):\n # check that we are raising the exception\n # on writing\n\n with tm.external_error_raised(Exception):\n with tm.ensure_clean() as path:\n to_feather(df, path)\n\n def check_round_trip(self, df, expected=None, write_kwargs={}, **read_kwargs):\n if expected is None:\n expected = df.copy()\n\n with tm.ensure_clean() as path:\n to_feather(df, path, **write_kwargs)\n\n result = read_feather(path, **read_kwargs)\n\n tm.assert_frame_equal(result, expected)\n\n def test_error(self):\n msg = "feather only support IO with DataFrames"\n for obj in [\n pd.Series([1, 2, 3]),\n 1,\n "foo",\n pd.Timestamp("20130101"),\n np.array([1, 2, 3]),\n ]:\n self.check_error_on_write(obj, ValueError, msg)\n\n def test_basic(self):\n df = pd.DataFrame(\n {\n "string": list("abc"),\n "int": list(range(1, 4)),\n "uint": np.arange(3, 6).astype("u1"),\n "float": np.arange(4.0, 7.0, dtype="float64"),\n "float_with_null": [1.0, np.nan, 3],\n "bool": [True, False, True],\n "bool_with_null": [True, np.nan, False],\n "cat": pd.Categorical(list("abc")),\n "dt": pd.DatetimeIndex(\n list(pd.date_range("20130101", periods=3)), freq=None\n ),\n "dttz": pd.DatetimeIndex(\n list(pd.date_range("20130101", periods=3, tz="US/Eastern")),\n freq=None,\n ),\n "dt_with_null": [\n pd.Timestamp("20130101"),\n pd.NaT,\n pd.Timestamp("20130103"),\n ],\n "dtns": pd.DatetimeIndex(\n list(pd.date_range("20130101", periods=3, freq="ns")), freq=None\n ),\n }\n )\n df["periods"] = pd.period_range("2013", freq="M", periods=3)\n df["timedeltas"] = pd.timedelta_range("1 day", periods=3)\n df["intervals"] = pd.interval_range(0, 3, 3)\n\n assert df.dttz.dtype.tz.zone == "US/Eastern"\n\n expected = df.copy()\n expected.loc[1, "bool_with_null"] = None\n self.check_round_trip(df, expected=expected)\n\n def test_duplicate_columns(self):\n # https://github.com/wesm/feather/issues/53\n # not currently able to handle duplicate columns\n df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy()\n self.check_external_error_on_write(df)\n\n def test_read_columns(self):\n # GH 24025\n df = pd.DataFrame(\n {\n "col1": list("abc"),\n "col2": list(range(1, 4)),\n "col3": list("xyz"),\n "col4": list(range(4, 7)),\n }\n )\n columns = ["col1", "col3"]\n self.check_round_trip(df, expected=df[columns], columns=columns)\n\n def test_read_columns_different_order(self):\n # GH 33878\n df = pd.DataFrame({"A": [1, 2], "B": ["x", "y"], "C": [True, False]})\n expected = df[["B", "A"]]\n self.check_round_trip(df, expected, columns=["B", "A"])\n\n def test_unsupported_other(self):\n # mixed python objects\n df = pd.DataFrame({"a": ["a", 1, 2.0]})\n self.check_external_error_on_write(df)\n\n def test_rw_use_threads(self):\n df = pd.DataFrame({"A": np.arange(100000)})\n self.check_round_trip(df, use_threads=True)\n self.check_round_trip(df, use_threads=False)\n\n def test_path_pathlib(self):\n df = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n ).reset_index()\n result = tm.round_trip_pathlib(df.to_feather, read_feather)\n tm.assert_frame_equal(df, result)\n\n def test_path_localpath(self):\n df = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n ).reset_index()\n result = tm.round_trip_localpath(df.to_feather, read_feather)\n tm.assert_frame_equal(df, result)\n\n def test_passthrough_keywords(self):\n df = pd.DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n ).reset_index()\n self.check_round_trip(df, write_kwargs={"version": 1})\n\n @pytest.mark.network\n @pytest.mark.single_cpu\n def test_http_path(self, feather_file, httpserver):\n # GH 29055\n expected = read_feather(feather_file)\n with open(feather_file, "rb") as f:\n httpserver.serve_content(content=f.read())\n res = read_feather(httpserver.url)\n tm.assert_frame_equal(expected, res)\n\n def test_read_feather_dtype_backend(\n self, string_storage, dtype_backend, using_infer_string\n ):\n # GH#50765\n df = pd.DataFrame(\n {\n "a": pd.Series([1, np.nan, 3], dtype="Int64"),\n "b": pd.Series([1, 2, 3], dtype="Int64"),\n "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"),\n "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"),\n "e": [True, False, None],\n "f": [True, False, True],\n "g": ["a", "b", "c"],\n "h": ["a", "b", None],\n }\n )\n\n with tm.ensure_clean() as path:\n to_feather(df, path)\n with pd.option_context("mode.string_storage", string_storage):\n result = read_feather(path, dtype_backend=dtype_backend)\n\n if dtype_backend == "pyarrow":\n pa = pytest.importorskip("pyarrow")\n if using_infer_string:\n string_dtype = pd.ArrowDtype(pa.large_string())\n else:\n string_dtype = pd.ArrowDtype(pa.string())\n else:\n string_dtype = pd.StringDtype(string_storage)\n\n expected = pd.DataFrame(\n {\n "a": pd.Series([1, np.nan, 3], dtype="Int64"),\n "b": pd.Series([1, 2, 3], dtype="Int64"),\n "c": pd.Series([1.5, np.nan, 2.5], dtype="Float64"),\n "d": pd.Series([1.5, 2.0, 2.5], dtype="Float64"),\n "e": pd.Series([True, False, pd.NA], dtype="boolean"),\n "f": pd.Series([True, False, True], dtype="boolean"),\n "g": pd.Series(["a", "b", "c"], dtype=string_dtype),\n "h": pd.Series(["a", "b", None], dtype=string_dtype),\n }\n )\n\n if dtype_backend == "pyarrow":\n from pandas.arrays import ArrowExtensionArray\n\n expected = pd.DataFrame(\n {\n col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))\n for col in expected.columns\n }\n )\n\n if using_infer_string:\n expected.columns = expected.columns.astype(\n pd.StringDtype(string_storage, na_value=np.nan)\n )\n tm.assert_frame_equal(result, expected)\n\n def test_int_columns_and_index(self):\n df = pd.DataFrame({"a": [1, 2, 3]}, index=pd.Index([3, 4, 5], name="test"))\n self.check_round_trip(df)\n\n def test_invalid_dtype_backend(self):\n msg = (\n "dtype_backend numpy is invalid, only 'numpy_nullable' and "\n "'pyarrow' are allowed."\n )\n df = pd.DataFrame({"int": list(range(1, 4))})\n with tm.ensure_clean("tmp.feather") as path:\n df.to_feather(path)\n with pytest.raises(ValueError, match=msg):\n read_feather(path, dtype_backend="numpy")\n\n def test_string_inference(self, tmp_path, using_infer_string):\n # GH#54431\n path = tmp_path / "test_string_inference.p"\n df = pd.DataFrame(data={"a": ["x", "y"]})\n df.to_feather(path)\n with pd.option_context("future.infer_string", True):\n result = read_feather(path)\n dtype = pd.StringDtype(na_value=np.nan)\n expected = pd.DataFrame(\n data={"a": ["x", "y"]}, dtype=pd.StringDtype(na_value=np.nan)\n )\n expected = pd.DataFrame(\n data={"a": ["x", "y"]},\n dtype=dtype,\n columns=pd.Index(\n ["a"],\n dtype=object\n if pa_version_under19p0 and not using_infer_string\n else dtype,\n ),\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.skipif(pa_version_under18p0, reason="not supported before 18.0")\n def test_string_inference_string_view_type(self, tmp_path):\n # GH#54798\n import pyarrow as pa\n from pyarrow import feather\n\n path = tmp_path / "string_view.parquet"\n table = pa.table({"a": pa.array([None, "b", "c"], pa.string_view())})\n feather.write_feather(table, path)\n\n with pd.option_context("future.infer_string", True):\n result = read_feather(path)\n\n expected = pd.DataFrame(\n data={"a": [None, "b", "c"]}, dtype=pd.StringDtype(na_value=np.nan)\n )\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\io\test_feather.py
test_feather.py
Python
10,210
0.95
0.108392
0.053279
awesome-app
532
2025-05-20T19:35:00.463627
MIT
true
d790bc45adfb9f28c6a8679b3e6e8933
import io\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nfrom pandas import (\n DataFrame,\n date_range,\n read_csv,\n read_excel,\n read_feather,\n read_json,\n read_parquet,\n read_pickle,\n read_stata,\n read_table,\n)\nimport pandas._testing as tm\nfrom pandas.util import _test_decorators as td\n\npytestmark = pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n)\n\n\n@pytest.fixture\ndef fsspectest():\n pytest.importorskip("fsspec")\n from fsspec import register_implementation\n from fsspec.implementations.memory import MemoryFileSystem\n from fsspec.registry import _registry as registry\n\n class TestMemoryFS(MemoryFileSystem):\n protocol = "testmem"\n test = [None]\n\n def __init__(self, **kwargs) -> None:\n self.test[0] = kwargs.pop("test", None)\n super().__init__(**kwargs)\n\n register_implementation("testmem", TestMemoryFS, clobber=True)\n yield TestMemoryFS()\n registry.pop("testmem", None)\n TestMemoryFS.test[0] = None\n TestMemoryFS.store.clear()\n\n\n@pytest.fixture\ndef df1():\n return DataFrame(\n {\n "int": [1, 3],\n "float": [2.0, np.nan],\n "str": ["t", "s"],\n "dt": date_range("2018-06-18", periods=2),\n }\n )\n\n\n@pytest.fixture\ndef cleared_fs():\n fsspec = pytest.importorskip("fsspec")\n\n memfs = fsspec.filesystem("memory")\n yield memfs\n memfs.store.clear()\n\n\ndef test_read_csv(cleared_fs, df1):\n text = str(df1.to_csv(index=False)).encode()\n with cleared_fs.open("test/test.csv", "wb") as w:\n w.write(text)\n df2 = read_csv("memory://test/test.csv", parse_dates=["dt"])\n\n tm.assert_frame_equal(df1, df2)\n\n\ndef test_reasonable_error(monkeypatch, cleared_fs):\n from fsspec.registry import known_implementations\n\n with pytest.raises(ValueError, match="nosuchprotocol"):\n read_csv("nosuchprotocol://test/test.csv")\n err_msg = "test error message"\n monkeypatch.setitem(\n known_implementations,\n "couldexist",\n {"class": "unimportable.CouldExist", "err": err_msg},\n )\n with pytest.raises(ImportError, match=err_msg):\n read_csv("couldexist://test/test.csv")\n\n\ndef test_to_csv(cleared_fs, df1):\n df1.to_csv("memory://test/test.csv", index=True)\n\n df2 = read_csv("memory://test/test.csv", parse_dates=["dt"], index_col=0)\n\n tm.assert_frame_equal(df1, df2)\n\n\ndef test_to_excel(cleared_fs, df1):\n pytest.importorskip("openpyxl")\n ext = "xlsx"\n path = f"memory://test/test.{ext}"\n df1.to_excel(path, index=True)\n\n df2 = read_excel(path, parse_dates=["dt"], index_col=0)\n\n tm.assert_frame_equal(df1, df2)\n\n\n@pytest.mark.parametrize("binary_mode", [False, True])\ndef test_to_csv_fsspec_object(cleared_fs, binary_mode, df1):\n fsspec = pytest.importorskip("fsspec")\n\n path = "memory://test/test.csv"\n mode = "wb" if binary_mode else "w"\n with fsspec.open(path, mode=mode).open() as fsspec_object:\n df1.to_csv(fsspec_object, index=True)\n assert not fsspec_object.closed\n\n mode = mode.replace("w", "r")\n with fsspec.open(path, mode=mode) as fsspec_object:\n df2 = read_csv(\n fsspec_object,\n parse_dates=["dt"],\n index_col=0,\n )\n assert not fsspec_object.closed\n\n tm.assert_frame_equal(df1, df2)\n\n\ndef test_csv_options(fsspectest):\n df = DataFrame({"a": [0]})\n df.to_csv(\n "testmem://test/test.csv", storage_options={"test": "csv_write"}, index=False\n )\n assert fsspectest.test[0] == "csv_write"\n read_csv("testmem://test/test.csv", storage_options={"test": "csv_read"})\n assert fsspectest.test[0] == "csv_read"\n\n\ndef test_read_table_options(fsspectest):\n # GH #39167\n df = DataFrame({"a": [0]})\n df.to_csv(\n "testmem://test/test.csv", storage_options={"test": "csv_write"}, index=False\n )\n assert fsspectest.test[0] == "csv_write"\n read_table("testmem://test/test.csv", storage_options={"test": "csv_read"})\n assert fsspectest.test[0] == "csv_read"\n\n\ndef test_excel_options(fsspectest):\n pytest.importorskip("openpyxl")\n extension = "xlsx"\n\n df = DataFrame({"a": [0]})\n\n path = f"testmem://test/test.{extension}"\n\n df.to_excel(path, storage_options={"test": "write"}, index=False)\n assert fsspectest.test[0] == "write"\n read_excel(path, storage_options={"test": "read"})\n assert fsspectest.test[0] == "read"\n\n\ndef test_to_parquet_new_file(cleared_fs, df1):\n """Regression test for writing to a not-yet-existent GCS Parquet file."""\n pytest.importorskip("fastparquet")\n\n df1.to_parquet(\n "memory://test/test.csv", index=True, engine="fastparquet", compression=None\n )\n\n\ndef test_arrowparquet_options(fsspectest):\n """Regression test for writing to a not-yet-existent GCS Parquet file."""\n pytest.importorskip("pyarrow")\n df = DataFrame({"a": [0]})\n df.to_parquet(\n "testmem://test/test.csv",\n engine="pyarrow",\n compression=None,\n storage_options={"test": "parquet_write"},\n )\n assert fsspectest.test[0] == "parquet_write"\n read_parquet(\n "testmem://test/test.csv",\n engine="pyarrow",\n storage_options={"test": "parquet_read"},\n )\n assert fsspectest.test[0] == "parquet_read"\n\n\n@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) fastparquet\ndef test_fastparquet_options(fsspectest):\n """Regression test for writing to a not-yet-existent GCS Parquet file."""\n pytest.importorskip("fastparquet")\n\n df = DataFrame({"a": [0]})\n df.to_parquet(\n "testmem://test/test.csv",\n engine="fastparquet",\n compression=None,\n storage_options={"test": "parquet_write"},\n )\n assert fsspectest.test[0] == "parquet_write"\n read_parquet(\n "testmem://test/test.csv",\n engine="fastparquet",\n storage_options={"test": "parquet_read"},\n )\n assert fsspectest.test[0] == "parquet_read"\n\n\n@pytest.mark.single_cpu\ndef test_from_s3_csv(s3_public_bucket_with_data, tips_file, s3so):\n pytest.importorskip("s3fs")\n tm.assert_equal(\n read_csv(\n f"s3://{s3_public_bucket_with_data.name}/tips.csv", storage_options=s3so\n ),\n read_csv(tips_file),\n )\n # the following are decompressed by pandas, not fsspec\n tm.assert_equal(\n read_csv(\n f"s3://{s3_public_bucket_with_data.name}/tips.csv.gz", storage_options=s3so\n ),\n read_csv(tips_file),\n )\n tm.assert_equal(\n read_csv(\n f"s3://{s3_public_bucket_with_data.name}/tips.csv.bz2", storage_options=s3so\n ),\n read_csv(tips_file),\n )\n\n\n@pytest.mark.single_cpu\n@pytest.mark.parametrize("protocol", ["s3", "s3a", "s3n"])\ndef test_s3_protocols(s3_public_bucket_with_data, tips_file, protocol, s3so):\n pytest.importorskip("s3fs")\n tm.assert_equal(\n read_csv(\n f"{protocol}://{s3_public_bucket_with_data.name}/tips.csv",\n storage_options=s3so,\n ),\n read_csv(tips_file),\n )\n\n\n@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string) fastparquet")\n@pytest.mark.single_cpu\n@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) fastparquet\ndef test_s3_parquet(s3_public_bucket, s3so, df1):\n pytest.importorskip("fastparquet")\n pytest.importorskip("s3fs")\n\n fn = f"s3://{s3_public_bucket.name}/test.parquet"\n df1.to_parquet(\n fn, index=False, engine="fastparquet", compression=None, storage_options=s3so\n )\n df2 = read_parquet(fn, engine="fastparquet", storage_options=s3so)\n tm.assert_equal(df1, df2)\n\n\n@td.skip_if_installed("fsspec")\ndef test_not_present_exception():\n msg = "Missing optional dependency 'fsspec'|fsspec library is required"\n with pytest.raises(ImportError, match=msg):\n read_csv("memory://test/test.csv")\n\n\ndef test_feather_options(fsspectest):\n pytest.importorskip("pyarrow")\n df = DataFrame({"a": [0]})\n df.to_feather("testmem://mockfile", storage_options={"test": "feather_write"})\n assert fsspectest.test[0] == "feather_write"\n out = read_feather("testmem://mockfile", storage_options={"test": "feather_read"})\n assert fsspectest.test[0] == "feather_read"\n tm.assert_frame_equal(df, out)\n\n\ndef test_pickle_options(fsspectest):\n df = DataFrame({"a": [0]})\n df.to_pickle("testmem://mockfile", storage_options={"test": "pickle_write"})\n assert fsspectest.test[0] == "pickle_write"\n out = read_pickle("testmem://mockfile", storage_options={"test": "pickle_read"})\n assert fsspectest.test[0] == "pickle_read"\n tm.assert_frame_equal(df, out)\n\n\ndef test_json_options(fsspectest, compression):\n df = DataFrame({"a": [0]})\n df.to_json(\n "testmem://mockfile",\n compression=compression,\n storage_options={"test": "json_write"},\n )\n assert fsspectest.test[0] == "json_write"\n out = read_json(\n "testmem://mockfile",\n compression=compression,\n storage_options={"test": "json_read"},\n )\n assert fsspectest.test[0] == "json_read"\n tm.assert_frame_equal(df, out)\n\n\ndef test_stata_options(fsspectest):\n df = DataFrame({"a": [0]})\n df.to_stata(\n "testmem://mockfile", storage_options={"test": "stata_write"}, write_index=False\n )\n assert fsspectest.test[0] == "stata_write"\n out = read_stata("testmem://mockfile", storage_options={"test": "stata_read"})\n assert fsspectest.test[0] == "stata_read"\n tm.assert_frame_equal(df, out.astype("int64"))\n\n\ndef test_markdown_options(fsspectest):\n pytest.importorskip("tabulate")\n df = DataFrame({"a": [0]})\n df.to_markdown("testmem://mockfile", storage_options={"test": "md_write"})\n assert fsspectest.test[0] == "md_write"\n assert fsspectest.cat("testmem://mockfile")\n\n\ndef test_non_fsspec_options():\n pytest.importorskip("pyarrow")\n with pytest.raises(ValueError, match="storage_options"):\n read_csv("localfile", storage_options={"a": True})\n with pytest.raises(ValueError, match="storage_options"):\n # separate test for parquet, which has a different code path\n read_parquet("localfile", storage_options={"a": True})\n by = io.BytesIO()\n\n with pytest.raises(ValueError, match="storage_options"):\n read_csv(by, storage_options={"a": True})\n\n df = DataFrame({"a": [0]})\n with pytest.raises(ValueError, match="storage_options"):\n df.to_parquet("nonfsspecpath", storage_options={"a": True})\n
.venv\Lib\site-packages\pandas\tests\io\test_fsspec.py
test_fsspec.py
Python
10,547
0.95
0.091954
0.010909
node-utils
499
2024-01-28T05:09:08.603749
GPL-3.0
true
e859092cdeb71ef515ccc5a9298d4960
import pandas as pd\nimport pandas._testing as tm\n\n\ndef test_read_gbq_deprecated():\n with tm.assert_produces_warning(FutureWarning):\n with tm.external_error_raised(Exception):\n pd.read_gbq("fake")\n\n\ndef test_to_gbq_deprecated():\n with tm.assert_produces_warning(FutureWarning):\n with tm.external_error_raised(Exception):\n pd.DataFrame(range(1)).to_gbq("fake")\n
.venv\Lib\site-packages\pandas\tests\io\test_gbq.py
test_gbq.py
Python
401
0.85
0.142857
0
awesome-app
575
2024-03-25T20:29:30.573328
BSD-3-Clause
true
2deda809c0979810c0f98d0ef6c5937d
from io import BytesIO\nimport os\nimport pathlib\nimport tarfile\nimport zipfile\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat.pyarrow import pa_version_under17p0\n\nfrom pandas import (\n DataFrame,\n Index,\n date_range,\n read_csv,\n read_excel,\n read_json,\n read_parquet,\n)\nimport pandas._testing as tm\nfrom pandas.util import _test_decorators as td\n\npytestmark = pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n)\n\n\n@pytest.fixture\ndef gcs_buffer():\n """Emulate GCS using a binary buffer."""\n pytest.importorskip("gcsfs")\n fsspec = pytest.importorskip("fsspec")\n\n gcs_buffer = BytesIO()\n gcs_buffer.close = lambda: True\n\n class MockGCSFileSystem(fsspec.AbstractFileSystem):\n @staticmethod\n def open(*args, **kwargs):\n gcs_buffer.seek(0)\n return gcs_buffer\n\n def ls(self, path, **kwargs):\n # needed for pyarrow\n return [{"name": path, "type": "file"}]\n\n # Overwrites the default implementation from gcsfs to our mock class\n fsspec.register_implementation("gs", MockGCSFileSystem, clobber=True)\n\n return gcs_buffer\n\n\n# Patches pyarrow; other processes should not pick up change\n@pytest.mark.single_cpu\n@pytest.mark.parametrize("format", ["csv", "json", "parquet", "excel", "markdown"])\ndef test_to_read_gcs(gcs_buffer, format, monkeypatch, capsys, request):\n """\n Test that many to/read functions support GCS.\n\n GH 33987\n """\n\n df1 = DataFrame(\n {\n "int": [1, 3],\n "float": [2.0, np.nan],\n "str": ["t", "s"],\n "dt": date_range("2018-06-18", periods=2),\n }\n )\n\n path = f"gs://test/test.{format}"\n\n if format == "csv":\n df1.to_csv(path, index=True)\n df2 = read_csv(path, parse_dates=["dt"], index_col=0)\n elif format == "excel":\n path = "gs://test/test.xlsx"\n df1.to_excel(path)\n df2 = read_excel(path, parse_dates=["dt"], index_col=0)\n elif format == "json":\n df1.to_json(path)\n df2 = read_json(path, convert_dates=["dt"])\n elif format == "parquet":\n pytest.importorskip("pyarrow")\n pa_fs = pytest.importorskip("pyarrow.fs")\n\n class MockFileSystem(pa_fs.FileSystem):\n @staticmethod\n def from_uri(path):\n print("Using pyarrow filesystem")\n to_local = pathlib.Path(path.replace("gs://", "")).absolute().as_uri()\n return pa_fs.LocalFileSystem(to_local)\n\n request.applymarker(\n pytest.mark.xfail(\n not pa_version_under17p0,\n raises=TypeError,\n reason="pyarrow 17 broke the mocked filesystem",\n )\n )\n with monkeypatch.context() as m:\n m.setattr(pa_fs, "FileSystem", MockFileSystem)\n df1.to_parquet(path)\n df2 = read_parquet(path)\n captured = capsys.readouterr()\n assert captured.out == "Using pyarrow filesystem\nUsing pyarrow filesystem\n"\n elif format == "markdown":\n pytest.importorskip("tabulate")\n df1.to_markdown(path)\n df2 = df1\n\n tm.assert_frame_equal(df1, df2)\n\n\ndef assert_equal_zip_safe(result: bytes, expected: bytes, compression: str):\n """\n For zip compression, only compare the CRC-32 checksum of the file contents\n to avoid checking the time-dependent last-modified timestamp which\n in some CI builds is off-by-one\n\n See https://en.wikipedia.org/wiki/ZIP_(file_format)#File_headers\n """\n if compression == "zip":\n # Only compare the CRC checksum of the file contents\n with zipfile.ZipFile(BytesIO(result)) as exp, zipfile.ZipFile(\n BytesIO(expected)\n ) as res:\n for res_info, exp_info in zip(res.infolist(), exp.infolist()):\n assert res_info.CRC == exp_info.CRC\n elif compression == "tar":\n with tarfile.open(fileobj=BytesIO(result)) as tar_exp, tarfile.open(\n fileobj=BytesIO(expected)\n ) as tar_res:\n for tar_res_info, tar_exp_info in zip(\n tar_res.getmembers(), tar_exp.getmembers()\n ):\n actual_file = tar_res.extractfile(tar_res_info)\n expected_file = tar_exp.extractfile(tar_exp_info)\n assert (actual_file is None) == (expected_file is None)\n if actual_file is not None and expected_file is not None:\n assert actual_file.read() == expected_file.read()\n else:\n assert result == expected\n\n\n@pytest.mark.parametrize("encoding", ["utf-8", "cp1251"])\ndef test_to_csv_compression_encoding_gcs(\n gcs_buffer, compression_only, encoding, compression_to_extension\n):\n """\n Compression and encoding should with GCS.\n\n GH 35677 (to_csv, compression), GH 26124 (to_csv, encoding), and\n GH 32392 (read_csv, encoding)\n """\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD")),\n index=Index([f"i-{i}" for i in range(30)]),\n )\n\n # reference of compressed and encoded file\n compression = {"method": compression_only}\n if compression_only == "gzip":\n compression["mtime"] = 1 # be reproducible\n buffer = BytesIO()\n df.to_csv(buffer, compression=compression, encoding=encoding, mode="wb")\n\n # write compressed file with explicit compression\n path_gcs = "gs://test/test.csv"\n df.to_csv(path_gcs, compression=compression, encoding=encoding)\n res = gcs_buffer.getvalue()\n expected = buffer.getvalue()\n assert_equal_zip_safe(res, expected, compression_only)\n\n read_df = read_csv(\n path_gcs, index_col=0, compression=compression_only, encoding=encoding\n )\n tm.assert_frame_equal(df, read_df)\n\n # write compressed file with implicit compression\n file_ext = compression_to_extension[compression_only]\n compression["method"] = "infer"\n path_gcs += f".{file_ext}"\n df.to_csv(path_gcs, compression=compression, encoding=encoding)\n\n res = gcs_buffer.getvalue()\n expected = buffer.getvalue()\n assert_equal_zip_safe(res, expected, compression_only)\n\n read_df = read_csv(path_gcs, index_col=0, compression="infer", encoding=encoding)\n tm.assert_frame_equal(df, read_df)\n\n\ndef test_to_parquet_gcs_new_file(monkeypatch, tmpdir):\n """Regression test for writing to a not-yet-existent GCS Parquet file."""\n pytest.importorskip("fastparquet")\n pytest.importorskip("gcsfs")\n\n from fsspec import AbstractFileSystem\n\n df1 = DataFrame(\n {\n "int": [1, 3],\n "float": [2.0, np.nan],\n "str": ["t", "s"],\n "dt": date_range("2018-06-18", periods=2),\n }\n )\n\n class MockGCSFileSystem(AbstractFileSystem):\n def open(self, path, mode="r", *args):\n if "w" not in mode:\n raise FileNotFoundError\n return open(os.path.join(tmpdir, "test.parquet"), mode, encoding="utf-8")\n\n monkeypatch.setattr("gcsfs.GCSFileSystem", MockGCSFileSystem)\n df1.to_parquet(\n "gs://test/test.csv", index=True, engine="fastparquet", compression=None\n )\n\n\n@td.skip_if_installed("gcsfs")\ndef test_gcs_not_present_exception():\n with tm.external_error_raised(ImportError):\n read_csv("gs://test/test.csv")\n
.venv\Lib\site-packages\pandas\tests\io\test_gcs.py
test_gcs.py
Python
7,334
0.95
0.105263
0.037234
vue-tools
519
2024-01-21T01:22:18.210470
GPL-3.0
true
49b8b6f89f890e89a2d3d3e9a2b25f87
from collections.abc import Iterator\nfrom functools import partial\nfrom io import (\n BytesIO,\n StringIO,\n)\nimport os\nfrom pathlib import Path\nimport re\nimport threading\nfrom urllib.error import URLError\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n NA,\n DataFrame,\n MultiIndex,\n Series,\n Timestamp,\n date_range,\n read_csv,\n read_html,\n to_datetime,\n)\nimport pandas._testing as tm\n\nfrom pandas.io.common import file_path_to_url\n\n\n@pytest.fixture(\n params=[\n "chinese_utf-16.html",\n "chinese_utf-32.html",\n "chinese_utf-8.html",\n "letz_latin1.html",\n ]\n)\ndef html_encoding_file(request, datapath):\n """Parametrized fixture for HTML encoding test filenames."""\n return datapath("io", "data", "html_encoding", request.param)\n\n\ndef assert_framelist_equal(list1, list2, *args, **kwargs):\n assert len(list1) == len(list2), (\n "lists are not of equal size "\n f"len(list1) == {len(list1)}, "\n f"len(list2) == {len(list2)}"\n )\n msg = "not all list elements are DataFrames"\n both_frames = all(\n map(\n lambda x, y: isinstance(x, DataFrame) and isinstance(y, DataFrame),\n list1,\n list2,\n )\n )\n assert both_frames, msg\n for frame_i, frame_j in zip(list1, list2):\n tm.assert_frame_equal(frame_i, frame_j, *args, **kwargs)\n assert not frame_i.empty, "frames are both empty"\n\n\ndef test_bs4_version_fails(monkeypatch, datapath):\n bs4 = pytest.importorskip("bs4")\n pytest.importorskip("html5lib")\n\n monkeypatch.setattr(bs4, "__version__", "4.2")\n with pytest.raises(ImportError, match="Pandas requires version"):\n read_html(datapath("io", "data", "html", "spam.html"), flavor="bs4")\n\n\ndef test_invalid_flavor():\n url = "google.com"\n flavor = "invalid flavor"\n msg = r"\{" + flavor + r"\} is not a valid set of flavors"\n\n with pytest.raises(ValueError, match=msg):\n read_html(StringIO(url), match="google", flavor=flavor)\n\n\ndef test_same_ordering(datapath):\n pytest.importorskip("bs4")\n pytest.importorskip("lxml")\n pytest.importorskip("html5lib")\n\n filename = datapath("io", "data", "html", "valid_markup.html")\n dfs_lxml = read_html(filename, index_col=0, flavor=["lxml"])\n dfs_bs4 = read_html(filename, index_col=0, flavor=["bs4"])\n assert_framelist_equal(dfs_lxml, dfs_bs4)\n\n\n@pytest.fixture(\n params=[\n pytest.param("bs4", marks=[td.skip_if_no("bs4"), td.skip_if_no("html5lib")]),\n pytest.param("lxml", marks=td.skip_if_no("lxml")),\n ],\n)\ndef flavor_read_html(request):\n return partial(read_html, flavor=request.param)\n\n\nclass TestReadHtml:\n def test_literal_html_deprecation(self, flavor_read_html):\n # GH 53785\n msg = (\n "Passing literal html to 'read_html' is deprecated and "\n "will be removed in a future version. To read from a "\n "literal string, wrap it in a 'StringIO' object."\n )\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n flavor_read_html(\n """<table>\n <thead>\n <tr>\n <th>A</th>\n <th>B</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>1</td>\n <td>2</td>\n </tr>\n </tbody>\n <tbody>\n <tr>\n <td>3</td>\n <td>4</td>\n </tr>\n </tbody>\n </table>"""\n )\n\n @pytest.fixture\n def spam_data(self, datapath):\n return datapath("io", "data", "html", "spam.html")\n\n @pytest.fixture\n def banklist_data(self, datapath):\n return datapath("io", "data", "html", "banklist.html")\n\n def test_to_html_compat(self, flavor_read_html):\n df = (\n DataFrame(\n np.random.default_rng(2).random((4, 3)),\n columns=pd.Index(list("abc")),\n )\n # pylint: disable-next=consider-using-f-string\n .map("{:.3f}".format).astype(float)\n )\n out = df.to_html()\n res = flavor_read_html(\n StringIO(out), attrs={"class": "dataframe"}, index_col=0\n )[0]\n tm.assert_frame_equal(res, df)\n\n def test_dtype_backend(self, string_storage, dtype_backend, flavor_read_html):\n # GH#50286\n df = DataFrame(\n {\n "a": Series([1, np.nan, 3], dtype="Int64"),\n "b": Series([1, 2, 3], dtype="Int64"),\n "c": Series([1.5, np.nan, 2.5], dtype="Float64"),\n "d": Series([1.5, 2.0, 2.5], dtype="Float64"),\n "e": [True, False, None],\n "f": [True, False, True],\n "g": ["a", "b", "c"],\n "h": ["a", "b", None],\n }\n )\n\n out = df.to_html(index=False)\n with pd.option_context("mode.string_storage", string_storage):\n result = flavor_read_html(StringIO(out), dtype_backend=dtype_backend)[0]\n\n if dtype_backend == "pyarrow":\n pa = pytest.importorskip("pyarrow")\n string_dtype = pd.ArrowDtype(pa.string())\n else:\n string_dtype = pd.StringDtype(string_storage)\n\n expected = DataFrame(\n {\n "a": Series([1, np.nan, 3], dtype="Int64"),\n "b": Series([1, 2, 3], dtype="Int64"),\n "c": Series([1.5, np.nan, 2.5], dtype="Float64"),\n "d": Series([1.5, 2.0, 2.5], dtype="Float64"),\n "e": Series([True, False, NA], dtype="boolean"),\n "f": Series([True, False, True], dtype="boolean"),\n "g": Series(["a", "b", "c"], dtype=string_dtype),\n "h": Series(["a", "b", None], dtype=string_dtype),\n }\n )\n\n if dtype_backend == "pyarrow":\n import pyarrow as pa\n\n from pandas.arrays import ArrowExtensionArray\n\n expected = DataFrame(\n {\n col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))\n for col in expected.columns\n }\n )\n\n # the storage of the str columns' Index is also affected by the\n # string_storage setting -> ignore that for checking the result\n tm.assert_frame_equal(result, expected, check_column_type=False)\n\n @pytest.mark.network\n @pytest.mark.single_cpu\n def test_banklist_url(self, httpserver, banklist_data, flavor_read_html):\n with open(banklist_data, encoding="utf-8") as f:\n httpserver.serve_content(content=f.read())\n df1 = flavor_read_html(\n # lxml cannot find attrs leave out for now\n httpserver.url,\n match="First Federal Bank of Florida", # attrs={"class": "dataTable"}\n )\n # lxml cannot find attrs leave out for now\n df2 = flavor_read_html(\n httpserver.url,\n match="Metcalf Bank",\n ) # attrs={"class": "dataTable"})\n\n assert_framelist_equal(df1, df2)\n\n @pytest.mark.network\n @pytest.mark.single_cpu\n def test_spam_url(self, httpserver, spam_data, flavor_read_html):\n with open(spam_data, encoding="utf-8") as f:\n httpserver.serve_content(content=f.read())\n df1 = flavor_read_html(httpserver.url, match=".*Water.*")\n df2 = flavor_read_html(httpserver.url, match="Unit")\n\n assert_framelist_equal(df1, df2)\n\n @pytest.mark.slow\n def test_banklist(self, banklist_data, flavor_read_html):\n df1 = flavor_read_html(\n banklist_data, match=".*Florida.*", attrs={"id": "table"}\n )\n df2 = flavor_read_html(\n banklist_data, match="Metcalf Bank", attrs={"id": "table"}\n )\n\n assert_framelist_equal(df1, df2)\n\n def test_spam(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*")\n df2 = flavor_read_html(spam_data, match="Unit")\n assert_framelist_equal(df1, df2)\n\n assert df1[0].iloc[0, 0] == "Proximates"\n assert df1[0].columns[0] == "Nutrient"\n\n def test_spam_no_match(self, spam_data, flavor_read_html):\n dfs = flavor_read_html(spam_data)\n for df in dfs:\n assert isinstance(df, DataFrame)\n\n def test_banklist_no_match(self, banklist_data, flavor_read_html):\n dfs = flavor_read_html(banklist_data, attrs={"id": "table"})\n for df in dfs:\n assert isinstance(df, DataFrame)\n\n def test_spam_header(self, spam_data, flavor_read_html):\n df = flavor_read_html(spam_data, match=".*Water.*", header=2)[0]\n assert df.columns[0] == "Proximates"\n assert not df.empty\n\n def test_skiprows_int(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=1)\n df2 = flavor_read_html(spam_data, match="Unit", skiprows=1)\n\n assert_framelist_equal(df1, df2)\n\n def test_skiprows_range(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=range(2))\n df2 = flavor_read_html(spam_data, match="Unit", skiprows=range(2))\n\n assert_framelist_equal(df1, df2)\n\n def test_skiprows_list(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=[1, 2])\n df2 = flavor_read_html(spam_data, match="Unit", skiprows=[2, 1])\n\n assert_framelist_equal(df1, df2)\n\n def test_skiprows_set(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows={1, 2})\n df2 = flavor_read_html(spam_data, match="Unit", skiprows={2, 1})\n\n assert_framelist_equal(df1, df2)\n\n def test_skiprows_slice(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=1)\n df2 = flavor_read_html(spam_data, match="Unit", skiprows=1)\n\n assert_framelist_equal(df1, df2)\n\n def test_skiprows_slice_short(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=slice(2))\n df2 = flavor_read_html(spam_data, match="Unit", skiprows=slice(2))\n\n assert_framelist_equal(df1, df2)\n\n def test_skiprows_slice_long(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=slice(2, 5))\n df2 = flavor_read_html(spam_data, match="Unit", skiprows=slice(4, 1, -1))\n\n assert_framelist_equal(df1, df2)\n\n def test_skiprows_ndarray(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", skiprows=np.arange(2))\n df2 = flavor_read_html(spam_data, match="Unit", skiprows=np.arange(2))\n\n assert_framelist_equal(df1, df2)\n\n def test_skiprows_invalid(self, spam_data, flavor_read_html):\n with pytest.raises(TypeError, match=("is not a valid type for skipping rows")):\n flavor_read_html(spam_data, match=".*Water.*", skiprows="asdf")\n\n def test_index(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", index_col=0)\n df2 = flavor_read_html(spam_data, match="Unit", index_col=0)\n assert_framelist_equal(df1, df2)\n\n def test_header_and_index_no_types(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", header=1, index_col=0)\n df2 = flavor_read_html(spam_data, match="Unit", header=1, index_col=0)\n assert_framelist_equal(df1, df2)\n\n def test_header_and_index_with_types(self, spam_data, flavor_read_html):\n df1 = flavor_read_html(spam_data, match=".*Water.*", header=1, index_col=0)\n df2 = flavor_read_html(spam_data, match="Unit", header=1, index_col=0)\n assert_framelist_equal(df1, df2)\n\n def test_infer_types(self, spam_data, flavor_read_html):\n # 10892 infer_types removed\n df1 = flavor_read_html(spam_data, match=".*Water.*", index_col=0)\n df2 = flavor_read_html(spam_data, match="Unit", index_col=0)\n assert_framelist_equal(df1, df2)\n\n def test_string_io(self, spam_data, flavor_read_html):\n with open(spam_data, encoding="UTF-8") as f:\n data1 = StringIO(f.read())\n\n with open(spam_data, encoding="UTF-8") as f:\n data2 = StringIO(f.read())\n\n df1 = flavor_read_html(data1, match=".*Water.*")\n df2 = flavor_read_html(data2, match="Unit")\n assert_framelist_equal(df1, df2)\n\n def test_string(self, spam_data, flavor_read_html):\n with open(spam_data, encoding="UTF-8") as f:\n data = f.read()\n\n df1 = flavor_read_html(StringIO(data), match=".*Water.*")\n df2 = flavor_read_html(StringIO(data), match="Unit")\n\n assert_framelist_equal(df1, df2)\n\n def test_file_like(self, spam_data, flavor_read_html):\n with open(spam_data, encoding="UTF-8") as f:\n df1 = flavor_read_html(f, match=".*Water.*")\n\n with open(spam_data, encoding="UTF-8") as f:\n df2 = flavor_read_html(f, match="Unit")\n\n assert_framelist_equal(df1, df2)\n\n @pytest.mark.network\n @pytest.mark.single_cpu\n def test_bad_url_protocol(self, httpserver, flavor_read_html):\n httpserver.serve_content("urlopen error unknown url type: git", code=404)\n with pytest.raises(URLError, match="urlopen error unknown url type: git"):\n flavor_read_html("git://github.com", match=".*Water.*")\n\n @pytest.mark.slow\n @pytest.mark.network\n @pytest.mark.single_cpu\n def test_invalid_url(self, httpserver, flavor_read_html):\n httpserver.serve_content("Name or service not known", code=404)\n with pytest.raises((URLError, ValueError), match="HTTP Error 404: NOT FOUND"):\n flavor_read_html(httpserver.url, match=".*Water.*")\n\n @pytest.mark.slow\n def test_file_url(self, banklist_data, flavor_read_html):\n url = banklist_data\n dfs = flavor_read_html(\n file_path_to_url(os.path.abspath(url)), match="First", attrs={"id": "table"}\n )\n assert isinstance(dfs, list)\n for df in dfs:\n assert isinstance(df, DataFrame)\n\n @pytest.mark.slow\n def test_invalid_table_attrs(self, banklist_data, flavor_read_html):\n url = banklist_data\n with pytest.raises(ValueError, match="No tables found"):\n flavor_read_html(\n url, match="First Federal Bank of Florida", attrs={"id": "tasdfable"}\n )\n\n @pytest.mark.slow\n def test_multiindex_header(self, banklist_data, flavor_read_html):\n df = flavor_read_html(\n banklist_data, match="Metcalf", attrs={"id": "table"}, header=[0, 1]\n )[0]\n assert isinstance(df.columns, MultiIndex)\n\n @pytest.mark.slow\n def test_multiindex_index(self, banklist_data, flavor_read_html):\n df = flavor_read_html(\n banklist_data, match="Metcalf", attrs={"id": "table"}, index_col=[0, 1]\n )[0]\n assert isinstance(df.index, MultiIndex)\n\n @pytest.mark.slow\n def test_multiindex_header_index(self, banklist_data, flavor_read_html):\n df = flavor_read_html(\n banklist_data,\n match="Metcalf",\n attrs={"id": "table"},\n header=[0, 1],\n index_col=[0, 1],\n )[0]\n assert isinstance(df.columns, MultiIndex)\n assert isinstance(df.index, MultiIndex)\n\n @pytest.mark.slow\n def test_multiindex_header_skiprows_tuples(self, banklist_data, flavor_read_html):\n df = flavor_read_html(\n banklist_data,\n match="Metcalf",\n attrs={"id": "table"},\n header=[0, 1],\n skiprows=1,\n )[0]\n assert isinstance(df.columns, MultiIndex)\n\n @pytest.mark.slow\n def test_multiindex_header_skiprows(self, banklist_data, flavor_read_html):\n df = flavor_read_html(\n banklist_data,\n match="Metcalf",\n attrs={"id": "table"},\n header=[0, 1],\n skiprows=1,\n )[0]\n assert isinstance(df.columns, MultiIndex)\n\n @pytest.mark.slow\n def test_multiindex_header_index_skiprows(self, banklist_data, flavor_read_html):\n df = flavor_read_html(\n banklist_data,\n match="Metcalf",\n attrs={"id": "table"},\n header=[0, 1],\n index_col=[0, 1],\n skiprows=1,\n )[0]\n assert isinstance(df.index, MultiIndex)\n assert isinstance(df.columns, MultiIndex)\n\n @pytest.mark.slow\n def test_regex_idempotency(self, banklist_data, flavor_read_html):\n url = banklist_data\n dfs = flavor_read_html(\n file_path_to_url(os.path.abspath(url)),\n match=re.compile(re.compile("Florida")),\n attrs={"id": "table"},\n )\n assert isinstance(dfs, list)\n for df in dfs:\n assert isinstance(df, DataFrame)\n\n def test_negative_skiprows(self, spam_data, flavor_read_html):\n msg = r"\(you passed a negative value\)"\n with pytest.raises(ValueError, match=msg):\n flavor_read_html(spam_data, match="Water", skiprows=-1)\n\n @pytest.fixture\n def python_docs(self):\n return """\n <table class="contentstable" align="center"><tr>\n <td width="50%">\n <p class="biglink"><a class="biglink" href="whatsnew/2.7.html">What's new in Python 2.7?</a><br/>\n <span class="linkdescr">or <a href="whatsnew/index.html">all "What's new" documents</a> since 2.0</span></p>\n <p class="biglink"><a class="biglink" href="tutorial/index.html">Tutorial</a><br/>\n <span class="linkdescr">start here</span></p>\n <p class="biglink"><a class="biglink" href="library/index.html">Library Reference</a><br/>\n <span class="linkdescr">keep this under your pillow</span></p>\n <p class="biglink"><a class="biglink" href="reference/index.html">Language Reference</a><br/>\n <span class="linkdescr">describes syntax and language elements</span></p>\n <p class="biglink"><a class="biglink" href="using/index.html">Python Setup and Usage</a><br/>\n <span class="linkdescr">how to use Python on different platforms</span></p>\n <p class="biglink"><a class="biglink" href="howto/index.html">Python HOWTOs</a><br/>\n <span class="linkdescr">in-depth documents on specific topics</span></p>\n </td><td width="50%">\n <p class="biglink"><a class="biglink" href="installing/index.html">Installing Python Modules</a><br/>\n <span class="linkdescr">installing from the Python Package Index &amp; other sources</span></p>\n <p class="biglink"><a class="biglink" href="distributing/index.html">Distributing Python Modules</a><br/>\n <span class="linkdescr">publishing modules for installation by others</span></p>\n <p class="biglink"><a class="biglink" href="extending/index.html">Extending and Embedding</a><br/>\n <span class="linkdescr">tutorial for C/C++ programmers</span></p>\n <p class="biglink"><a class="biglink" href="c-api/index.html">Python/C API</a><br/>\n <span class="linkdescr">reference for C/C++ programmers</span></p>\n <p class="biglink"><a class="biglink" href="faq/index.html">FAQs</a><br/>\n <span class="linkdescr">frequently asked questions (with answers!)</span></p>\n </td></tr>\n </table>\n\n <p><strong>Indices and tables:</strong></p>\n <table class="contentstable" align="center"><tr>\n <td width="50%">\n <p class="biglink"><a class="biglink" href="py-modindex.html">Python Global Module Index</a><br/>\n <span class="linkdescr">quick access to all modules</span></p>\n <p class="biglink"><a class="biglink" href="genindex.html">General Index</a><br/>\n <span class="linkdescr">all functions, classes, terms</span></p>\n <p class="biglink"><a class="biglink" href="glossary.html">Glossary</a><br/>\n <span class="linkdescr">the most important terms explained</span></p>\n </td><td width="50%">\n <p class="biglink"><a class="biglink" href="search.html">Search page</a><br/>\n <span class="linkdescr">search this documentation</span></p>\n <p class="biglink"><a class="biglink" href="contents.html">Complete Table of Contents</a><br/>\n <span class="linkdescr">lists all sections and subsections</span></p>\n </td></tr>\n </table>\n """ # noqa: E501\n\n @pytest.mark.network\n @pytest.mark.single_cpu\n def test_multiple_matches(self, python_docs, httpserver, flavor_read_html):\n httpserver.serve_content(content=python_docs)\n dfs = flavor_read_html(httpserver.url, match="Python")\n assert len(dfs) > 1\n\n @pytest.mark.network\n @pytest.mark.single_cpu\n def test_python_docs_table(self, python_docs, httpserver, flavor_read_html):\n httpserver.serve_content(content=python_docs)\n dfs = flavor_read_html(httpserver.url, match="Python")\n zz = [df.iloc[0, 0][0:4] for df in dfs]\n assert sorted(zz) == ["Pyth", "What"]\n\n def test_empty_tables(self, flavor_read_html):\n """\n Make sure that read_html ignores empty tables.\n """\n html = """\n <table>\n <thead>\n <tr>\n <th>A</th>\n <th>B</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>1</td>\n <td>2</td>\n </tr>\n </tbody>\n </table>\n <table>\n <tbody>\n </tbody>\n </table>\n """\n result = flavor_read_html(StringIO(html))\n assert len(result) == 1\n\n def test_multiple_tbody(self, flavor_read_html):\n # GH-20690\n # Read all tbody tags within a single table.\n result = flavor_read_html(\n StringIO(\n """<table>\n <thead>\n <tr>\n <th>A</th>\n <th>B</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>1</td>\n <td>2</td>\n </tr>\n </tbody>\n <tbody>\n <tr>\n <td>3</td>\n <td>4</td>\n </tr>\n </tbody>\n </table>"""\n )\n )[0]\n\n expected = DataFrame(data=[[1, 2], [3, 4]], columns=["A", "B"])\n\n tm.assert_frame_equal(result, expected)\n\n def test_header_and_one_column(self, flavor_read_html):\n """\n Don't fail with bs4 when there is a header and only one column\n as described in issue #9178\n """\n result = flavor_read_html(\n StringIO(\n """<table>\n <thead>\n <tr>\n <th>Header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>first</td>\n </tr>\n </tbody>\n </table>"""\n )\n )[0]\n\n expected = DataFrame(data={"Header": "first"}, index=[0])\n\n tm.assert_frame_equal(result, expected)\n\n def test_thead_without_tr(self, flavor_read_html):\n """\n Ensure parser adds <tr> within <thead> on malformed HTML.\n """\n result = flavor_read_html(\n StringIO(\n """<table>\n <thead>\n <tr>\n <th>Country</th>\n <th>Municipality</th>\n <th>Year</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Ukraine</td>\n <th>Odessa</th>\n <td>1944</td>\n </tr>\n </tbody>\n </table>"""\n )\n )[0]\n\n expected = DataFrame(\n data=[["Ukraine", "Odessa", 1944]],\n columns=["Country", "Municipality", "Year"],\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_tfoot_read(self, flavor_read_html):\n """\n Make sure that read_html reads tfoot, containing td or th.\n Ignores empty tfoot\n """\n data_template = """<table>\n <thead>\n <tr>\n <th>A</th>\n <th>B</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>bodyA</td>\n <td>bodyB</td>\n </tr>\n </tbody>\n <tfoot>\n {footer}\n </tfoot>\n </table>"""\n\n expected1 = DataFrame(data=[["bodyA", "bodyB"]], columns=["A", "B"])\n\n expected2 = DataFrame(\n data=[["bodyA", "bodyB"], ["footA", "footB"]], columns=["A", "B"]\n )\n\n data1 = data_template.format(footer="")\n data2 = data_template.format(footer="<tr><td>footA</td><th>footB</th></tr>")\n\n result1 = flavor_read_html(StringIO(data1))[0]\n result2 = flavor_read_html(StringIO(data2))[0]\n\n tm.assert_frame_equal(result1, expected1)\n tm.assert_frame_equal(result2, expected2)\n\n def test_parse_header_of_non_string_column(self, flavor_read_html):\n # GH5048: if header is specified explicitly, an int column should be\n # parsed as int while its header is parsed as str\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <tr>\n <td>S</td>\n <td>I</td>\n </tr>\n <tr>\n <td>text</td>\n <td>1944</td>\n </tr>\n </table>\n """\n ),\n header=0,\n )[0]\n\n expected = DataFrame([["text", 1944]], columns=("S", "I"))\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.slow\n def test_banklist_header(self, banklist_data, datapath, flavor_read_html):\n from pandas.io.html import _remove_whitespace\n\n def try_remove_ws(x):\n try:\n return _remove_whitespace(x)\n except AttributeError:\n return x\n\n df = flavor_read_html(banklist_data, match="Metcalf", attrs={"id": "table"})[0]\n ground_truth = read_csv(\n datapath("io", "data", "csv", "banklist.csv"),\n converters={"Updated Date": Timestamp, "Closing Date": Timestamp},\n )\n assert df.shape == ground_truth.shape\n old = [\n "First Vietnamese American Bank In Vietnamese",\n "Westernbank Puerto Rico En Espanol",\n "R-G Premier Bank of Puerto Rico En Espanol",\n "Eurobank En Espanol",\n "Sanderson State Bank En Espanol",\n "Washington Mutual Bank (Including its subsidiary Washington "\n "Mutual Bank FSB)",\n "Silver State Bank En Espanol",\n "AmTrade International Bank En Espanol",\n "Hamilton Bank, NA En Espanol",\n "The Citizens Savings Bank Pioneer Community Bank, Inc.",\n ]\n new = [\n "First Vietnamese American Bank",\n "Westernbank Puerto Rico",\n "R-G Premier Bank of Puerto Rico",\n "Eurobank",\n "Sanderson State Bank",\n "Washington Mutual Bank",\n "Silver State Bank",\n "AmTrade International Bank",\n "Hamilton Bank, NA",\n "The Citizens Savings Bank",\n ]\n dfnew = df.map(try_remove_ws).replace(old, new)\n gtnew = ground_truth.map(try_remove_ws)\n converted = dfnew\n date_cols = ["Closing Date", "Updated Date"]\n converted[date_cols] = converted[date_cols].apply(to_datetime)\n tm.assert_frame_equal(converted, gtnew)\n\n @pytest.mark.slow\n def test_gold_canyon(self, banklist_data, flavor_read_html):\n gc = "Gold Canyon"\n with open(banklist_data, encoding="utf-8") as f:\n raw_text = f.read()\n\n assert gc in raw_text\n df = flavor_read_html(\n banklist_data, match="Gold Canyon", attrs={"id": "table"}\n )[0]\n assert gc in df.to_string()\n\n def test_different_number_of_cols(self, flavor_read_html):\n expected = flavor_read_html(\n StringIO(\n """<table>\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>C_l0_g0</th>\n <th>C_l0_g1</th>\n <th>C_l0_g2</th>\n <th>C_l0_g3</th>\n <th>C_l0_g4</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>R_l0_g0</th>\n <td> 0.763</td>\n <td> 0.233</td>\n <td> nan</td>\n <td> nan</td>\n <td> nan</td>\n </tr>\n <tr>\n <th>R_l0_g1</th>\n <td> 0.244</td>\n <td> 0.285</td>\n <td> 0.392</td>\n <td> 0.137</td>\n <td> 0.222</td>\n </tr>\n </tbody>\n </table>"""\n ),\n index_col=0,\n )[0]\n\n result = flavor_read_html(\n StringIO(\n """<table>\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>C_l0_g0</th>\n <th>C_l0_g1</th>\n <th>C_l0_g2</th>\n <th>C_l0_g3</th>\n <th>C_l0_g4</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>R_l0_g0</th>\n <td> 0.763</td>\n <td> 0.233</td>\n </tr>\n <tr>\n <th>R_l0_g1</th>\n <td> 0.244</td>\n <td> 0.285</td>\n <td> 0.392</td>\n <td> 0.137</td>\n <td> 0.222</td>\n </tr>\n </tbody>\n </table>"""\n ),\n index_col=0,\n )[0]\n\n tm.assert_frame_equal(result, expected)\n\n def test_colspan_rowspan_1(self, flavor_read_html):\n # GH17054\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <tr>\n <th>A</th>\n <th colspan="1">B</th>\n <th rowspan="1">C</th>\n </tr>\n <tr>\n <td>a</td>\n <td>b</td>\n <td>c</td>\n </tr>\n </table>\n """\n )\n )[0]\n\n expected = DataFrame([["a", "b", "c"]], columns=["A", "B", "C"])\n\n tm.assert_frame_equal(result, expected)\n\n def test_colspan_rowspan_copy_values(self, flavor_read_html):\n # GH17054\n\n # In ASCII, with lowercase letters being copies:\n #\n # X x Y Z W\n # A B b z C\n\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <tr>\n <td colspan="2">X</td>\n <td>Y</td>\n <td rowspan="2">Z</td>\n <td>W</td>\n </tr>\n <tr>\n <td>A</td>\n <td colspan="2">B</td>\n <td>C</td>\n </tr>\n </table>\n """\n ),\n header=0,\n )[0]\n\n expected = DataFrame(\n data=[["A", "B", "B", "Z", "C"]], columns=["X", "X.1", "Y", "Z", "W"]\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_colspan_rowspan_both_not_1(self, flavor_read_html):\n # GH17054\n\n # In ASCII, with lowercase letters being copies:\n #\n # A B b b C\n # a b b b D\n\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <tr>\n <td rowspan="2">A</td>\n <td rowspan="2" colspan="3">B</td>\n <td>C</td>\n </tr>\n <tr>\n <td>D</td>\n </tr>\n </table>\n """\n ),\n header=0,\n )[0]\n\n expected = DataFrame(\n data=[["A", "B", "B", "B", "D"]], columns=["A", "B", "B.1", "B.2", "C"]\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_rowspan_at_end_of_row(self, flavor_read_html):\n # GH17054\n\n # In ASCII, with lowercase letters being copies:\n #\n # A B\n # C b\n\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <tr>\n <td>A</td>\n <td rowspan="2">B</td>\n </tr>\n <tr>\n <td>C</td>\n </tr>\n </table>\n """\n ),\n header=0,\n )[0]\n\n expected = DataFrame(data=[["C", "B"]], columns=["A", "B"])\n\n tm.assert_frame_equal(result, expected)\n\n def test_rowspan_only_rows(self, flavor_read_html):\n # GH17054\n\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <tr>\n <td rowspan="3">A</td>\n <td rowspan="3">B</td>\n </tr>\n </table>\n """\n ),\n header=0,\n )[0]\n\n expected = DataFrame(data=[["A", "B"], ["A", "B"]], columns=["A", "B"])\n\n tm.assert_frame_equal(result, expected)\n\n def test_header_inferred_from_rows_with_only_th(self, flavor_read_html):\n # GH17054\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <tr>\n <th>A</th>\n <th>B</th>\n </tr>\n <tr>\n <th>a</th>\n <th>b</th>\n </tr>\n <tr>\n <td>1</td>\n <td>2</td>\n </tr>\n </table>\n """\n )\n )[0]\n\n columns = MultiIndex(levels=[["A", "B"], ["a", "b"]], codes=[[0, 1], [0, 1]])\n expected = DataFrame(data=[[1, 2]], columns=columns)\n\n tm.assert_frame_equal(result, expected)\n\n def test_parse_dates_list(self, flavor_read_html):\n df = DataFrame({"date": date_range("1/1/2001", periods=10)})\n expected = df.to_html()\n res = flavor_read_html(StringIO(expected), parse_dates=[1], index_col=0)\n tm.assert_frame_equal(df, res[0])\n res = flavor_read_html(StringIO(expected), parse_dates=["date"], index_col=0)\n tm.assert_frame_equal(df, res[0])\n\n def test_parse_dates_combine(self, flavor_read_html):\n raw_dates = Series(date_range("1/1/2001", periods=10))\n df = DataFrame(\n {\n "date": raw_dates.map(lambda x: str(x.date())),\n "time": raw_dates.map(lambda x: str(x.time())),\n }\n )\n res = flavor_read_html(\n StringIO(df.to_html()), parse_dates={"datetime": [1, 2]}, index_col=1\n )\n newdf = DataFrame({"datetime": raw_dates})\n tm.assert_frame_equal(newdf, res[0])\n\n def test_wikipedia_states_table(self, datapath, flavor_read_html):\n data = datapath("io", "data", "html", "wikipedia_states.html")\n assert os.path.isfile(data), f"{repr(data)} is not a file"\n assert os.path.getsize(data), f"{repr(data)} is an empty file"\n result = flavor_read_html(data, match="Arizona", header=1)[0]\n assert result.shape == (60, 12)\n assert "Unnamed" in result.columns[-1]\n assert result["sq mi"].dtype == np.dtype("float64")\n assert np.allclose(result.loc[0, "sq mi"], 665384.04)\n\n def test_wikipedia_states_multiindex(self, datapath, flavor_read_html):\n data = datapath("io", "data", "html", "wikipedia_states.html")\n result = flavor_read_html(data, match="Arizona", index_col=0)[0]\n assert result.shape == (60, 11)\n assert "Unnamed" in result.columns[-1][1]\n assert result.columns.nlevels == 2\n assert np.allclose(result.loc["Alaska", ("Total area[2]", "sq mi")], 665384.04)\n\n def test_parser_error_on_empty_header_row(self, flavor_read_html):\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <thead>\n <tr><th></th><th></tr>\n <tr><th>A</th><th>B</th></tr>\n </thead>\n <tbody>\n <tr><td>a</td><td>b</td></tr>\n </tbody>\n </table>\n """\n ),\n header=[0, 1],\n )\n expected = DataFrame(\n [["a", "b"]],\n columns=MultiIndex.from_tuples(\n [("Unnamed: 0_level_0", "A"), ("Unnamed: 1_level_0", "B")]\n ),\n )\n tm.assert_frame_equal(result[0], expected)\n\n def test_decimal_rows(self, flavor_read_html):\n # GH 12907\n result = flavor_read_html(\n StringIO(\n """<html>\n <body>\n <table>\n <thead>\n <tr>\n <th>Header</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>1100#101</td>\n </tr>\n </tbody>\n </table>\n </body>\n </html>"""\n ),\n decimal="#",\n )[0]\n\n expected = DataFrame(data={"Header": 1100.101}, index=[0])\n\n assert result["Header"].dtype == np.dtype("float64")\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("arg", [True, False])\n def test_bool_header_arg(self, spam_data, arg, flavor_read_html):\n # GH 6114\n msg = re.escape(\n "Passing a bool to header is invalid. Use header=None for no header or "\n "header=int or list-like of ints to specify the row(s) making up the "\n "column names"\n )\n with pytest.raises(TypeError, match=msg):\n flavor_read_html(spam_data, header=arg)\n\n def test_converters(self, flavor_read_html):\n # GH 13461\n result = flavor_read_html(\n StringIO(\n """<table>\n <thead>\n <tr>\n <th>a</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td> 0.763</td>\n </tr>\n <tr>\n <td> 0.244</td>\n </tr>\n </tbody>\n </table>"""\n ),\n converters={"a": str},\n )[0]\n\n expected = DataFrame({"a": ["0.763", "0.244"]})\n\n tm.assert_frame_equal(result, expected)\n\n def test_na_values(self, flavor_read_html):\n # GH 13461\n result = flavor_read_html(\n StringIO(\n """<table>\n <thead>\n <tr>\n <th>a</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td> 0.763</td>\n </tr>\n <tr>\n <td> 0.244</td>\n </tr>\n </tbody>\n </table>"""\n ),\n na_values=[0.244],\n )[0]\n\n expected = DataFrame({"a": [0.763, np.nan]})\n\n tm.assert_frame_equal(result, expected)\n\n def test_keep_default_na(self, flavor_read_html):\n html_data = """<table>\n <thead>\n <tr>\n <th>a</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td> N/A</td>\n </tr>\n <tr>\n <td> NA</td>\n </tr>\n </tbody>\n </table>"""\n\n expected_df = DataFrame({"a": ["N/A", "NA"]})\n html_df = flavor_read_html(StringIO(html_data), keep_default_na=False)[0]\n tm.assert_frame_equal(expected_df, html_df)\n\n expected_df = DataFrame({"a": [np.nan, np.nan]})\n html_df = flavor_read_html(StringIO(html_data), keep_default_na=True)[0]\n tm.assert_frame_equal(expected_df, html_df)\n\n def test_preserve_empty_rows(self, flavor_read_html):\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <tr>\n <th>A</th>\n <th>B</th>\n </tr>\n <tr>\n <td>a</td>\n <td>b</td>\n </tr>\n <tr>\n <td></td>\n <td></td>\n </tr>\n </table>\n """\n )\n )[0]\n\n expected = DataFrame(data=[["a", "b"], [np.nan, np.nan]], columns=["A", "B"])\n\n tm.assert_frame_equal(result, expected)\n\n def test_ignore_empty_rows_when_inferring_header(self, flavor_read_html):\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <thead>\n <tr><th></th><th></tr>\n <tr><th>A</th><th>B</th></tr>\n <tr><th>a</th><th>b</th></tr>\n </thead>\n <tbody>\n <tr><td>1</td><td>2</td></tr>\n </tbody>\n </table>\n """\n )\n )[0]\n\n columns = MultiIndex(levels=[["A", "B"], ["a", "b"]], codes=[[0, 1], [0, 1]])\n expected = DataFrame(data=[[1, 2]], columns=columns)\n\n tm.assert_frame_equal(result, expected)\n\n def test_multiple_header_rows(self, flavor_read_html):\n # Issue #13434\n expected_df = DataFrame(\n data=[("Hillary", 68, "D"), ("Bernie", 74, "D"), ("Donald", 69, "R")]\n )\n expected_df.columns = [\n ["Unnamed: 0_level_0", "Age", "Party"],\n ["Name", "Unnamed: 1_level_1", "Unnamed: 2_level_1"],\n ]\n html = expected_df.to_html(index=False)\n html_df = flavor_read_html(StringIO(html))[0]\n tm.assert_frame_equal(expected_df, html_df)\n\n def test_works_on_valid_markup(self, datapath, flavor_read_html):\n filename = datapath("io", "data", "html", "valid_markup.html")\n dfs = flavor_read_html(filename, index_col=0)\n assert isinstance(dfs, list)\n assert isinstance(dfs[0], DataFrame)\n\n @pytest.mark.slow\n def test_fallback_success(self, datapath, flavor_read_html):\n banklist_data = datapath("io", "data", "html", "banklist.html")\n\n flavor_read_html(banklist_data, match=".*Water.*", flavor=["lxml", "html5lib"])\n\n def test_to_html_timestamp(self):\n rng = date_range("2000-01-01", periods=10)\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=rng)\n\n result = df.to_html()\n assert "2000-01-01" in result\n\n def test_to_html_borderless(self):\n df = DataFrame([{"A": 1, "B": 2}])\n out_border_default = df.to_html()\n out_border_true = df.to_html(border=True)\n out_border_explicit_default = df.to_html(border=1)\n out_border_nondefault = df.to_html(border=2)\n out_border_zero = df.to_html(border=0)\n\n out_border_false = df.to_html(border=False)\n\n assert ' border="1"' in out_border_default\n assert out_border_true == out_border_default\n assert out_border_default == out_border_explicit_default\n assert out_border_default != out_border_nondefault\n assert ' border="2"' in out_border_nondefault\n assert ' border="0"' not in out_border_zero\n assert " border" not in out_border_false\n assert out_border_zero == out_border_false\n\n @pytest.mark.parametrize(\n "displayed_only,exp0,exp1",\n [\n (True, DataFrame(["foo"]), None),\n (False, DataFrame(["foo bar baz qux"]), DataFrame(["foo"])),\n ],\n )\n def test_displayed_only(self, displayed_only, exp0, exp1, flavor_read_html):\n # GH 20027\n data = """<html>\n <body>\n <table>\n <tr>\n <td>\n foo\n <span style="display:none;text-align:center">bar</span>\n <span style="display:none">baz</span>\n <span style="display: none">qux</span>\n </td>\n </tr>\n </table>\n <table style="display: none">\n <tr>\n <td>foo</td>\n </tr>\n </table>\n </body>\n </html>"""\n\n dfs = flavor_read_html(StringIO(data), displayed_only=displayed_only)\n tm.assert_frame_equal(dfs[0], exp0)\n\n if exp1 is not None:\n tm.assert_frame_equal(dfs[1], exp1)\n else:\n assert len(dfs) == 1 # Should not parse hidden table\n\n @pytest.mark.parametrize("displayed_only", [True, False])\n def test_displayed_only_with_many_elements(self, displayed_only, flavor_read_html):\n html_table = """\n <table>\n <tr>\n <th>A</th>\n <th>B</th>\n </tr>\n <tr>\n <td>1</td>\n <td>2</td>\n </tr>\n <tr>\n <td><span style="display:none"></span>4</td>\n <td>5</td>\n </tr>\n </table>\n """\n result = flavor_read_html(StringIO(html_table), displayed_only=displayed_only)[\n 0\n ]\n expected = DataFrame({"A": [1, 4], "B": [2, 5]})\n tm.assert_frame_equal(result, expected)\n\n @td.skip_if_windows()\n @pytest.mark.filterwarnings(\n "ignore:You provided Unicode markup but also provided a value for "\n "from_encoding.*:UserWarning"\n )\n def test_encode(self, html_encoding_file, flavor_read_html):\n base_path = os.path.basename(html_encoding_file)\n root = os.path.splitext(base_path)[0]\n _, encoding = root.split("_")\n\n try:\n with open(html_encoding_file, "rb") as fobj:\n from_string = flavor_read_html(\n fobj.read(), encoding=encoding, index_col=0\n ).pop()\n\n with open(html_encoding_file, "rb") as fobj:\n from_file_like = flavor_read_html(\n BytesIO(fobj.read()), encoding=encoding, index_col=0\n ).pop()\n\n from_filename = flavor_read_html(\n html_encoding_file, encoding=encoding, index_col=0\n ).pop()\n tm.assert_frame_equal(from_string, from_file_like)\n tm.assert_frame_equal(from_string, from_filename)\n except Exception:\n # seems utf-16/32 fail on windows\n if is_platform_windows():\n if "16" in encoding or "32" in encoding:\n pytest.skip()\n raise\n\n def test_parse_failure_unseekable(self, flavor_read_html):\n # Issue #17975\n\n if flavor_read_html.keywords.get("flavor") == "lxml":\n pytest.skip("Not applicable for lxml")\n\n class UnseekableStringIO(StringIO):\n def seekable(self):\n return False\n\n bad = UnseekableStringIO(\n """\n <table><tr><td>spam<foobr />eggs</td></tr></table>"""\n )\n\n assert flavor_read_html(bad)\n\n with pytest.raises(ValueError, match="passed a non-rewindable file object"):\n flavor_read_html(bad)\n\n def test_parse_failure_rewinds(self, flavor_read_html):\n # Issue #17975\n\n class MockFile:\n def __init__(self, data) -> None:\n self.data = data\n self.at_end = False\n\n def read(self, size=None):\n data = "" if self.at_end else self.data\n self.at_end = True\n return data\n\n def seek(self, offset):\n self.at_end = False\n\n def seekable(self):\n return True\n\n # GH 49036 pylint checks for presence of __next__ for iterators\n def __next__(self):\n ...\n\n def __iter__(self) -> Iterator:\n # `is_file_like` depends on the presence of\n # the __iter__ attribute.\n return self\n\n good = MockFile("<table><tr><td>spam<br />eggs</td></tr></table>")\n bad = MockFile("<table><tr><td>spam<foobr />eggs</td></tr></table>")\n\n assert flavor_read_html(good)\n assert flavor_read_html(bad)\n\n @pytest.mark.slow\n @pytest.mark.single_cpu\n def test_importcheck_thread_safety(self, datapath, flavor_read_html):\n # see gh-16928\n\n class ErrorThread(threading.Thread):\n def run(self):\n try:\n super().run()\n except Exception as err:\n self.err = err\n else:\n self.err = None\n\n filename = datapath("io", "data", "html", "valid_markup.html")\n helper_thread1 = ErrorThread(target=flavor_read_html, args=(filename,))\n helper_thread2 = ErrorThread(target=flavor_read_html, args=(filename,))\n\n helper_thread1.start()\n helper_thread2.start()\n\n while helper_thread1.is_alive() or helper_thread2.is_alive():\n pass\n assert None is helper_thread1.err is helper_thread2.err\n\n def test_parse_path_object(self, datapath, flavor_read_html):\n # GH 37705\n file_path_string = datapath("io", "data", "html", "spam.html")\n file_path = Path(file_path_string)\n df1 = flavor_read_html(file_path_string)[0]\n df2 = flavor_read_html(file_path)[0]\n tm.assert_frame_equal(df1, df2)\n\n def test_parse_br_as_space(self, flavor_read_html):\n # GH 29528: pd.read_html() convert <br> to space\n result = flavor_read_html(\n StringIO(\n """\n <table>\n <tr>\n <th>A</th>\n </tr>\n <tr>\n <td>word1<br>word2</td>\n </tr>\n </table>\n """\n )\n )[0]\n\n expected = DataFrame(data=[["word1 word2"]], columns=["A"])\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("arg", ["all", "body", "header", "footer"])\n def test_extract_links(self, arg, flavor_read_html):\n gh_13141_data = """\n <table>\n <tr>\n <th>HTTP</th>\n <th>FTP</th>\n <th><a href="https://en.wiktionary.org/wiki/linkless">Linkless</a></th>\n </tr>\n <tr>\n <td><a href="https://en.wikipedia.org/">Wikipedia</a></td>\n <td>SURROUNDING <a href="ftp://ftp.us.debian.org/">Debian</a> TEXT</td>\n <td>Linkless</td>\n </tr>\n <tfoot>\n <tr>\n <td><a href="https://en.wikipedia.org/wiki/Page_footer">Footer</a></td>\n <td>\n Multiple <a href="1">links:</a> <a href="2">Only first captured.</a>\n </td>\n </tr>\n </tfoot>\n </table>\n """\n\n gh_13141_expected = {\n "head_ignore": ["HTTP", "FTP", "Linkless"],\n "head_extract": [\n ("HTTP", None),\n ("FTP", None),\n ("Linkless", "https://en.wiktionary.org/wiki/linkless"),\n ],\n "body_ignore": ["Wikipedia", "SURROUNDING Debian TEXT", "Linkless"],\n "body_extract": [\n ("Wikipedia", "https://en.wikipedia.org/"),\n ("SURROUNDING Debian TEXT", "ftp://ftp.us.debian.org/"),\n ("Linkless", None),\n ],\n "footer_ignore": [\n "Footer",\n "Multiple links: Only first captured.",\n None,\n ],\n "footer_extract": [\n ("Footer", "https://en.wikipedia.org/wiki/Page_footer"),\n ("Multiple links: Only first captured.", "1"),\n None,\n ],\n }\n\n data_exp = gh_13141_expected["body_ignore"]\n foot_exp = gh_13141_expected["footer_ignore"]\n head_exp = gh_13141_expected["head_ignore"]\n if arg == "all":\n data_exp = gh_13141_expected["body_extract"]\n foot_exp = gh_13141_expected["footer_extract"]\n head_exp = gh_13141_expected["head_extract"]\n elif arg == "body":\n data_exp = gh_13141_expected["body_extract"]\n elif arg == "footer":\n foot_exp = gh_13141_expected["footer_extract"]\n elif arg == "header":\n head_exp = gh_13141_expected["head_extract"]\n\n result = flavor_read_html(StringIO(gh_13141_data), extract_links=arg)[0]\n expected = DataFrame([data_exp, foot_exp], columns=head_exp)\n expected = expected.fillna(np.nan)\n tm.assert_frame_equal(result, expected)\n\n def test_extract_links_bad(self, spam_data):\n msg = (\n "`extract_links` must be one of "\n '{None, "header", "footer", "body", "all"}, got "incorrect"'\n )\n with pytest.raises(ValueError, match=msg):\n read_html(spam_data, extract_links="incorrect")\n\n def test_extract_links_all_no_header(self, flavor_read_html):\n # GH 48316\n data = """\n <table>\n <tr>\n <td>\n <a href='https://google.com'>Google.com</a>\n </td>\n </tr>\n </table>\n """\n result = flavor_read_html(StringIO(data), extract_links="all")[0]\n expected = DataFrame([[("Google.com", "https://google.com")]])\n tm.assert_frame_equal(result, expected)\n\n def test_invalid_dtype_backend(self):\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 read_html("test", dtype_backend="numpy")\n\n def test_style_tag(self, flavor_read_html):\n # GH 48316\n data = """\n <table>\n <tr>\n <th>\n <style>.style</style>\n A\n </th>\n <th>B</th>\n </tr>\n <tr>\n <td>A1</td>\n <td>B1</td>\n </tr>\n <tr>\n <td>A2</td>\n <td>B2</td>\n </tr>\n </table>\n """\n result = flavor_read_html(StringIO(data))[0]\n expected = DataFrame(data=[["A1", "B1"], ["A2", "B2"]], columns=["A", "B"])\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\io\test_html.py
test_html.py
Python
56,525
0.75
0.117718
0.032798
python-kit
931
2025-05-16T15:43:13.436167
GPL-3.0
true
1f6224c76fe2acf2c0b96babff7bc4eb
"""\nTests for the pandas custom headers in http(s) requests\n"""\nfrom functools import partial\nimport gzip\nfrom io import BytesIO\n\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nimport pandas._testing as tm\n\npytestmark = [\n pytest.mark.single_cpu,\n pytest.mark.network,\n pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n ),\n]\n\n\ndef gzip_bytes(response_bytes):\n with BytesIO() as bio:\n with gzip.GzipFile(fileobj=bio, mode="w") as zipper:\n zipper.write(response_bytes)\n return bio.getvalue()\n\n\ndef csv_responder(df):\n return df.to_csv(index=False).encode("utf-8")\n\n\ndef gz_csv_responder(df):\n return gzip_bytes(csv_responder(df))\n\n\ndef json_responder(df):\n return df.to_json().encode("utf-8")\n\n\ndef gz_json_responder(df):\n return gzip_bytes(json_responder(df))\n\n\ndef html_responder(df):\n return df.to_html(index=False).encode("utf-8")\n\n\ndef parquetpyarrow_reponder(df):\n return df.to_parquet(index=False, engine="pyarrow")\n\n\ndef parquetfastparquet_responder(df):\n # the fastparquet engine doesn't like to write to a buffer\n # it can do it via the open_with function being set appropriately\n # however it automatically calls the close method and wipes the buffer\n # so just overwrite that attribute on this instance to not do that\n\n # protected by an importorskip in the respective test\n import fsspec\n\n df.to_parquet(\n "memory://fastparquet_user_agent.parquet",\n index=False,\n engine="fastparquet",\n compression=None,\n )\n with fsspec.open("memory://fastparquet_user_agent.parquet", "rb") as f:\n return f.read()\n\n\ndef pickle_respnder(df):\n with BytesIO() as bio:\n df.to_pickle(bio)\n return bio.getvalue()\n\n\ndef stata_responder(df):\n with BytesIO() as bio:\n df.to_stata(bio, write_index=False)\n return bio.getvalue()\n\n\n@pytest.mark.parametrize(\n "responder, read_method",\n [\n (csv_responder, pd.read_csv),\n (json_responder, pd.read_json),\n (\n html_responder,\n lambda *args, **kwargs: pd.read_html(*args, **kwargs)[0],\n ),\n pytest.param(\n parquetpyarrow_reponder,\n partial(pd.read_parquet, engine="pyarrow"),\n marks=td.skip_if_no("pyarrow"),\n ),\n pytest.param(\n parquetfastparquet_responder,\n partial(pd.read_parquet, engine="fastparquet"),\n # TODO(ArrayManager) fastparquet\n marks=[\n td.skip_if_no("fastparquet"),\n td.skip_if_no("fsspec"),\n td.skip_array_manager_not_yet_implemented,\n pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string"),\n ],\n ),\n (pickle_respnder, pd.read_pickle),\n (stata_responder, pd.read_stata),\n (gz_csv_responder, pd.read_csv),\n (gz_json_responder, pd.read_json),\n ],\n)\n@pytest.mark.parametrize(\n "storage_options",\n [\n None,\n {"User-Agent": "foo"},\n {"User-Agent": "foo", "Auth": "bar"},\n ],\n)\ndef test_request_headers(responder, read_method, httpserver, storage_options):\n expected = pd.DataFrame({"a": ["b"]})\n default_headers = ["Accept-Encoding", "Host", "Connection", "User-Agent"]\n if "gz" in responder.__name__:\n extra = {"Content-Encoding": "gzip"}\n if storage_options is None:\n storage_options = extra\n else:\n storage_options |= extra\n else:\n extra = None\n expected_headers = set(default_headers).union(\n storage_options.keys() if storage_options else []\n )\n httpserver.serve_content(content=responder(expected), headers=extra)\n result = read_method(httpserver.url, storage_options=storage_options)\n tm.assert_frame_equal(result, expected)\n\n request_headers = dict(httpserver.requests[0].headers)\n for header in expected_headers:\n exp = request_headers.pop(header)\n if storage_options and header in storage_options:\n assert exp == storage_options[header]\n # No extra headers added\n assert not request_headers\n\n\n@pytest.mark.parametrize(\n "engine",\n [\n "pyarrow",\n "fastparquet",\n ],\n)\ndef test_to_parquet_to_disk_with_storage_options(engine):\n headers = {\n "User-Agent": "custom",\n "Auth": "other_custom",\n }\n\n pytest.importorskip(engine)\n\n true_df = pd.DataFrame({"column_name": ["column_value"]})\n msg = (\n "storage_options passed with file object or non-fsspec file path|"\n "storage_options passed with buffer, or non-supported URL"\n )\n with pytest.raises(ValueError, match=msg):\n true_df.to_parquet("/tmp/junk.parquet", storage_options=headers, engine=engine)\n
.venv\Lib\site-packages\pandas\tests\io\test_http_headers.py
test_http_headers.py
Python
4,885
0.95
0.108571
0.049645
python-kit
778
2025-04-19T02:58:52.468393
Apache-2.0
true
fec42dfcedd90a32051ea275cefe9ef4
""" test orc compat """\nimport datetime\nfrom decimal import Decimal\nfrom io import BytesIO\nimport os\nimport pathlib\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import read_orc\nimport pandas._testing as tm\nfrom pandas.core.arrays import StringArray\n\npytest.importorskip("pyarrow.orc")\n\nimport pyarrow as pa\n\npytestmark = pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n)\n\n\n@pytest.fixture\ndef dirpath(datapath):\n return datapath("io", "data", "orc")\n\n\n@pytest.fixture(\n params=[\n np.array([1, 20], dtype="uint64"),\n pd.Series(["a", "b", "a"], dtype="category"),\n [pd.Interval(left=0, right=2), pd.Interval(left=0, right=5)],\n [pd.Period("2022-01-03", freq="D"), pd.Period("2022-01-04", freq="D")],\n ]\n)\ndef orc_writer_dtypes_not_supported(request):\n # Examples of dataframes with dtypes for which conversion to ORC\n # hasn't been implemented yet, that is, Category, unsigned integers,\n # interval, period and sparse.\n return pd.DataFrame({"unimpl": request.param})\n\n\ndef test_orc_reader_empty(dirpath, using_infer_string):\n columns = [\n "boolean1",\n "byte1",\n "short1",\n "int1",\n "long1",\n "float1",\n "double1",\n "bytes1",\n "string1",\n ]\n dtypes = [\n "bool",\n "int8",\n "int16",\n "int32",\n "int64",\n "float32",\n "float64",\n "object",\n "str" if using_infer_string else "object",\n ]\n expected = pd.DataFrame(index=pd.RangeIndex(0))\n for colname, dtype in zip(columns, dtypes):\n expected[colname] = pd.Series(dtype=dtype)\n expected.columns = expected.columns.astype("str")\n\n inputfile = os.path.join(dirpath, "TestOrcFile.emptyFile.orc")\n got = read_orc(inputfile, columns=columns)\n\n tm.assert_equal(expected, got)\n\n\ndef test_orc_reader_basic(dirpath):\n data = {\n "boolean1": np.array([False, True], dtype="bool"),\n "byte1": np.array([1, 100], dtype="int8"),\n "short1": np.array([1024, 2048], dtype="int16"),\n "int1": np.array([65536, 65536], dtype="int32"),\n "long1": np.array([9223372036854775807, 9223372036854775807], dtype="int64"),\n "float1": np.array([1.0, 2.0], dtype="float32"),\n "double1": np.array([-15.0, -5.0], dtype="float64"),\n "bytes1": np.array([b"\x00\x01\x02\x03\x04", b""], dtype="object"),\n "string1": np.array(["hi", "bye"], dtype="object"),\n }\n expected = pd.DataFrame.from_dict(data)\n\n inputfile = os.path.join(dirpath, "TestOrcFile.test1.orc")\n got = read_orc(inputfile, columns=data.keys())\n\n tm.assert_equal(expected, got)\n\n\ndef test_orc_reader_decimal(dirpath):\n # Only testing the first 10 rows of data\n data = {\n "_col0": np.array(\n [\n Decimal("-1000.50000"),\n Decimal("-999.60000"),\n Decimal("-998.70000"),\n Decimal("-997.80000"),\n Decimal("-996.90000"),\n Decimal("-995.10000"),\n Decimal("-994.11000"),\n Decimal("-993.12000"),\n Decimal("-992.13000"),\n Decimal("-991.14000"),\n ],\n dtype="object",\n )\n }\n expected = pd.DataFrame.from_dict(data)\n\n inputfile = os.path.join(dirpath, "TestOrcFile.decimal.orc")\n got = read_orc(inputfile).iloc[:10]\n\n tm.assert_equal(expected, got)\n\n\ndef test_orc_reader_date_low(dirpath):\n data = {\n "time": np.array(\n [\n "1900-05-05 12:34:56.100000",\n "1900-05-05 12:34:56.100100",\n "1900-05-05 12:34:56.100200",\n "1900-05-05 12:34:56.100300",\n "1900-05-05 12:34:56.100400",\n "1900-05-05 12:34:56.100500",\n "1900-05-05 12:34:56.100600",\n "1900-05-05 12:34:56.100700",\n "1900-05-05 12:34:56.100800",\n "1900-05-05 12:34:56.100900",\n ],\n dtype="datetime64[ns]",\n ),\n "date": np.array(\n [\n datetime.date(1900, 12, 25),\n datetime.date(1900, 12, 25),\n datetime.date(1900, 12, 25),\n datetime.date(1900, 12, 25),\n datetime.date(1900, 12, 25),\n datetime.date(1900, 12, 25),\n datetime.date(1900, 12, 25),\n datetime.date(1900, 12, 25),\n datetime.date(1900, 12, 25),\n datetime.date(1900, 12, 25),\n ],\n dtype="object",\n ),\n }\n expected = pd.DataFrame.from_dict(data)\n\n inputfile = os.path.join(dirpath, "TestOrcFile.testDate1900.orc")\n got = read_orc(inputfile).iloc[:10]\n\n tm.assert_equal(expected, got)\n\n\ndef test_orc_reader_date_high(dirpath):\n data = {\n "time": np.array(\n [\n "2038-05-05 12:34:56.100000",\n "2038-05-05 12:34:56.100100",\n "2038-05-05 12:34:56.100200",\n "2038-05-05 12:34:56.100300",\n "2038-05-05 12:34:56.100400",\n "2038-05-05 12:34:56.100500",\n "2038-05-05 12:34:56.100600",\n "2038-05-05 12:34:56.100700",\n "2038-05-05 12:34:56.100800",\n "2038-05-05 12:34:56.100900",\n ],\n dtype="datetime64[ns]",\n ),\n "date": np.array(\n [\n datetime.date(2038, 12, 25),\n datetime.date(2038, 12, 25),\n datetime.date(2038, 12, 25),\n datetime.date(2038, 12, 25),\n datetime.date(2038, 12, 25),\n datetime.date(2038, 12, 25),\n datetime.date(2038, 12, 25),\n datetime.date(2038, 12, 25),\n datetime.date(2038, 12, 25),\n datetime.date(2038, 12, 25),\n ],\n dtype="object",\n ),\n }\n expected = pd.DataFrame.from_dict(data)\n\n inputfile = os.path.join(dirpath, "TestOrcFile.testDate2038.orc")\n got = read_orc(inputfile).iloc[:10]\n\n tm.assert_equal(expected, got)\n\n\ndef test_orc_reader_snappy_compressed(dirpath):\n data = {\n "int1": np.array(\n [\n -1160101563,\n 1181413113,\n 2065821249,\n -267157795,\n 172111193,\n 1752363137,\n 1406072123,\n 1911809390,\n -1308542224,\n -467100286,\n ],\n dtype="int32",\n ),\n "string1": np.array(\n [\n "f50dcb8",\n "382fdaaa",\n "90758c6",\n "9e8caf3f",\n "ee97332b",\n "d634da1",\n "2bea4396",\n "d67d89e8",\n "ad71007e",\n "e8c82066",\n ],\n dtype="object",\n ),\n }\n expected = pd.DataFrame.from_dict(data)\n\n inputfile = os.path.join(dirpath, "TestOrcFile.testSnappy.orc")\n got = read_orc(inputfile).iloc[:10]\n\n tm.assert_equal(expected, got)\n\n\ndef test_orc_roundtrip_file(dirpath):\n # GH44554\n # PyArrow gained ORC write support with the current argument order\n pytest.importorskip("pyarrow")\n\n data = {\n "boolean1": np.array([False, True], dtype="bool"),\n "byte1": np.array([1, 100], dtype="int8"),\n "short1": np.array([1024, 2048], dtype="int16"),\n "int1": np.array([65536, 65536], dtype="int32"),\n "long1": np.array([9223372036854775807, 9223372036854775807], dtype="int64"),\n "float1": np.array([1.0, 2.0], dtype="float32"),\n "double1": np.array([-15.0, -5.0], dtype="float64"),\n "bytes1": np.array([b"\x00\x01\x02\x03\x04", b""], dtype="object"),\n "string1": np.array(["hi", "bye"], dtype="object"),\n }\n expected = pd.DataFrame.from_dict(data)\n\n with tm.ensure_clean() as path:\n expected.to_orc(path)\n got = read_orc(path)\n\n tm.assert_equal(expected, got)\n\n\ndef test_orc_roundtrip_bytesio():\n # GH44554\n # PyArrow gained ORC write support with the current argument order\n pytest.importorskip("pyarrow")\n\n data = {\n "boolean1": np.array([False, True], dtype="bool"),\n "byte1": np.array([1, 100], dtype="int8"),\n "short1": np.array([1024, 2048], dtype="int16"),\n "int1": np.array([65536, 65536], dtype="int32"),\n "long1": np.array([9223372036854775807, 9223372036854775807], dtype="int64"),\n "float1": np.array([1.0, 2.0], dtype="float32"),\n "double1": np.array([-15.0, -5.0], dtype="float64"),\n "bytes1": np.array([b"\x00\x01\x02\x03\x04", b""], dtype="object"),\n "string1": np.array(["hi", "bye"], dtype="object"),\n }\n expected = pd.DataFrame.from_dict(data)\n\n bytes = expected.to_orc()\n got = read_orc(BytesIO(bytes))\n\n tm.assert_equal(expected, got)\n\n\ndef test_orc_writer_dtypes_not_supported(orc_writer_dtypes_not_supported):\n # GH44554\n # PyArrow gained ORC write support with the current argument order\n pytest.importorskip("pyarrow")\n\n msg = "The dtype of one or more columns is not supported yet."\n with pytest.raises(NotImplementedError, match=msg):\n orc_writer_dtypes_not_supported.to_orc()\n\n\ndef test_orc_dtype_backend_pyarrow(using_infer_string):\n pytest.importorskip("pyarrow")\n df = pd.DataFrame(\n {\n "string": list("abc"),\n "string_with_nan": ["a", np.nan, "c"],\n "string_with_none": ["a", None, "c"],\n "bytes": [b"foo", b"bar", None],\n "int": list(range(1, 4)),\n "float": np.arange(4.0, 7.0, dtype="float64"),\n "float_with_nan": [2.0, np.nan, 3.0],\n "bool": [True, False, True],\n "bool_with_na": [True, False, None],\n "datetime": pd.date_range("20130101", periods=3),\n "datetime_with_nat": [\n pd.Timestamp("20130101"),\n pd.NaT,\n pd.Timestamp("20130103"),\n ],\n }\n )\n\n bytes_data = df.copy().to_orc()\n result = read_orc(BytesIO(bytes_data), dtype_backend="pyarrow")\n\n expected = pd.DataFrame(\n {\n col: pd.arrays.ArrowExtensionArray(pa.array(df[col], from_pandas=True))\n for col in df.columns\n }\n )\n if using_infer_string:\n # ORC does not preserve distinction between string and large string\n # -> the default large string comes back as string\n string_dtype = pd.ArrowDtype(pa.string())\n expected["string"] = expected["string"].astype(string_dtype)\n expected["string_with_nan"] = expected["string_with_nan"].astype(string_dtype)\n expected["string_with_none"] = expected["string_with_none"].astype(string_dtype)\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_orc_dtype_backend_numpy_nullable():\n # GH#50503\n pytest.importorskip("pyarrow")\n df = pd.DataFrame(\n {\n "string": list("abc"),\n "string_with_nan": ["a", np.nan, "c"],\n "string_with_none": ["a", None, "c"],\n "int": list(range(1, 4)),\n "int_with_nan": pd.Series([1, pd.NA, 3], dtype="Int64"),\n "na_only": pd.Series([pd.NA, pd.NA, pd.NA], dtype="Int64"),\n "float": np.arange(4.0, 7.0, dtype="float64"),\n "float_with_nan": [2.0, np.nan, 3.0],\n "bool": [True, False, True],\n "bool_with_na": [True, False, None],\n }\n )\n\n bytes_data = df.copy().to_orc()\n result = read_orc(BytesIO(bytes_data), dtype_backend="numpy_nullable")\n\n expected = pd.DataFrame(\n {\n "string": StringArray(np.array(["a", "b", "c"], dtype=np.object_)),\n "string_with_nan": StringArray(\n np.array(["a", pd.NA, "c"], dtype=np.object_)\n ),\n "string_with_none": StringArray(\n np.array(["a", pd.NA, "c"], dtype=np.object_)\n ),\n "int": pd.Series([1, 2, 3], dtype="Int64"),\n "int_with_nan": pd.Series([1, pd.NA, 3], dtype="Int64"),\n "na_only": pd.Series([pd.NA, pd.NA, pd.NA], dtype="Int64"),\n "float": pd.Series([4.0, 5.0, 6.0], dtype="Float64"),\n "float_with_nan": pd.Series([2.0, pd.NA, 3.0], dtype="Float64"),\n "bool": pd.Series([True, False, True], dtype="boolean"),\n "bool_with_na": pd.Series([True, False, pd.NA], dtype="boolean"),\n }\n )\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_orc_uri_path():\n expected = pd.DataFrame({"int": list(range(1, 4))})\n with tm.ensure_clean("tmp.orc") as path:\n expected.to_orc(path)\n uri = pathlib.Path(path).as_uri()\n result = read_orc(uri)\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "index",\n [\n pd.RangeIndex(start=2, stop=5, step=1),\n pd.RangeIndex(start=0, stop=3, step=1, name="non-default"),\n pd.Index([1, 2, 3]),\n ],\n)\ndef test_to_orc_non_default_index(index):\n df = pd.DataFrame({"a": [1, 2, 3]}, index=index)\n msg = (\n "orc does not support serializing a non-default index|"\n "orc does not serialize index meta-data"\n )\n with pytest.raises(ValueError, match=msg):\n df.to_orc()\n\n\ndef test_invalid_dtype_backend():\n msg = (\n "dtype_backend numpy is invalid, only 'numpy_nullable' and "\n "'pyarrow' are allowed."\n )\n df = pd.DataFrame({"int": list(range(1, 4))})\n with tm.ensure_clean("tmp.orc") as path:\n df.to_orc(path)\n with pytest.raises(ValueError, match=msg):\n read_orc(path, dtype_backend="numpy")\n\n\ndef test_string_inference(tmp_path):\n # GH#54431\n path = tmp_path / "test_string_inference.p"\n df = pd.DataFrame(data={"a": ["x", "y"]})\n df.to_orc(path)\n with pd.option_context("future.infer_string", True):\n result = read_orc(path)\n expected = pd.DataFrame(\n data={"a": ["x", "y"]},\n dtype=pd.StringDtype(na_value=np.nan),\n columns=pd.Index(["a"], dtype=pd.StringDtype(na_value=np.nan)),\n )\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\io\test_orc.py
test_orc.py
Python
14,261
0.95
0.04955
0.036842
vue-tools
398
2024-03-10T15:11:29.549595
MIT
true
117588126c3a17c0736980e838fd13fb
""" test parquet compat """\nimport datetime\nfrom decimal import Decimal\nfrom io import BytesIO\nimport os\nimport pathlib\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import (\n using_copy_on_write,\n using_string_dtype,\n)\nfrom pandas._config.config import _get_option\n\nfrom pandas.compat import is_platform_windows\nfrom pandas.compat.pyarrow import (\n pa_version_under11p0,\n pa_version_under13p0,\n pa_version_under15p0,\n pa_version_under19p0,\n pa_version_under20p0,\n)\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.util.version import Version\n\nfrom pandas.io.parquet import (\n FastParquetImpl,\n PyArrowImpl,\n get_engine,\n read_parquet,\n to_parquet,\n)\n\ntry:\n import pyarrow\n\n _HAVE_PYARROW = True\nexcept ImportError:\n _HAVE_PYARROW = False\n\ntry:\n import fastparquet\n\n _HAVE_FASTPARQUET = True\nexcept ImportError:\n _HAVE_FASTPARQUET = False\n\n\n# TODO(ArrayManager) fastparquet relies on BlockManager internals\n\npytestmark = [\n pytest.mark.filterwarnings("ignore:DataFrame._data is deprecated:FutureWarning"),\n pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n ),\n]\n\n\n# setup engines & skips\n@pytest.fixture(\n params=[\n pytest.param(\n "fastparquet",\n marks=[\n pytest.mark.skipif(\n not _HAVE_FASTPARQUET\n or _get_option("mode.data_manager", silent=True) == "array",\n reason="fastparquet is not installed or ArrayManager is used",\n ),\n pytest.mark.xfail(\n using_string_dtype(),\n reason="TODO(infer_string) fastparquet",\n strict=False,\n ),\n ],\n ),\n pytest.param(\n "pyarrow",\n marks=pytest.mark.skipif(\n not _HAVE_PYARROW, reason="pyarrow is not installed"\n ),\n ),\n ]\n)\ndef engine(request):\n return request.param\n\n\n@pytest.fixture\ndef pa():\n if not _HAVE_PYARROW:\n pytest.skip("pyarrow is not installed")\n return "pyarrow"\n\n\n@pytest.fixture\ndef fp(request):\n if not _HAVE_FASTPARQUET:\n pytest.skip("fastparquet is not installed")\n elif _get_option("mode.data_manager", silent=True) == "array":\n pytest.skip("ArrayManager is not supported with fastparquet")\n if using_string_dtype():\n request.applymarker(\n pytest.mark.xfail(reason="TODO(infer_string) fastparquet", strict=False)\n )\n return "fastparquet"\n\n\n@pytest.fixture\ndef df_compat():\n return pd.DataFrame({"A": [1, 2, 3], "B": "foo"}, columns=pd.Index(["A", "B"]))\n\n\n@pytest.fixture\ndef df_cross_compat():\n df = pd.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("20130101", periods=3),\n # 'g': pd.date_range('20130101', periods=3,\n # tz='US/Eastern'),\n # 'h': pd.date_range('20130101', periods=3, freq='ns')\n }\n )\n return df\n\n\n@pytest.fixture\ndef df_full():\n return pd.DataFrame(\n {\n "string": list("abc"),\n "string_with_nan": ["a", np.nan, "c"],\n "string_with_none": ["a", None, "c"],\n "bytes": [b"foo", b"bar", b"baz"],\n "unicode": ["foo", "bar", "baz"],\n "int": list(range(1, 4)),\n "uint": np.arange(3, 6).astype("u1"),\n "float": np.arange(4.0, 7.0, dtype="float64"),\n "float_with_nan": [2.0, np.nan, 3.0],\n "bool": [True, False, True],\n "datetime": pd.date_range("20130101", periods=3),\n "datetime_with_nat": [\n pd.Timestamp("20130101"),\n pd.NaT,\n pd.Timestamp("20130103"),\n ],\n }\n )\n\n\n@pytest.fixture(\n params=[\n datetime.datetime.now(datetime.timezone.utc),\n datetime.datetime.now(datetime.timezone.min),\n datetime.datetime.now(datetime.timezone.max),\n datetime.datetime.strptime("2019-01-04T16:41:24+0200", "%Y-%m-%dT%H:%M:%S%z"),\n datetime.datetime.strptime("2019-01-04T16:41:24+0215", "%Y-%m-%dT%H:%M:%S%z"),\n datetime.datetime.strptime("2019-01-04T16:41:24-0200", "%Y-%m-%dT%H:%M:%S%z"),\n datetime.datetime.strptime("2019-01-04T16:41:24-0215", "%Y-%m-%dT%H:%M:%S%z"),\n ]\n)\ndef timezone_aware_date_list(request):\n return request.param\n\n\ndef check_round_trip(\n df,\n engine=None,\n path=None,\n write_kwargs=None,\n read_kwargs=None,\n expected=None,\n check_names=True,\n check_like=False,\n check_dtype=True,\n repeat=2,\n):\n """Verify parquet serializer and deserializer produce the same results.\n\n Performs a pandas to disk and disk to pandas round trip,\n then compares the 2 resulting DataFrames to verify equality.\n\n Parameters\n ----------\n df: Dataframe\n engine: str, optional\n 'pyarrow' or 'fastparquet'\n path: str, optional\n write_kwargs: dict of str:str, optional\n read_kwargs: dict of str:str, optional\n expected: DataFrame, optional\n Expected deserialization result, otherwise will be equal to `df`\n check_names: list of str, optional\n Closed set of column names to be compared\n check_like: bool, optional\n If True, ignore the order of index & columns.\n repeat: int, optional\n How many times to repeat the test\n """\n write_kwargs = write_kwargs or {"compression": None}\n read_kwargs = read_kwargs or {}\n\n if expected is None:\n expected = df\n\n if engine:\n write_kwargs["engine"] = engine\n read_kwargs["engine"] = engine\n\n def compare(repeat):\n for _ in range(repeat):\n df.to_parquet(path, **write_kwargs)\n actual = read_parquet(path, **read_kwargs)\n\n if "string_with_nan" in expected:\n expected.loc[1, "string_with_nan"] = None\n tm.assert_frame_equal(\n expected,\n actual,\n check_names=check_names,\n check_like=check_like,\n check_dtype=check_dtype,\n )\n\n if path is None:\n with tm.ensure_clean() as path:\n compare(repeat)\n else:\n compare(repeat)\n\n\ndef check_partition_names(path, expected):\n """Check partitions of a parquet file are as expected.\n\n Parameters\n ----------\n path: str\n Path of the dataset.\n expected: iterable of str\n Expected partition names.\n """\n import pyarrow.dataset as ds\n\n dataset = ds.dataset(path, partitioning="hive")\n assert dataset.partitioning.schema.names == expected\n\n\ndef test_invalid_engine(df_compat):\n msg = "engine must be one of 'pyarrow', 'fastparquet'"\n with pytest.raises(ValueError, match=msg):\n check_round_trip(df_compat, "foo", "bar")\n\n\ndef test_options_py(df_compat, pa, using_infer_string):\n # use the set option\n if using_infer_string and not pa_version_under19p0:\n df_compat.columns = df_compat.columns.astype("str")\n\n with pd.option_context("io.parquet.engine", "pyarrow"):\n check_round_trip(df_compat)\n\n\ndef test_options_fp(df_compat, fp):\n # use the set option\n\n with pd.option_context("io.parquet.engine", "fastparquet"):\n check_round_trip(df_compat)\n\n\ndef test_options_auto(df_compat, fp, pa):\n # use the set option\n\n with pd.option_context("io.parquet.engine", "auto"):\n check_round_trip(df_compat)\n\n\ndef test_options_get_engine(fp, pa):\n assert isinstance(get_engine("pyarrow"), PyArrowImpl)\n assert isinstance(get_engine("fastparquet"), FastParquetImpl)\n\n with pd.option_context("io.parquet.engine", "pyarrow"):\n assert isinstance(get_engine("auto"), PyArrowImpl)\n assert isinstance(get_engine("pyarrow"), PyArrowImpl)\n assert isinstance(get_engine("fastparquet"), FastParquetImpl)\n\n with pd.option_context("io.parquet.engine", "fastparquet"):\n assert isinstance(get_engine("auto"), FastParquetImpl)\n assert isinstance(get_engine("pyarrow"), PyArrowImpl)\n assert isinstance(get_engine("fastparquet"), FastParquetImpl)\n\n with pd.option_context("io.parquet.engine", "auto"):\n assert isinstance(get_engine("auto"), PyArrowImpl)\n assert isinstance(get_engine("pyarrow"), PyArrowImpl)\n assert isinstance(get_engine("fastparquet"), FastParquetImpl)\n\n\ndef test_get_engine_auto_error_message():\n # Expect different error messages from get_engine(engine="auto")\n # if engines aren't installed vs. are installed but bad version\n from pandas.compat._optional import VERSIONS\n\n # Do we have engines installed, but a bad version of them?\n pa_min_ver = VERSIONS.get("pyarrow")\n fp_min_ver = VERSIONS.get("fastparquet")\n have_pa_bad_version = (\n False\n if not _HAVE_PYARROW\n else Version(pyarrow.__version__) < Version(pa_min_ver)\n )\n have_fp_bad_version = (\n False\n if not _HAVE_FASTPARQUET\n else Version(fastparquet.__version__) < Version(fp_min_ver)\n )\n # Do we have usable engines installed?\n have_usable_pa = _HAVE_PYARROW and not have_pa_bad_version\n have_usable_fp = _HAVE_FASTPARQUET and not have_fp_bad_version\n\n if not have_usable_pa and not have_usable_fp:\n # No usable engines found.\n if have_pa_bad_version:\n match = f"Pandas requires version .{pa_min_ver}. or newer of .pyarrow."\n with pytest.raises(ImportError, match=match):\n get_engine("auto")\n else:\n match = "Missing optional dependency .pyarrow."\n with pytest.raises(ImportError, match=match):\n get_engine("auto")\n\n if have_fp_bad_version:\n match = f"Pandas requires version .{fp_min_ver}. or newer of .fastparquet."\n with pytest.raises(ImportError, match=match):\n get_engine("auto")\n else:\n match = "Missing optional dependency .fastparquet."\n with pytest.raises(ImportError, match=match):\n get_engine("auto")\n\n\ndef test_cross_engine_pa_fp(df_cross_compat, pa, fp):\n # cross-compat with differing reading/writing engines\n\n df = df_cross_compat\n with tm.ensure_clean() as path:\n df.to_parquet(path, engine=pa, compression=None)\n\n result = read_parquet(path, engine=fp)\n tm.assert_frame_equal(result, df)\n\n result = read_parquet(path, engine=fp, columns=["a", "d"])\n tm.assert_frame_equal(result, df[["a", "d"]])\n\n\ndef test_cross_engine_fp_pa(df_cross_compat, pa, fp):\n # cross-compat with differing reading/writing engines\n df = df_cross_compat\n with tm.ensure_clean() as path:\n df.to_parquet(path, engine=fp, compression=None)\n\n result = read_parquet(path, engine=pa)\n tm.assert_frame_equal(result, df)\n\n result = read_parquet(path, engine=pa, columns=["a", "d"])\n tm.assert_frame_equal(result, df[["a", "d"]])\n\n\ndef test_parquet_pos_args_deprecation(engine):\n # GH-54229\n df = pd.DataFrame({"a": [1, 2, 3]})\n msg = (\n r"Starting with pandas version 3.0 all arguments of to_parquet except for the "\n r"argument 'path' will be keyword-only."\n )\n with tm.ensure_clean() as path:\n with tm.assert_produces_warning(\n FutureWarning,\n match=msg,\n check_stacklevel=False,\n raise_on_extra_warnings=False,\n ):\n df.to_parquet(path, engine)\n\n\nclass Base:\n def check_error_on_write(self, df, engine, exc, err_msg):\n # check that we are raising the exception on writing\n with tm.ensure_clean() as path:\n with pytest.raises(exc, match=err_msg):\n to_parquet(df, path, engine, compression=None)\n\n def check_external_error_on_write(self, df, engine, exc):\n # check that an external library is raising the exception on writing\n with tm.ensure_clean() as path:\n with tm.external_error_raised(exc):\n to_parquet(df, path, engine, compression=None)\n\n\nclass TestBasic(Base):\n def test_error(self, engine):\n for obj in [\n pd.Series([1, 2, 3]),\n 1,\n "foo",\n pd.Timestamp("20130101"),\n np.array([1, 2, 3]),\n ]:\n msg = "to_parquet only supports IO with DataFrames"\n self.check_error_on_write(obj, engine, ValueError, msg)\n\n def test_columns_dtypes(self, engine):\n df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))})\n\n # unicode\n df.columns = ["foo", "bar"]\n check_round_trip(df, engine)\n\n @pytest.mark.parametrize("compression", [None, "gzip", "snappy", "brotli"])\n def test_compression(self, engine, compression):\n df = pd.DataFrame({"A": [1, 2, 3]})\n check_round_trip(df, engine, write_kwargs={"compression": compression})\n\n def test_read_columns(self, engine):\n # GH18154\n df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))})\n\n expected = pd.DataFrame({"string": list("abc")})\n check_round_trip(\n df, engine, expected=expected, read_kwargs={"columns": ["string"]}\n )\n\n def test_read_filters(self, engine, tmp_path):\n df = pd.DataFrame(\n {\n "int": list(range(4)),\n "part": list("aabb"),\n }\n )\n\n expected = pd.DataFrame({"int": [0, 1]})\n check_round_trip(\n df,\n engine,\n path=tmp_path,\n expected=expected,\n write_kwargs={"partition_cols": ["part"]},\n read_kwargs={"filters": [("part", "==", "a")], "columns": ["int"]},\n repeat=1,\n )\n\n def test_write_index(self, engine):\n check_names = engine != "fastparquet"\n\n df = pd.DataFrame({"A": [1, 2, 3]})\n check_round_trip(df, engine)\n\n indexes = [\n [2, 3, 4],\n pd.date_range("20130101", periods=3),\n list("abc"),\n [1, 3, 4],\n ]\n # non-default index\n for index in indexes:\n df.index = index\n if isinstance(index, pd.DatetimeIndex):\n df.index = df.index._with_freq(None) # freq doesn't round-trip\n check_round_trip(df, engine, check_names=check_names)\n\n # index with meta-data\n df.index = [0, 1, 2]\n df.index.name = "foo"\n check_round_trip(df, engine)\n\n def test_write_multiindex(self, pa):\n # Not supported in fastparquet as of 0.1.3 or older pyarrow version\n engine = pa\n\n df = pd.DataFrame({"A": [1, 2, 3]})\n index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1)])\n df.index = index\n check_round_trip(df, engine)\n\n def test_multiindex_with_columns(self, pa):\n engine = pa\n dates = pd.date_range("01-Jan-2018", "01-Dec-2018", freq="MS")\n df = pd.DataFrame(\n np.random.default_rng(2).standard_normal((2 * len(dates), 3)),\n columns=list("ABC"),\n )\n index1 = pd.MultiIndex.from_product(\n [["Level1", "Level2"], dates], names=["level", "date"]\n )\n index2 = index1.copy(names=None)\n for index in [index1, index2]:\n df.index = index\n\n check_round_trip(df, engine)\n check_round_trip(\n df, engine, read_kwargs={"columns": ["A", "B"]}, expected=df[["A", "B"]]\n )\n\n def test_write_ignoring_index(self, engine):\n # ENH 20768\n # Ensure index=False omits the index from the written Parquet file.\n df = pd.DataFrame({"a": [1, 2, 3], "b": ["q", "r", "s"]})\n\n write_kwargs = {"compression": None, "index": False}\n\n # Because we're dropping the index, we expect the loaded dataframe to\n # have the default integer index.\n expected = df.reset_index(drop=True)\n\n check_round_trip(df, engine, write_kwargs=write_kwargs, expected=expected)\n\n # Ignore custom index\n df = pd.DataFrame(\n {"a": [1, 2, 3], "b": ["q", "r", "s"]}, index=["zyx", "wvu", "tsr"]\n )\n\n check_round_trip(df, engine, write_kwargs=write_kwargs, expected=expected)\n\n # Ignore multi-indexes as well.\n arrays = [\n ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n df = pd.DataFrame(\n {"one": list(range(8)), "two": [-i for i in range(8)]}, index=arrays\n )\n\n expected = df.reset_index(drop=True)\n check_round_trip(df, engine, write_kwargs=write_kwargs, expected=expected)\n\n def test_write_column_multiindex(self, engine):\n # Not able to write column multi-indexes with non-string column names.\n mi_columns = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1)])\n df = pd.DataFrame(\n np.random.default_rng(2).standard_normal((4, 3)), columns=mi_columns\n )\n\n if engine == "fastparquet":\n self.check_error_on_write(\n df, engine, TypeError, "Column name must be a string"\n )\n elif engine == "pyarrow":\n check_round_trip(df, engine)\n\n def test_write_column_multiindex_nonstring(self, engine):\n # GH #34777\n\n # Not able to write column multi-indexes with non-string column names\n arrays = [\n ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],\n [1, 2, 1, 2, 1, 2, 1, 2],\n ]\n df = pd.DataFrame(\n np.random.default_rng(2).standard_normal((8, 8)), columns=arrays\n )\n df.columns.names = ["Level1", "Level2"]\n if engine == "fastparquet":\n self.check_error_on_write(df, engine, ValueError, "Column name")\n elif engine == "pyarrow":\n check_round_trip(df, engine)\n\n def test_write_column_multiindex_string(self, pa):\n # GH #34777\n # Not supported in fastparquet as of 0.1.3\n engine = pa\n\n # Write column multi-indexes with string column names\n arrays = [\n ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n df = pd.DataFrame(\n np.random.default_rng(2).standard_normal((8, 8)), columns=arrays\n )\n df.columns.names = ["ColLevel1", "ColLevel2"]\n\n check_round_trip(df, engine)\n\n def test_write_column_index_string(self, pa):\n # GH #34777\n # Not supported in fastparquet as of 0.1.3\n engine = pa\n\n # Write column indexes with string column names\n arrays = ["bar", "baz", "foo", "qux"]\n df = pd.DataFrame(\n np.random.default_rng(2).standard_normal((8, 4)), columns=arrays\n )\n df.columns.name = "StringCol"\n\n check_round_trip(df, engine)\n\n def test_write_column_index_nonstring(self, engine):\n # GH #34777\n\n # Write column indexes with string column names\n arrays = [1, 2, 3, 4]\n df = pd.DataFrame(\n np.random.default_rng(2).standard_normal((8, 4)), columns=arrays\n )\n df.columns.name = "NonStringCol"\n if engine == "fastparquet":\n self.check_error_on_write(\n df, engine, TypeError, "Column name must be a string"\n )\n else:\n check_round_trip(df, engine)\n\n def test_dtype_backend(self, engine, request):\n pq = pytest.importorskip("pyarrow.parquet")\n\n if engine == "fastparquet":\n # We are manually disabling fastparquet's\n # nullable dtype support pending discussion\n mark = pytest.mark.xfail(\n reason="Fastparquet nullable dtype support is disabled"\n )\n request.applymarker(mark)\n\n table = pyarrow.table(\n {\n "a": pyarrow.array([1, 2, 3, None], "int64"),\n "b": pyarrow.array([1, 2, 3, None], "uint8"),\n "c": pyarrow.array(["a", "b", "c", None]),\n "d": pyarrow.array([True, False, True, None]),\n # Test that nullable dtypes used even in absence of nulls\n "e": pyarrow.array([1, 2, 3, 4], "int64"),\n # GH 45694\n "f": pyarrow.array([1.0, 2.0, 3.0, None], "float32"),\n "g": pyarrow.array([1.0, 2.0, 3.0, None], "float64"),\n }\n )\n with tm.ensure_clean() as path:\n # write manually with pyarrow to write integers\n pq.write_table(table, path)\n result1 = read_parquet(path, engine=engine)\n result2 = read_parquet(path, engine=engine, dtype_backend="numpy_nullable")\n\n assert result1["a"].dtype == np.dtype("float64")\n expected = pd.DataFrame(\n {\n "a": pd.array([1, 2, 3, None], dtype="Int64"),\n "b": pd.array([1, 2, 3, None], dtype="UInt8"),\n "c": pd.array(["a", "b", "c", None], dtype="string"),\n "d": pd.array([True, False, True, None], dtype="boolean"),\n "e": pd.array([1, 2, 3, 4], dtype="Int64"),\n "f": pd.array([1.0, 2.0, 3.0, None], dtype="Float32"),\n "g": pd.array([1.0, 2.0, 3.0, None], dtype="Float64"),\n }\n )\n if engine == "fastparquet":\n # Fastparquet doesn't support string columns yet\n # Only int and boolean\n result2 = result2.drop("c", axis=1)\n expected = expected.drop("c", axis=1)\n tm.assert_frame_equal(result2, expected)\n\n @pytest.mark.parametrize(\n "dtype",\n [\n "Int64",\n "UInt8",\n "boolean",\n "object",\n "datetime64[ns, UTC]",\n "float",\n "period[D]",\n "Float64",\n "string",\n ],\n )\n def test_read_empty_array(self, pa, dtype):\n # GH #41241\n df = pd.DataFrame(\n {\n "value": pd.array([], dtype=dtype),\n }\n )\n # GH 45694\n expected = None\n if dtype == "float":\n expected = pd.DataFrame(\n {\n "value": pd.array([], dtype="Float64"),\n }\n )\n check_round_trip(\n df, pa, read_kwargs={"dtype_backend": "numpy_nullable"}, expected=expected\n )\n\n @pytest.mark.network\n @pytest.mark.single_cpu\n def test_parquet_read_from_url(self, httpserver, datapath, df_compat, engine):\n if engine != "auto":\n pytest.importorskip(engine)\n with open(datapath("io", "data", "parquet", "simple.parquet"), mode="rb") as f:\n httpserver.serve_content(content=f.read())\n df = read_parquet(httpserver.url, engine=engine)\n tm.assert_frame_equal(df, df_compat)\n\n\nclass TestParquetPyArrow(Base):\n def test_basic(self, pa, df_full):\n df = df_full\n\n # additional supported types for pyarrow\n dti = pd.date_range("20130101", periods=3, tz="Europe/Brussels")\n dti = dti._with_freq(None) # freq doesn't round-trip\n df["datetime_tz"] = dti\n df["bool_with_none"] = [True, None, True]\n\n check_round_trip(df, pa)\n\n def test_basic_subset_columns(self, pa, df_full):\n # GH18628\n\n df = df_full\n # additional supported types for pyarrow\n df["datetime_tz"] = pd.date_range("20130101", periods=3, tz="Europe/Brussels")\n\n check_round_trip(\n df,\n pa,\n expected=df[["string", "int"]],\n read_kwargs={"columns": ["string", "int"]},\n )\n\n def test_to_bytes_without_path_or_buf_provided(self, pa, df_full):\n # GH 37105\n buf_bytes = df_full.to_parquet(engine=pa)\n assert isinstance(buf_bytes, bytes)\n\n buf_stream = BytesIO(buf_bytes)\n res = read_parquet(buf_stream)\n\n expected = df_full.copy()\n expected.loc[1, "string_with_nan"] = None\n tm.assert_frame_equal(res, expected)\n\n def test_duplicate_columns(self, pa):\n # not currently able to handle duplicate columns\n df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy()\n self.check_error_on_write(df, pa, ValueError, "Duplicate column names found")\n\n def test_timedelta(self, pa):\n df = pd.DataFrame({"a": pd.timedelta_range("1 day", periods=3)})\n check_round_trip(df, pa)\n\n def test_unsupported(self, pa):\n # mixed python objects\n df = pd.DataFrame({"a": ["a", 1, 2.0]})\n # pyarrow 0.11 raises ArrowTypeError\n # older pyarrows raise ArrowInvalid\n self.check_external_error_on_write(df, pa, pyarrow.ArrowException)\n\n def test_unsupported_float16(self, pa):\n # #44847, #44914\n # Not able to write float 16 column using pyarrow.\n data = np.arange(2, 10, dtype=np.float16)\n df = pd.DataFrame(data=data, columns=["fp16"])\n if pa_version_under15p0:\n self.check_external_error_on_write(df, pa, pyarrow.ArrowException)\n else:\n check_round_trip(df, pa)\n\n @pytest.mark.xfail(\n is_platform_windows(),\n reason=(\n "PyArrow does not cleanup of partial files dumps when unsupported "\n "dtypes are passed to_parquet function in windows"\n ),\n )\n @pytest.mark.skipif(not pa_version_under15p0, reason="float16 works on 15")\n @pytest.mark.parametrize("path_type", [str, pathlib.Path])\n def test_unsupported_float16_cleanup(self, pa, path_type):\n # #44847, #44914\n # Not able to write float 16 column using pyarrow.\n # Tests cleanup by pyarrow in case of an error\n data = np.arange(2, 10, dtype=np.float16)\n df = pd.DataFrame(data=data, columns=["fp16"])\n\n with tm.ensure_clean() as path_str:\n path = path_type(path_str)\n with tm.external_error_raised(pyarrow.ArrowException):\n df.to_parquet(path=path, engine=pa)\n assert not os.path.isfile(path)\n\n def test_categorical(self, pa):\n # supported in >= 0.7.0\n df = pd.DataFrame(\n {\n "a": pd.Categorical(list("abcdef")),\n # test for null, out-of-order values, and unobserved category\n "b": pd.Categorical(\n ["bar", "foo", "foo", "bar", None, "bar"],\n dtype=pd.CategoricalDtype(["foo", "bar", "baz"]),\n ),\n # test for ordered flag\n "c": pd.Categorical(\n ["a", "b", "c", "a", "c", "b"],\n categories=["b", "c", "d"],\n ordered=True,\n ),\n }\n )\n\n check_round_trip(df, pa)\n\n @pytest.mark.single_cpu\n def test_s3_roundtrip_explicit_fs(self, df_compat, s3_public_bucket, pa, s3so):\n s3fs = pytest.importorskip("s3fs")\n s3 = s3fs.S3FileSystem(**s3so)\n kw = {"filesystem": s3}\n check_round_trip(\n df_compat,\n pa,\n path=f"{s3_public_bucket.name}/pyarrow.parquet",\n read_kwargs=kw,\n write_kwargs=kw,\n )\n\n @pytest.mark.single_cpu\n def test_s3_roundtrip(self, df_compat, s3_public_bucket, pa, s3so):\n # GH #19134\n s3so = {"storage_options": s3so}\n check_round_trip(\n df_compat,\n pa,\n path=f"s3://{s3_public_bucket.name}/pyarrow.parquet",\n read_kwargs=s3so,\n write_kwargs=s3so,\n )\n\n @pytest.mark.single_cpu\n @pytest.mark.parametrize(\n "partition_col",\n [\n ["A"],\n [],\n ],\n )\n def test_s3_roundtrip_for_dir(\n self, df_compat, s3_public_bucket, pa, partition_col, s3so\n ):\n pytest.importorskip("s3fs")\n # GH #26388\n expected_df = df_compat.copy()\n\n # GH #35791\n if partition_col:\n expected_df = expected_df.astype(dict.fromkeys(partition_col, np.int32))\n partition_col_type = "category"\n\n expected_df[partition_col] = expected_df[partition_col].astype(\n partition_col_type\n )\n\n check_round_trip(\n df_compat,\n pa,\n expected=expected_df,\n path=f"s3://{s3_public_bucket.name}/parquet_dir",\n read_kwargs={"storage_options": s3so},\n write_kwargs={\n "partition_cols": partition_col,\n "compression": None,\n "storage_options": s3so,\n },\n check_like=True,\n repeat=1,\n )\n\n def test_read_file_like_obj_support(self, df_compat, using_infer_string):\n pytest.importorskip("pyarrow")\n buffer = BytesIO()\n df_compat.to_parquet(buffer)\n df_from_buf = read_parquet(buffer)\n if using_infer_string and not pa_version_under19p0:\n df_compat.columns = df_compat.columns.astype("str")\n tm.assert_frame_equal(df_compat, df_from_buf)\n\n def test_expand_user(self, df_compat, monkeypatch):\n pytest.importorskip("pyarrow")\n monkeypatch.setenv("HOME", "TestingUser")\n monkeypatch.setenv("USERPROFILE", "TestingUser")\n with pytest.raises(OSError, match=r".*TestingUser.*"):\n read_parquet("~/file.parquet")\n with pytest.raises(OSError, match=r".*TestingUser.*"):\n df_compat.to_parquet("~/file.parquet")\n\n def test_partition_cols_supported(self, tmp_path, pa, df_full):\n # GH #23283\n partition_cols = ["bool", "int"]\n df = df_full\n df.to_parquet(tmp_path, partition_cols=partition_cols, compression=None)\n check_partition_names(tmp_path, partition_cols)\n assert read_parquet(tmp_path).shape == df.shape\n\n def test_partition_cols_string(self, tmp_path, pa, df_full):\n # GH #27117\n partition_cols = "bool"\n partition_cols_list = [partition_cols]\n df = df_full\n df.to_parquet(tmp_path, partition_cols=partition_cols, compression=None)\n check_partition_names(tmp_path, partition_cols_list)\n assert read_parquet(tmp_path).shape == df.shape\n\n @pytest.mark.parametrize(\n "path_type", [str, lambda x: x], ids=["string", "pathlib.Path"]\n )\n def test_partition_cols_pathlib(self, tmp_path, pa, df_compat, path_type):\n # GH 35902\n\n partition_cols = "B"\n partition_cols_list = [partition_cols]\n df = df_compat\n\n path = path_type(tmp_path)\n df.to_parquet(path, partition_cols=partition_cols_list)\n assert read_parquet(path).shape == df.shape\n\n def test_empty_dataframe(self, pa):\n # GH #27339\n df = pd.DataFrame(index=[], columns=[])\n check_round_trip(df, pa)\n\n def test_write_with_schema(self, pa):\n import pyarrow\n\n df = pd.DataFrame({"x": [0, 1]})\n schema = pyarrow.schema([pyarrow.field("x", type=pyarrow.bool_())])\n out_df = df.astype(bool)\n check_round_trip(df, pa, write_kwargs={"schema": schema}, expected=out_df)\n\n def test_additional_extension_arrays(self, pa, using_infer_string):\n # test additional ExtensionArrays that are supported through the\n # __arrow_array__ protocol\n pytest.importorskip("pyarrow")\n df = pd.DataFrame(\n {\n "a": pd.Series([1, 2, 3], dtype="Int64"),\n "b": pd.Series([1, 2, 3], dtype="UInt32"),\n "c": pd.Series(["a", None, "c"], dtype="string"),\n }\n )\n if using_infer_string and pa_version_under19p0:\n check_round_trip(df, pa, expected=df.astype({"c": "str"}))\n else:\n check_round_trip(df, pa)\n\n df = pd.DataFrame({"a": pd.Series([1, 2, 3, None], dtype="Int64")})\n check_round_trip(df, pa)\n\n def test_pyarrow_backed_string_array(self, pa, string_storage, using_infer_string):\n # test ArrowStringArray supported through the __arrow_array__ protocol\n pytest.importorskip("pyarrow")\n df = pd.DataFrame({"a": pd.Series(["a", None, "c"], dtype="string[pyarrow]")})\n with pd.option_context("string_storage", string_storage):\n if using_infer_string:\n if pa_version_under19p0:\n expected = df.astype("str")\n else:\n expected = df.astype(f"string[{string_storage}]")\n expected.columns = expected.columns.astype("str")\n else:\n expected = df.astype(f"string[{string_storage}]")\n check_round_trip(df, pa, expected=expected)\n\n def test_additional_extension_types(self, pa):\n # test additional ExtensionArrays that are supported through the\n # __arrow_array__ protocol + by defining a custom ExtensionType\n pytest.importorskip("pyarrow")\n df = pd.DataFrame(\n {\n "c": pd.IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)]),\n "d": pd.period_range("2012-01-01", periods=3, freq="D"),\n # GH-45881 issue with interval with datetime64[ns] subtype\n "e": pd.IntervalIndex.from_breaks(\n pd.date_range("2012-01-01", periods=4, freq="D")\n ),\n }\n )\n check_round_trip(df, pa)\n\n def test_timestamp_nanoseconds(self, pa):\n # with version 2.6, pyarrow defaults to writing the nanoseconds, so\n # this should work without error\n # Note in previous pyarrows(<7.0.0), only the pseudo-version 2.0 was available\n ver = "2.6"\n df = pd.DataFrame({"a": pd.date_range("2017-01-01", freq="1ns", periods=10)})\n check_round_trip(df, pa, write_kwargs={"version": ver})\n\n def test_timezone_aware_index(self, pa, timezone_aware_date_list):\n pytest.importorskip("pyarrow", "11.0.0")\n\n idx = 5 * [timezone_aware_date_list]\n df = pd.DataFrame(index=idx, data={"index_as_col": idx})\n\n # see gh-36004\n # compare time(zone) values only, skip their class:\n # pyarrow always creates fixed offset timezones using pytz.FixedOffset()\n # even if it was datetime.timezone() originally\n #\n # technically they are the same:\n # they both implement datetime.tzinfo\n # they both wrap datetime.timedelta()\n # this use-case sets the resolution to 1 minute\n\n expected = df[:]\n if pa_version_under11p0:\n expected.index = expected.index.as_unit("ns")\n if timezone_aware_date_list.tzinfo != datetime.timezone.utc:\n # pyarrow returns pytz.FixedOffset while pandas constructs datetime.timezone\n # https://github.com/pandas-dev/pandas/issues/37286\n try:\n import pytz\n except ImportError:\n pass\n else:\n offset = df.index.tz.utcoffset(timezone_aware_date_list)\n tz = pytz.FixedOffset(offset.total_seconds() / 60)\n expected.index = expected.index.tz_convert(tz)\n expected["index_as_col"] = expected["index_as_col"].dt.tz_convert(tz)\n check_round_trip(df, pa, check_dtype=False, expected=expected)\n\n def test_filter_row_groups(self, pa):\n # https://github.com/pandas-dev/pandas/issues/26551\n pytest.importorskip("pyarrow")\n df = pd.DataFrame({"a": list(range(3))})\n with tm.ensure_clean() as path:\n df.to_parquet(path, engine=pa)\n result = read_parquet(path, pa, filters=[("a", "==", 0)])\n assert len(result) == 1\n\n def test_read_parquet_manager(self, pa, using_array_manager):\n # ensure that read_parquet honors the pandas.options.mode.data_manager option\n df = pd.DataFrame(\n np.random.default_rng(2).standard_normal((10, 3)), columns=["A", "B", "C"]\n )\n\n with tm.ensure_clean() as path:\n df.to_parquet(path, engine=pa)\n result = read_parquet(path, pa)\n if using_array_manager:\n assert isinstance(result._mgr, pd.core.internals.ArrayManager)\n else:\n assert isinstance(result._mgr, pd.core.internals.BlockManager)\n\n def test_read_dtype_backend_pyarrow_config(self, pa, df_full):\n import pyarrow\n\n df = df_full\n\n # additional supported types for pyarrow\n dti = pd.date_range("20130101", periods=3, tz="Europe/Brussels")\n dti = dti._with_freq(None) # freq doesn't round-trip\n df["datetime_tz"] = dti\n df["bool_with_none"] = [True, None, True]\n\n pa_table = pyarrow.Table.from_pandas(df)\n expected = pa_table.to_pandas(types_mapper=pd.ArrowDtype)\n if pa_version_under13p0:\n # pyarrow infers datetimes as us instead of ns\n expected["datetime"] = expected["datetime"].astype("timestamp[us][pyarrow]")\n expected["datetime_with_nat"] = expected["datetime_with_nat"].astype(\n "timestamp[us][pyarrow]"\n )\n expected["datetime_tz"] = expected["datetime_tz"].astype(\n pd.ArrowDtype(pyarrow.timestamp(unit="us", tz="Europe/Brussels"))\n )\n\n check_round_trip(\n df,\n engine=pa,\n read_kwargs={"dtype_backend": "pyarrow"},\n expected=expected,\n )\n\n def test_read_dtype_backend_pyarrow_config_index(self, pa):\n df = pd.DataFrame(\n {"a": [1, 2]}, index=pd.Index([3, 4], name="test"), dtype="int64[pyarrow]"\n )\n expected = df.copy()\n import pyarrow\n\n if Version(pyarrow.__version__) > Version("11.0.0"):\n expected.index = expected.index.astype("int64[pyarrow]")\n check_round_trip(\n df,\n engine=pa,\n read_kwargs={"dtype_backend": "pyarrow"},\n expected=expected,\n )\n\n @pytest.mark.parametrize(\n "columns",\n [\n [0, 1],\n pytest.param(\n [b"foo", b"bar"],\n marks=pytest.mark.xfail(\n pa_version_under20p0,\n raises=NotImplementedError,\n reason="https://github.com/apache/arrow/pull/44171",\n ),\n ),\n [\n datetime.datetime(2011, 1, 1, 0, 0),\n datetime.datetime(2011, 1, 1, 1, 1),\n ],\n ],\n )\n def test_columns_dtypes_not_invalid(self, pa, columns):\n df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))})\n\n df.columns = columns\n check_round_trip(df, pa)\n\n def test_empty_columns(self, pa):\n # GH 52034\n df = pd.DataFrame(index=pd.Index(["a", "b", "c"], name="custom name"))\n check_round_trip(df, pa)\n\n def test_df_attrs_persistence(self, tmp_path, pa):\n path = tmp_path / "test_df_metadata.p"\n df = pd.DataFrame(data={1: [1]})\n df.attrs = {"test_attribute": 1}\n df.to_parquet(path, engine=pa)\n new_df = read_parquet(path, engine=pa)\n assert new_df.attrs == df.attrs\n\n def test_string_inference(self, tmp_path, pa, using_infer_string):\n # GH#54431\n path = tmp_path / "test_string_inference.p"\n df = pd.DataFrame(data={"a": ["x", "y"]}, index=["a", "b"])\n df.to_parquet(path, engine=pa)\n with pd.option_context("future.infer_string", True):\n result = read_parquet(path, engine=pa)\n dtype = pd.StringDtype(na_value=np.nan)\n expected = pd.DataFrame(\n data={"a": ["x", "y"]},\n dtype=dtype,\n index=pd.Index(["a", "b"], dtype=dtype),\n columns=pd.Index(\n ["a"],\n dtype=object\n if pa_version_under19p0 and not using_infer_string\n else dtype,\n ),\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.skipif(pa_version_under11p0, reason="not supported before 11.0")\n def test_roundtrip_decimal(self, tmp_path, pa):\n # GH#54768\n import pyarrow as pa\n\n path = tmp_path / "decimal.p"\n df = pd.DataFrame({"a": [Decimal("123.00")]}, dtype="string[pyarrow]")\n df.to_parquet(path, schema=pa.schema([("a", pa.decimal128(5))]))\n result = read_parquet(path)\n if pa_version_under19p0:\n expected = pd.DataFrame({"a": ["123"]}, dtype="string[python]")\n else:\n expected = pd.DataFrame({"a": [Decimal("123.00")]}, dtype="object")\n tm.assert_frame_equal(result, expected)\n\n def test_infer_string_large_string_type(self, tmp_path, pa):\n # GH#54798\n import pyarrow as pa\n import pyarrow.parquet as pq\n\n path = tmp_path / "large_string.p"\n\n table = pa.table({"a": pa.array([None, "b", "c"], pa.large_string())})\n pq.write_table(table, path)\n\n with pd.option_context("future.infer_string", True):\n result = read_parquet(path)\n expected = pd.DataFrame(\n data={"a": [None, "b", "c"]},\n dtype=pd.StringDtype(na_value=np.nan),\n columns=pd.Index(["a"], dtype=pd.StringDtype(na_value=np.nan)),\n )\n tm.assert_frame_equal(result, expected)\n\n # NOTE: this test is not run by default, because it requires a lot of memory (>5GB)\n # @pytest.mark.slow\n # def test_string_column_above_2GB(self, tmp_path, pa):\n # # https://github.com/pandas-dev/pandas/issues/55606\n # # above 2GB of string data\n # v1 = b"x" * 100000000\n # v2 = b"x" * 147483646\n # df = pd.DataFrame({"strings": [v1] * 20 + [v2] + ["x"] * 20}, dtype="string")\n # df.to_parquet(tmp_path / "test.parquet")\n # result = read_parquet(tmp_path / "test.parquet")\n # assert result["strings"].dtype == "string"\n\n\nclass TestParquetFastParquet(Base):\n def test_basic(self, fp, df_full):\n df = df_full\n\n dti = pd.date_range("20130101", periods=3, tz="US/Eastern")\n dti = dti._with_freq(None) # freq doesn't round-trip\n df["datetime_tz"] = dti\n df["timedelta"] = pd.timedelta_range("1 day", periods=3)\n check_round_trip(df, fp)\n\n def test_columns_dtypes_invalid(self, fp):\n df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))})\n\n err = TypeError\n msg = "Column name must be a string"\n\n # numeric\n df.columns = [0, 1]\n self.check_error_on_write(df, fp, err, msg)\n\n # bytes\n df.columns = [b"foo", b"bar"]\n self.check_error_on_write(df, fp, err, msg)\n\n # python object\n df.columns = [\n datetime.datetime(2011, 1, 1, 0, 0),\n datetime.datetime(2011, 1, 1, 1, 1),\n ]\n self.check_error_on_write(df, fp, err, msg)\n\n def test_duplicate_columns(self, fp):\n # not currently able to handle duplicate columns\n df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy()\n msg = "Cannot create parquet dataset with duplicate column names"\n self.check_error_on_write(df, fp, ValueError, msg)\n\n def test_bool_with_none(self, fp, request):\n import fastparquet\n\n if Version(fastparquet.__version__) < Version("2024.11.0") and Version(\n np.__version__\n ) >= Version("2.0.0"):\n request.applymarker(\n pytest.mark.xfail(\n reason=("fastparquet uses np.float_ in numpy2"),\n )\n )\n df = pd.DataFrame({"a": [True, None, False]})\n expected = pd.DataFrame({"a": [1.0, np.nan, 0.0]}, dtype="float16")\n # Fastparquet bug in 0.7.1 makes it so that this dtype becomes\n # float64\n check_round_trip(df, fp, expected=expected, check_dtype=False)\n\n def test_unsupported(self, fp):\n # period\n df = pd.DataFrame({"a": pd.period_range("2013", freq="M", periods=3)})\n # error from fastparquet -> don't check exact error message\n self.check_error_on_write(df, fp, ValueError, None)\n\n # mixed\n df = pd.DataFrame({"a": ["a", 1, 2.0]})\n msg = "Can't infer object conversion type"\n self.check_error_on_write(df, fp, ValueError, msg)\n\n def test_categorical(self, fp):\n df = pd.DataFrame({"a": pd.Categorical(list("abc"))})\n check_round_trip(df, fp)\n\n def test_filter_row_groups(self, fp):\n d = {"a": list(range(3))}\n df = pd.DataFrame(d)\n with tm.ensure_clean() as path:\n df.to_parquet(path, engine=fp, compression=None, row_group_offsets=1)\n result = read_parquet(path, fp, filters=[("a", "==", 0)])\n assert len(result) == 1\n\n @pytest.mark.single_cpu\n def test_s3_roundtrip(self, df_compat, s3_public_bucket, fp, s3so):\n # GH #19134\n check_round_trip(\n df_compat,\n fp,\n path=f"s3://{s3_public_bucket.name}/fastparquet.parquet",\n read_kwargs={"storage_options": s3so},\n write_kwargs={"compression": None, "storage_options": s3so},\n )\n\n def test_partition_cols_supported(self, tmp_path, fp, df_full):\n # GH #23283\n partition_cols = ["bool", "int"]\n df = df_full\n df.to_parquet(\n tmp_path,\n engine="fastparquet",\n partition_cols=partition_cols,\n compression=None,\n )\n assert os.path.exists(tmp_path)\n import fastparquet\n\n actual_partition_cols = fastparquet.ParquetFile(str(tmp_path), False).cats\n assert len(actual_partition_cols) == 2\n\n def test_partition_cols_string(self, tmp_path, fp, df_full):\n # GH #27117\n partition_cols = "bool"\n df = df_full\n df.to_parquet(\n tmp_path,\n engine="fastparquet",\n partition_cols=partition_cols,\n compression=None,\n )\n assert os.path.exists(tmp_path)\n import fastparquet\n\n actual_partition_cols = fastparquet.ParquetFile(str(tmp_path), False).cats\n assert len(actual_partition_cols) == 1\n\n def test_partition_on_supported(self, tmp_path, fp, df_full):\n # GH #23283\n partition_cols = ["bool", "int"]\n df = df_full\n df.to_parquet(\n tmp_path,\n engine="fastparquet",\n compression=None,\n partition_on=partition_cols,\n )\n assert os.path.exists(tmp_path)\n import fastparquet\n\n actual_partition_cols = fastparquet.ParquetFile(str(tmp_path), False).cats\n assert len(actual_partition_cols) == 2\n\n def test_error_on_using_partition_cols_and_partition_on(\n self, tmp_path, fp, df_full\n ):\n # GH #23283\n partition_cols = ["bool", "int"]\n df = df_full\n msg = (\n "Cannot use both partition_on and partition_cols. Use partition_cols for "\n "partitioning data"\n )\n with pytest.raises(ValueError, match=msg):\n df.to_parquet(\n tmp_path,\n engine="fastparquet",\n compression=None,\n partition_on=partition_cols,\n partition_cols=partition_cols,\n )\n\n @pytest.mark.skipif(using_copy_on_write(), reason="fastparquet writes into Index")\n def test_empty_dataframe(self, fp):\n # GH #27339\n df = pd.DataFrame()\n expected = df.copy()\n check_round_trip(df, fp, expected=expected)\n\n def test_timezone_aware_index(self, fp, timezone_aware_date_list, request):\n import fastparquet\n\n if Version(fastparquet.__version__) > Version("2022.12") and Version(\n fastparquet.__version__\n ) < Version("2024.11.0"):\n request.applymarker(\n pytest.mark.xfail(\n reason=(\n "fastparquet bug, see "\n "https://github.com/dask/fastparquet/issues/929"\n ),\n )\n )\n\n idx = 5 * [timezone_aware_date_list]\n\n df = pd.DataFrame(index=idx, data={"index_as_col": idx})\n\n expected = df.copy()\n expected.index.name = "index"\n check_round_trip(df, fp, expected=expected)\n\n def test_use_nullable_dtypes_not_supported(self, fp):\n df = pd.DataFrame({"a": [1, 2]})\n\n with tm.ensure_clean() as path:\n df.to_parquet(path)\n with pytest.raises(ValueError, match="not supported for the fastparquet"):\n with tm.assert_produces_warning(FutureWarning):\n read_parquet(path, engine="fastparquet", use_nullable_dtypes=True)\n with pytest.raises(ValueError, match="not supported for the fastparquet"):\n read_parquet(path, engine="fastparquet", dtype_backend="pyarrow")\n\n def test_close_file_handle_on_read_error(self):\n with tm.ensure_clean("test.parquet") as path:\n pathlib.Path(path).write_bytes(b"breakit")\n with pytest.raises(Exception, match=""): # Not important which exception\n read_parquet(path, engine="fastparquet")\n # The next line raises an error on Windows if the file is still open\n pathlib.Path(path).unlink(missing_ok=False)\n\n def test_bytes_file_name(self, engine):\n # GH#48944\n df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]})\n with tm.ensure_clean("test.parquet") as path:\n with open(path.encode(), "wb") as f:\n df.to_parquet(f)\n\n result = read_parquet(path, engine=engine)\n tm.assert_frame_equal(result, df)\n\n def test_filesystem_notimplemented(self):\n pytest.importorskip("fastparquet")\n df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]})\n with tm.ensure_clean() as path:\n with pytest.raises(\n NotImplementedError, match="filesystem is not implemented"\n ):\n df.to_parquet(path, engine="fastparquet", filesystem="foo")\n\n with tm.ensure_clean() as path:\n pathlib.Path(path).write_bytes(b"foo")\n with pytest.raises(\n NotImplementedError, match="filesystem is not implemented"\n ):\n read_parquet(path, engine="fastparquet", filesystem="foo")\n\n def test_invalid_filesystem(self):\n pytest.importorskip("pyarrow")\n df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]})\n with tm.ensure_clean() as path:\n with pytest.raises(\n ValueError, match="filesystem must be a pyarrow or fsspec FileSystem"\n ):\n df.to_parquet(path, engine="pyarrow", filesystem="foo")\n\n with tm.ensure_clean() as path:\n pathlib.Path(path).write_bytes(b"foo")\n with pytest.raises(\n ValueError, match="filesystem must be a pyarrow or fsspec FileSystem"\n ):\n read_parquet(path, engine="pyarrow", filesystem="foo")\n\n def test_unsupported_pa_filesystem_storage_options(self):\n pa_fs = pytest.importorskip("pyarrow.fs")\n df = pd.DataFrame(data={"A": [0, 1], "B": [1, 0]})\n with tm.ensure_clean() as path:\n with pytest.raises(\n NotImplementedError,\n match="storage_options not supported with a pyarrow FileSystem.",\n ):\n df.to_parquet(\n path,\n engine="pyarrow",\n filesystem=pa_fs.LocalFileSystem(),\n storage_options={"foo": "bar"},\n )\n\n with tm.ensure_clean() as path:\n pathlib.Path(path).write_bytes(b"foo")\n with pytest.raises(\n NotImplementedError,\n match="storage_options not supported with a pyarrow FileSystem.",\n ):\n read_parquet(\n path,\n engine="pyarrow",\n filesystem=pa_fs.LocalFileSystem(),\n storage_options={"foo": "bar"},\n )\n\n def test_invalid_dtype_backend(self, engine):\n msg = (\n "dtype_backend numpy is invalid, only 'numpy_nullable' and "\n "'pyarrow' are allowed."\n )\n df = pd.DataFrame({"int": list(range(1, 4))})\n with tm.ensure_clean("tmp.parquet") as path:\n df.to_parquet(path)\n with pytest.raises(ValueError, match=msg):\n read_parquet(path, dtype_backend="numpy")\n\n @pytest.mark.skipif(using_copy_on_write(), reason="fastparquet writes into Index")\n def test_empty_columns(self, fp):\n # GH 52034\n df = pd.DataFrame(index=pd.Index(["a", "b", "c"], name="custom name"))\n expected = pd.DataFrame(index=pd.Index(["a", "b", "c"], name="custom name"))\n check_round_trip(df, fp, expected=expected)\n
.venv\Lib\site-packages\pandas\tests\io\test_parquet.py
test_parquet.py
Python
53,124
0.75
0.105193
0.101721
vue-tools
910
2024-08-09T23:46:27.976062
MIT
true
81702386d20c2ba0fe808288cf225ea7
"""\nmanage legacy pickle tests\n\nHow to add pickle tests:\n\n1. Install pandas version intended to output the pickle.\n\n2. Execute "generate_legacy_storage_files.py" to create the pickle.\n$ python generate_legacy_storage_files.py <output_dir> pickle\n\n3. Move the created pickle to "data/legacy_pickle/<version>" directory.\n"""\nfrom __future__ import annotations\n\nfrom array import array\nimport bz2\nimport datetime\nimport functools\nfrom functools import partial\nimport gzip\nimport io\nimport os\nfrom pathlib import Path\nimport pickle\nimport shutil\nimport tarfile\nfrom typing import Any\nimport uuid\nimport zipfile\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import (\n get_lzma_file,\n is_platform_little_endian,\n)\nfrom pandas.compat._optional import import_optional_dependency\nfrom pandas.compat.compressors import flatten_buffer\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n period_range,\n)\nimport pandas._testing as tm\nfrom pandas.tests.io.generate_legacy_storage_files import create_pickle_data\n\nimport pandas.io.common as icom\nfrom pandas.tseries.offsets import (\n Day,\n MonthEnd,\n)\n\n\n# ---------------------\n# comparison functions\n# ---------------------\ndef compare_element(result, expected, typ):\n if isinstance(expected, Index):\n tm.assert_index_equal(expected, result)\n return\n\n if typ.startswith("sp_"):\n tm.assert_equal(result, expected)\n elif typ == "timestamp":\n if expected is pd.NaT:\n assert result is pd.NaT\n else:\n assert result == expected\n else:\n comparator = getattr(tm, f"assert_{typ}_equal", tm.assert_almost_equal)\n comparator(result, expected)\n\n\n# ---------------------\n# tests\n# ---------------------\n\n\n@pytest.mark.parametrize(\n "data",\n [\n b"123",\n b"123456",\n bytearray(b"123"),\n memoryview(b"123"),\n pickle.PickleBuffer(b"123"),\n array("I", [1, 2, 3]),\n memoryview(b"123456").cast("B", (3, 2)),\n memoryview(b"123456").cast("B", (3, 2))[::2],\n np.arange(12).reshape((3, 4), order="C"),\n np.arange(12).reshape((3, 4), order="F"),\n np.arange(12).reshape((3, 4), order="C")[:, ::2],\n ],\n)\ndef test_flatten_buffer(data):\n result = flatten_buffer(data)\n expected = memoryview(data).tobytes("A")\n assert result == expected\n if isinstance(data, (bytes, bytearray)):\n assert result is data\n elif isinstance(result, memoryview):\n assert result.ndim == 1\n assert result.format == "B"\n assert result.contiguous\n assert result.shape == (result.nbytes,)\n\n\ndef test_pickles(datapath):\n if not is_platform_little_endian():\n pytest.skip("known failure on non-little endian")\n\n # For loop for compat with --strict-data-files\n for legacy_pickle in Path(__file__).parent.glob("data/legacy_pickle/*/*.p*kl*"):\n legacy_pickle = datapath(legacy_pickle)\n\n data = pd.read_pickle(legacy_pickle)\n\n for typ, dv in data.items():\n for dt, result in dv.items():\n expected = data[typ][dt]\n\n if typ == "series" and dt == "ts":\n # GH 7748\n tm.assert_series_equal(result, expected)\n assert result.index.freq == expected.index.freq\n assert not result.index.freq.normalize\n tm.assert_series_equal(result > 0, expected > 0)\n\n # GH 9291\n freq = result.index.freq\n assert freq + Day(1) == Day(2)\n\n res = freq + pd.Timedelta(hours=1)\n assert isinstance(res, pd.Timedelta)\n assert res == pd.Timedelta(days=1, hours=1)\n\n res = freq + pd.Timedelta(nanoseconds=1)\n assert isinstance(res, pd.Timedelta)\n assert res == pd.Timedelta(days=1, nanoseconds=1)\n elif typ == "index" and dt == "period":\n tm.assert_index_equal(result, expected)\n assert isinstance(result.freq, MonthEnd)\n assert result.freq == MonthEnd()\n assert result.freqstr == "M"\n tm.assert_index_equal(result.shift(2), expected.shift(2))\n elif typ == "series" and dt in ("dt_tz", "cat"):\n tm.assert_series_equal(result, expected)\n elif typ == "frame" and dt in (\n "dt_mixed_tzs",\n "cat_onecol",\n "cat_and_float",\n ):\n tm.assert_frame_equal(result, expected)\n else:\n compare_element(result, expected, typ)\n\n\ndef python_pickler(obj, path):\n with open(path, "wb") as fh:\n pickle.dump(obj, fh, protocol=-1)\n\n\ndef python_unpickler(path):\n with open(path, "rb") as fh:\n fh.seek(0)\n return pickle.load(fh)\n\n\ndef flatten(data: dict) -> list[tuple[str, Any]]:\n """Flatten create_pickle_data"""\n return [\n (typ, example)\n for typ, examples in data.items()\n for example in examples.values()\n ]\n\n\n@pytest.mark.parametrize(\n "pickle_writer",\n [\n pytest.param(python_pickler, id="python"),\n pytest.param(pd.to_pickle, id="pandas_proto_default"),\n pytest.param(\n functools.partial(pd.to_pickle, protocol=pickle.HIGHEST_PROTOCOL),\n id="pandas_proto_highest",\n ),\n pytest.param(functools.partial(pd.to_pickle, protocol=4), id="pandas_proto_4"),\n pytest.param(\n functools.partial(pd.to_pickle, protocol=5),\n id="pandas_proto_5",\n ),\n ],\n)\n@pytest.mark.parametrize("writer", [pd.to_pickle, python_pickler])\n@pytest.mark.parametrize("typ, expected", flatten(create_pickle_data()))\ndef test_round_trip_current(typ, expected, pickle_writer, writer):\n with tm.ensure_clean() as path:\n # test writing with each pickler\n pickle_writer(expected, path)\n\n # test reading with each unpickler\n result = pd.read_pickle(path)\n compare_element(result, expected, typ)\n\n result = python_unpickler(path)\n compare_element(result, expected, typ)\n\n # and the same for file objects (GH 35679)\n with open(path, mode="wb") as handle:\n writer(expected, path)\n handle.seek(0) # shouldn't close file handle\n with open(path, mode="rb") as handle:\n result = pd.read_pickle(handle)\n handle.seek(0) # shouldn't close file handle\n compare_element(result, expected, typ)\n\n\ndef test_pickle_path_pathlib():\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n result = tm.round_trip_pathlib(df.to_pickle, pd.read_pickle)\n tm.assert_frame_equal(df, result)\n\n\ndef test_pickle_path_localpath():\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n result = tm.round_trip_localpath(df.to_pickle, pd.read_pickle)\n tm.assert_frame_equal(df, result)\n\n\n# ---------------------\n# test pickle compression\n# ---------------------\n\n\n@pytest.fixture\ndef get_random_path():\n return f"__{uuid.uuid4()}__.pickle"\n\n\nclass TestCompression:\n _extension_to_compression = icom.extension_to_compression\n\n def compress_file(self, src_path, dest_path, compression):\n if compression is None:\n shutil.copyfile(src_path, dest_path)\n return\n\n if compression == "gzip":\n f = gzip.open(dest_path, "w")\n elif compression == "bz2":\n f = bz2.BZ2File(dest_path, "w")\n elif compression == "zip":\n with zipfile.ZipFile(dest_path, "w", compression=zipfile.ZIP_DEFLATED) as f:\n f.write(src_path, os.path.basename(src_path))\n elif compression == "tar":\n with open(src_path, "rb") as fh:\n with tarfile.open(dest_path, mode="w") as tar:\n tarinfo = tar.gettarinfo(src_path, os.path.basename(src_path))\n tar.addfile(tarinfo, fh)\n elif compression == "xz":\n f = get_lzma_file()(dest_path, "w")\n elif compression == "zstd":\n f = import_optional_dependency("zstandard").open(dest_path, "wb")\n else:\n msg = f"Unrecognized compression type: {compression}"\n raise ValueError(msg)\n\n if compression not in ["zip", "tar"]:\n with open(src_path, "rb") as fh:\n with f:\n f.write(fh.read())\n\n def test_write_explicit(self, compression, get_random_path):\n base = get_random_path\n path1 = base + ".compressed"\n path2 = base + ".raw"\n\n with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n\n # write to compressed file\n df.to_pickle(p1, compression=compression)\n\n # decompress\n with tm.decompress_file(p1, compression=compression) as f:\n with open(p2, "wb") as fh:\n fh.write(f.read())\n\n # read decompressed file\n df2 = pd.read_pickle(p2, compression=None)\n\n tm.assert_frame_equal(df, df2)\n\n @pytest.mark.parametrize("compression", ["", "None", "bad", "7z"])\n def test_write_explicit_bad(self, compression, get_random_path):\n with pytest.raises(ValueError, match="Unrecognized compression type"):\n with tm.ensure_clean(get_random_path) as path:\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n df.to_pickle(path, compression=compression)\n\n def test_write_infer(self, compression_ext, get_random_path):\n base = get_random_path\n path1 = base + compression_ext\n path2 = base + ".raw"\n compression = self._extension_to_compression.get(compression_ext.lower())\n\n with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n\n # write to compressed file by inferred compression method\n df.to_pickle(p1)\n\n # decompress\n with tm.decompress_file(p1, compression=compression) as f:\n with open(p2, "wb") as fh:\n fh.write(f.read())\n\n # read decompressed file\n df2 = pd.read_pickle(p2, compression=None)\n\n tm.assert_frame_equal(df, df2)\n\n def test_read_explicit(self, compression, get_random_path):\n base = get_random_path\n path1 = base + ".raw"\n path2 = base + ".compressed"\n\n with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n\n # write to uncompressed file\n df.to_pickle(p1, compression=None)\n\n # compress\n self.compress_file(p1, p2, compression=compression)\n\n # read compressed file\n df2 = pd.read_pickle(p2, compression=compression)\n tm.assert_frame_equal(df, df2)\n\n def test_read_infer(self, compression_ext, get_random_path):\n base = get_random_path\n path1 = base + ".raw"\n path2 = base + compression_ext\n compression = self._extension_to_compression.get(compression_ext.lower())\n\n with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2:\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n\n # write to uncompressed file\n df.to_pickle(p1, compression=None)\n\n # compress\n self.compress_file(p1, p2, compression=compression)\n\n # read compressed file by inferred compression method\n df2 = pd.read_pickle(p2)\n tm.assert_frame_equal(df, df2)\n\n\n# ---------------------\n# test pickle compression\n# ---------------------\n\n\nclass TestProtocol:\n @pytest.mark.parametrize("protocol", [-1, 0, 1, 2])\n def test_read(self, protocol, get_random_path):\n with tm.ensure_clean(get_random_path) as path:\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n df.to_pickle(path, protocol=protocol)\n df2 = pd.read_pickle(path)\n tm.assert_frame_equal(df, df2)\n\n\n@pytest.mark.parametrize(\n ["pickle_file", "excols"],\n [\n ("test_py27.pkl", Index(["a", "b", "c"], dtype=object)),\n (\n "test_mi_py27.pkl",\n pd.MultiIndex(\n [\n Index(["a", "b", "c"], dtype=object),\n Index(["A", "B", "C"], dtype=object),\n ],\n [np.array([0, 1, 2]), np.array([0, 1, 2])],\n ),\n ),\n ],\n)\ndef test_unicode_decode_error(datapath, pickle_file, excols):\n # pickle file written with py27, should be readable without raising\n # UnicodeDecodeError, see GH#28645 and GH#31988\n path = datapath("io", "data", "pickle", pickle_file)\n df = pd.read_pickle(path)\n\n # just test the columns are correct since the values are random\n tm.assert_index_equal(df.columns, excols)\n\n\n# ---------------------\n# tests for buffer I/O\n# ---------------------\n\n\ndef test_pickle_buffer_roundtrip():\n with tm.ensure_clean() as path:\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n with open(path, "wb") as fh:\n df.to_pickle(fh)\n with open(path, "rb") as fh:\n result = pd.read_pickle(fh)\n tm.assert_frame_equal(df, result)\n\n\n# ---------------------\n# tests for URL I/O\n# ---------------------\n\n\n@pytest.mark.parametrize(\n "mockurl", ["http://url.com", "ftp://test.com", "http://gzip.com"]\n)\ndef test_pickle_generalurl_read(monkeypatch, mockurl):\n def python_pickler(obj, path):\n with open(path, "wb") as fh:\n pickle.dump(obj, fh, protocol=-1)\n\n class MockReadResponse:\n def __init__(self, path) -> None:\n self.file = open(path, "rb")\n if "gzip" in path:\n self.headers = {"Content-Encoding": "gzip"}\n else:\n self.headers = {"Content-Encoding": ""}\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.close()\n\n def read(self):\n return self.file.read()\n\n def close(self):\n return self.file.close()\n\n with tm.ensure_clean() as path:\n\n def mock_urlopen_read(*args, **kwargs):\n return MockReadResponse(path)\n\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n python_pickler(df, path)\n monkeypatch.setattr("urllib.request.urlopen", mock_urlopen_read)\n result = pd.read_pickle(mockurl)\n tm.assert_frame_equal(df, result)\n\n\ndef test_pickle_fsspec_roundtrip():\n pytest.importorskip("fsspec")\n with tm.ensure_clean():\n mockurl = "memory://mockfile"\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n df.to_pickle(mockurl)\n result = pd.read_pickle(mockurl)\n tm.assert_frame_equal(df, result)\n\n\nclass MyTz(datetime.tzinfo):\n def __init__(self) -> None:\n pass\n\n\ndef test_read_pickle_with_subclass():\n # GH 12163\n expected = Series(dtype=object), MyTz()\n result = tm.round_trip_pickle(expected)\n\n tm.assert_series_equal(result[0], expected[0])\n assert isinstance(result[1], MyTz)\n\n\ndef test_pickle_binary_object_compression(compression):\n """\n Read/write from binary file-objects w/wo compression.\n\n GH 26237, GH 29054, and GH 29570\n """\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD"), dtype=object),\n index=Index([f"i-{i}" for i in range(30)], dtype=object),\n )\n\n # reference for compression\n with tm.ensure_clean() as path:\n df.to_pickle(path, compression=compression)\n reference = Path(path).read_bytes()\n\n # write\n buffer = io.BytesIO()\n df.to_pickle(buffer, compression=compression)\n buffer.seek(0)\n\n # gzip and zip safe the filename: cannot compare the compressed content\n assert buffer.getvalue() == reference or compression in ("gzip", "zip", "tar")\n\n # read\n read_df = pd.read_pickle(buffer, compression=compression)\n buffer.seek(0)\n tm.assert_frame_equal(df, read_df)\n\n\ndef test_pickle_dataframe_with_multilevel_index(\n multiindex_year_month_day_dataframe_random_data,\n multiindex_dataframe_random_data,\n):\n ymd = multiindex_year_month_day_dataframe_random_data\n frame = multiindex_dataframe_random_data\n\n def _test_roundtrip(frame):\n unpickled = tm.round_trip_pickle(frame)\n tm.assert_frame_equal(frame, unpickled)\n\n _test_roundtrip(frame)\n _test_roundtrip(frame.T)\n _test_roundtrip(ymd)\n _test_roundtrip(ymd.T)\n\n\ndef test_pickle_timeseries_periodindex():\n # GH#2891\n prng = period_range("1/1/2011", "1/1/2012", freq="M")\n ts = Series(np.random.default_rng(2).standard_normal(len(prng)), prng)\n new_ts = tm.round_trip_pickle(ts)\n assert new_ts.index.freqstr == "M"\n\n\n@pytest.mark.parametrize(\n "name", [777, 777.0, "name", datetime.datetime(2001, 11, 11), (1, 2)]\n)\ndef test_pickle_preserve_name(name):\n unpickled = tm.round_trip_pickle(Series(np.arange(10, dtype=np.float64), name=name))\n assert unpickled.name == name\n\n\ndef test_pickle_datetimes(datetime_series):\n unp_ts = tm.round_trip_pickle(datetime_series)\n tm.assert_series_equal(unp_ts, datetime_series)\n\n\ndef test_pickle_strings(string_series):\n unp_series = tm.round_trip_pickle(string_series)\n tm.assert_series_equal(unp_series, string_series)\n\n\n@td.skip_array_manager_invalid_test\ndef test_pickle_preserves_block_ndim():\n # GH#37631\n ser = Series(list("abc")).astype("category").iloc[[0]]\n res = tm.round_trip_pickle(ser)\n\n assert res._mgr.blocks[0].ndim == 1\n assert res._mgr.blocks[0].shape == (1,)\n\n # GH#37631 OP issue was about indexing, underlying problem was pickle\n tm.assert_series_equal(res[[True]], ser)\n\n\n@pytest.mark.parametrize("protocol", [pickle.DEFAULT_PROTOCOL, pickle.HIGHEST_PROTOCOL])\ndef test_pickle_big_dataframe_compression(protocol, compression):\n # GH#39002\n df = DataFrame(range(100000))\n result = tm.round_trip_pathlib(\n partial(df.to_pickle, protocol=protocol, compression=compression),\n partial(pd.read_pickle, compression=compression),\n )\n tm.assert_frame_equal(df, result)\n\n\ndef test_pickle_frame_v124_unpickle_130(datapath):\n # GH#42345 DataFrame created in 1.2.x, unpickle in 1.3.x\n path = datapath(\n Path(__file__).parent,\n "data",\n "legacy_pickle",\n "1.2.4",\n "empty_frame_v1_2_4-GH#42345.pkl",\n )\n with open(path, "rb") as fd:\n df = pickle.load(fd)\n\n expected = DataFrame(index=[], columns=[])\n tm.assert_frame_equal(df, expected)\n\n\ndef test_pickle_pos_args_deprecation():\n # GH-54229\n df = DataFrame({"a": [1, 2, 3]})\n msg = (\n r"Starting with pandas version 3.0 all arguments of to_pickle except for the "\n r"argument 'path' will be keyword-only."\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n buffer = io.BytesIO()\n df.to_pickle(buffer, "infer")\n
.venv\Lib\site-packages\pandas\tests\io\test_pickle.py
test_pickle.py
Python
20,949
0.95
0.118541
0.095057
react-lib
562
2025-06-01T05:14:36.916917
MIT
true
0f0e670a097d09e4a3ca0210951a79d2
from io import BytesIO\n\nimport pytest\n\nfrom pandas import read_csv\n\n\ndef test_streaming_s3_objects():\n # GH17135\n # botocore gained iteration support in 1.10.47, can now be used in read_*\n pytest.importorskip("botocore", minversion="1.10.47")\n from botocore.response import StreamingBody\n\n data = [b"foo,bar,baz\n1,2,3\n4,5,6\n", b"just,the,header\n"]\n for el in data:\n body = StreamingBody(BytesIO(el), content_length=len(el))\n read_csv(body)\n\n\n@pytest.mark.single_cpu\ndef test_read_without_creds_from_pub_bucket(s3_public_bucket_with_data, s3so):\n # GH 34626\n pytest.importorskip("s3fs")\n result = read_csv(\n f"s3://{s3_public_bucket_with_data.name}/tips.csv",\n nrows=3,\n storage_options=s3so,\n )\n assert len(result) == 3\n\n\n@pytest.mark.single_cpu\ndef test_read_with_creds_from_pub_bucket(s3_public_bucket_with_data, s3so):\n # Ensure we can read from a public bucket with credentials\n # GH 34626\n pytest.importorskip("s3fs")\n df = read_csv(\n f"s3://{s3_public_bucket_with_data.name}/tips.csv",\n nrows=5,\n header=None,\n storage_options=s3so,\n )\n assert len(df) == 5\n
.venv\Lib\site-packages\pandas\tests\io\test_s3.py
test_s3.py
Python
1,181
0.95
0.093023
0.147059
react-lib
881
2024-04-17T17:04:16.136543
BSD-3-Clause
true
57ca45142bf97774a2c54d26d8e3e3bf
import datetime\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.util.version import Version\n\npyreadstat = pytest.importorskip("pyreadstat")\n\n\n# TODO(CoW) - detection of chained assignment in cython\n# https://github.com/pandas-dev/pandas/issues/51315\n@pytest.mark.filterwarnings("ignore::pandas.errors.ChainedAssignmentError")\n@pytest.mark.filterwarnings("ignore:ChainedAssignmentError:FutureWarning")\n@pytest.mark.parametrize("path_klass", [lambda p: p, Path])\ndef test_spss_labelled_num(path_klass, datapath):\n # test file from the Haven project (https://haven.tidyverse.org/)\n # Licence at LICENSES/HAVEN_LICENSE, LICENSES/HAVEN_MIT\n fname = path_klass(datapath("io", "data", "spss", "labelled-num.sav"))\n\n df = pd.read_spss(fname, convert_categoricals=True)\n expected = pd.DataFrame({"VAR00002": "This is one"}, index=[0])\n expected["VAR00002"] = pd.Categorical(expected["VAR00002"])\n tm.assert_frame_equal(df, expected)\n\n df = pd.read_spss(fname, convert_categoricals=False)\n expected = pd.DataFrame({"VAR00002": 1.0}, index=[0])\n tm.assert_frame_equal(df, expected)\n\n\n@pytest.mark.filterwarnings("ignore::pandas.errors.ChainedAssignmentError")\n@pytest.mark.filterwarnings("ignore:ChainedAssignmentError:FutureWarning")\ndef test_spss_labelled_num_na(datapath):\n # test file from the Haven project (https://haven.tidyverse.org/)\n # Licence at LICENSES/HAVEN_LICENSE, LICENSES/HAVEN_MIT\n fname = datapath("io", "data", "spss", "labelled-num-na.sav")\n\n df = pd.read_spss(fname, convert_categoricals=True)\n expected = pd.DataFrame({"VAR00002": ["This is one", None]})\n expected["VAR00002"] = pd.Categorical(expected["VAR00002"])\n tm.assert_frame_equal(df, expected)\n\n df = pd.read_spss(fname, convert_categoricals=False)\n expected = pd.DataFrame({"VAR00002": [1.0, np.nan]})\n tm.assert_frame_equal(df, expected)\n\n\n@pytest.mark.filterwarnings("ignore::pandas.errors.ChainedAssignmentError")\n@pytest.mark.filterwarnings("ignore:ChainedAssignmentError:FutureWarning")\ndef test_spss_labelled_str(datapath):\n # test file from the Haven project (https://haven.tidyverse.org/)\n # Licence at LICENSES/HAVEN_LICENSE, LICENSES/HAVEN_MIT\n fname = datapath("io", "data", "spss", "labelled-str.sav")\n\n df = pd.read_spss(fname, convert_categoricals=True)\n expected = pd.DataFrame({"gender": ["Male", "Female"]})\n expected["gender"] = pd.Categorical(expected["gender"])\n tm.assert_frame_equal(df, expected)\n\n df = pd.read_spss(fname, convert_categoricals=False)\n expected = pd.DataFrame({"gender": ["M", "F"]})\n tm.assert_frame_equal(df, expected)\n\n\n@pytest.mark.filterwarnings("ignore::pandas.errors.ChainedAssignmentError")\n@pytest.mark.filterwarnings("ignore:ChainedAssignmentError:FutureWarning")\ndef test_spss_umlauts(datapath):\n # test file from the Haven project (https://haven.tidyverse.org/)\n # Licence at LICENSES/HAVEN_LICENSE, LICENSES/HAVEN_MIT\n fname = datapath("io", "data", "spss", "umlauts.sav")\n\n df = pd.read_spss(fname, convert_categoricals=True)\n expected = pd.DataFrame(\n {"var1": ["the ä umlaut", "the ü umlaut", "the ä umlaut", "the ö umlaut"]}\n )\n expected["var1"] = pd.Categorical(expected["var1"])\n tm.assert_frame_equal(df, expected)\n\n df = pd.read_spss(fname, convert_categoricals=False)\n expected = pd.DataFrame({"var1": [1.0, 2.0, 1.0, 3.0]})\n tm.assert_frame_equal(df, expected)\n\n\ndef test_spss_usecols(datapath):\n # usecols must be list-like\n fname = datapath("io", "data", "spss", "labelled-num.sav")\n\n with pytest.raises(TypeError, match="usecols must be list-like."):\n pd.read_spss(fname, usecols="VAR00002")\n\n\ndef test_spss_umlauts_dtype_backend(datapath, dtype_backend):\n # test file from the Haven project (https://haven.tidyverse.org/)\n # Licence at LICENSES/HAVEN_LICENSE, LICENSES/HAVEN_MIT\n fname = datapath("io", "data", "spss", "umlauts.sav")\n\n df = pd.read_spss(fname, convert_categoricals=False, dtype_backend=dtype_backend)\n expected = pd.DataFrame({"var1": [1.0, 2.0, 1.0, 3.0]}, dtype="Int64")\n\n if dtype_backend == "pyarrow":\n pa = pytest.importorskip("pyarrow")\n\n from pandas.arrays import ArrowExtensionArray\n\n expected = pd.DataFrame(\n {\n col: ArrowExtensionArray(pa.array(expected[col], from_pandas=True))\n for col in expected.columns\n }\n )\n\n tm.assert_frame_equal(df, expected)\n\n\ndef test_invalid_dtype_backend():\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 pd.read_spss("test", dtype_backend="numpy")\n\n\n@pytest.mark.filterwarnings("ignore::pandas.errors.ChainedAssignmentError")\n@pytest.mark.filterwarnings("ignore:ChainedAssignmentError:FutureWarning")\ndef test_spss_metadata(datapath):\n # GH 54264\n fname = datapath("io", "data", "spss", "labelled-num.sav")\n\n df = pd.read_spss(fname)\n metadata = {\n "column_names": ["VAR00002"],\n "column_labels": [None],\n "column_names_to_labels": {"VAR00002": None},\n "file_encoding": "UTF-8",\n "number_columns": 1,\n "number_rows": 1,\n "variable_value_labels": {"VAR00002": {1.0: "This is one"}},\n "value_labels": {"labels0": {1.0: "This is one"}},\n "variable_to_label": {"VAR00002": "labels0"},\n "notes": [],\n "original_variable_types": {"VAR00002": "F8.0"},\n "readstat_variable_types": {"VAR00002": "double"},\n "table_name": None,\n "missing_ranges": {},\n "missing_user_values": {},\n "variable_storage_width": {"VAR00002": 8},\n "variable_display_width": {"VAR00002": 8},\n "variable_alignment": {"VAR00002": "unknown"},\n "variable_measure": {"VAR00002": "unknown"},\n "file_label": None,\n "file_format": "sav/zsav",\n }\n if Version(pyreadstat.__version__) >= Version("1.2.4"):\n metadata.update(\n {\n "creation_time": datetime.datetime(2015, 2, 6, 14, 33, 36),\n "modification_time": datetime.datetime(2015, 2, 6, 14, 33, 36),\n }\n )\n if Version(pyreadstat.__version__) >= Version("1.2.8"):\n metadata["mr_sets"] = {}\n tm.assert_dict_equal(df.attrs, metadata)\n
.venv\Lib\site-packages\pandas\tests\io\test_spss.py
test_spss.py
Python
6,432
0.95
0.072289
0.106061
react-lib
463
2024-07-23T11:31:39.005182
Apache-2.0
true
e72b7d01038d760e5c1c3ea60278c159
import bz2\nimport datetime as dt\nfrom datetime import datetime\nimport gzip\nimport io\nimport os\nimport struct\nimport tarfile\nimport zipfile\n\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import CategoricalDtype\nimport pandas._testing as tm\nfrom pandas.core.frame import (\n DataFrame,\n Series,\n)\n\nfrom pandas.io.parsers import read_csv\nfrom pandas.io.stata import (\n CategoricalConversionWarning,\n InvalidColumnName,\n PossiblePrecisionLoss,\n StataMissingValue,\n StataReader,\n StataWriter,\n StataWriterUTF8,\n ValueLabelTypeMismatch,\n read_stata,\n)\n\n\n@pytest.fixture\ndef mixed_frame():\n return DataFrame(\n {\n "a": [1, 2, 3, 4],\n "b": [1.0, 3.0, 27.0, 81.0],\n "c": ["Atlanta", "Birmingham", "Cincinnati", "Detroit"],\n }\n )\n\n\n@pytest.fixture\ndef parsed_114(datapath):\n dta14_114 = datapath("io", "data", "stata", "stata5_114.dta")\n parsed_114 = read_stata(dta14_114, convert_dates=True)\n parsed_114.index.name = "index"\n return parsed_114\n\n\nclass TestStata:\n def read_dta(self, file):\n # Legacy default reader configuration\n return read_stata(file, convert_dates=True)\n\n def read_csv(self, file):\n return read_csv(file, parse_dates=True)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_read_empty_dta(self, version):\n empty_ds = DataFrame(columns=["unit"])\n # GH 7369, make sure can read a 0-obs dta file\n with tm.ensure_clean() as path:\n empty_ds.to_stata(path, write_index=False, version=version)\n empty_ds2 = read_stata(path)\n tm.assert_frame_equal(empty_ds, empty_ds2)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_read_empty_dta_with_dtypes(self, version):\n # GH 46240\n # Fixing above bug revealed that types are not correctly preserved when\n # writing empty DataFrames\n empty_df_typed = DataFrame(\n {\n "i8": np.array([0], dtype=np.int8),\n "i16": np.array([0], dtype=np.int16),\n "i32": np.array([0], dtype=np.int32),\n "i64": np.array([0], dtype=np.int64),\n "u8": np.array([0], dtype=np.uint8),\n "u16": np.array([0], dtype=np.uint16),\n "u32": np.array([0], dtype=np.uint32),\n "u64": np.array([0], dtype=np.uint64),\n "f32": np.array([0], dtype=np.float32),\n "f64": np.array([0], dtype=np.float64),\n }\n )\n expected = empty_df_typed.copy()\n # No uint# support. Downcast since values in range for int#\n expected["u8"] = expected["u8"].astype(np.int8)\n expected["u16"] = expected["u16"].astype(np.int16)\n expected["u32"] = expected["u32"].astype(np.int32)\n # No int64 supported at all. Downcast since values in range for int32\n expected["u64"] = expected["u64"].astype(np.int32)\n expected["i64"] = expected["i64"].astype(np.int32)\n\n # GH 7369, make sure can read a 0-obs dta file\n with tm.ensure_clean() as path:\n empty_df_typed.to_stata(path, write_index=False, version=version)\n empty_reread = read_stata(path)\n tm.assert_frame_equal(expected, empty_reread)\n tm.assert_series_equal(expected.dtypes, empty_reread.dtypes)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_read_index_col_none(self, version):\n df = DataFrame({"a": range(5), "b": ["b1", "b2", "b3", "b4", "b5"]})\n # GH 7369, make sure can read a 0-obs dta file\n with tm.ensure_clean() as path:\n df.to_stata(path, write_index=False, version=version)\n read_df = read_stata(path)\n\n assert isinstance(read_df.index, pd.RangeIndex)\n expected = df.copy()\n expected["a"] = expected["a"].astype(np.int32)\n tm.assert_frame_equal(read_df, expected, check_index_type=True)\n\n @pytest.mark.parametrize("file", ["stata1_114", "stata1_117"])\n def test_read_dta1(self, file, datapath):\n file = datapath("io", "data", "stata", f"{file}.dta")\n parsed = self.read_dta(file)\n\n # Pandas uses np.nan as missing value.\n # Thus, all columns will be of type float, regardless of their name.\n expected = DataFrame(\n [(np.nan, np.nan, np.nan, np.nan, np.nan)],\n columns=["float_miss", "double_miss", "byte_miss", "int_miss", "long_miss"],\n )\n\n # this is an oddity as really the nan should be float64, but\n # the casting doesn't fail so need to match stata here\n expected["float_miss"] = expected["float_miss"].astype(np.float32)\n\n tm.assert_frame_equal(parsed, expected)\n\n def test_read_dta2(self, datapath):\n expected = DataFrame.from_records(\n [\n (\n datetime(2006, 11, 19, 23, 13, 20),\n 1479596223000,\n datetime(2010, 1, 20),\n datetime(2010, 1, 8),\n datetime(2010, 1, 1),\n datetime(1974, 7, 1),\n datetime(2010, 1, 1),\n datetime(2010, 1, 1),\n ),\n (\n datetime(1959, 12, 31, 20, 3, 20),\n -1479590,\n datetime(1953, 10, 2),\n datetime(1948, 6, 10),\n datetime(1955, 1, 1),\n datetime(1955, 7, 1),\n datetime(1955, 1, 1),\n datetime(2, 1, 1),\n ),\n (pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT),\n ],\n columns=[\n "datetime_c",\n "datetime_big_c",\n "date",\n "weekly_date",\n "monthly_date",\n "quarterly_date",\n "half_yearly_date",\n "yearly_date",\n ],\n )\n expected["yearly_date"] = expected["yearly_date"].astype("O")\n\n path1 = datapath("io", "data", "stata", "stata2_114.dta")\n path2 = datapath("io", "data", "stata", "stata2_115.dta")\n path3 = datapath("io", "data", "stata", "stata2_117.dta")\n\n with tm.assert_produces_warning(UserWarning):\n parsed_114 = self.read_dta(path1)\n with tm.assert_produces_warning(UserWarning):\n parsed_115 = self.read_dta(path2)\n with tm.assert_produces_warning(UserWarning):\n parsed_117 = self.read_dta(path3)\n # FIXME: don't leave commented-out\n # 113 is buggy due to limits of date format support in Stata\n # parsed_113 = self.read_dta(\n # datapath("io", "data", "stata", "stata2_113.dta")\n # )\n\n # FIXME: don't leave commented-out\n # buggy test because of the NaT comparison on certain platforms\n # Format 113 test fails since it does not support tc and tC formats\n # tm.assert_frame_equal(parsed_113, expected)\n tm.assert_frame_equal(parsed_114, expected, check_datetimelike_compat=True)\n tm.assert_frame_equal(parsed_115, expected, check_datetimelike_compat=True)\n tm.assert_frame_equal(parsed_117, expected, check_datetimelike_compat=True)\n\n @pytest.mark.parametrize(\n "file", ["stata3_113", "stata3_114", "stata3_115", "stata3_117"]\n )\n def test_read_dta3(self, file, datapath):\n file = datapath("io", "data", "stata", f"{file}.dta")\n parsed = self.read_dta(file)\n\n # match stata here\n expected = self.read_csv(datapath("io", "data", "stata", "stata3.csv"))\n expected = expected.astype(np.float32)\n expected["year"] = expected["year"].astype(np.int16)\n expected["quarter"] = expected["quarter"].astype(np.int8)\n\n tm.assert_frame_equal(parsed, expected)\n\n @pytest.mark.parametrize(\n "file", ["stata4_113", "stata4_114", "stata4_115", "stata4_117"]\n )\n def test_read_dta4(self, file, datapath):\n file = datapath("io", "data", "stata", f"{file}.dta")\n parsed = self.read_dta(file)\n\n expected = DataFrame.from_records(\n [\n ["one", "ten", "one", "one", "one"],\n ["two", "nine", "two", "two", "two"],\n ["three", "eight", "three", "three", "three"],\n ["four", "seven", 4, "four", "four"],\n ["five", "six", 5, np.nan, "five"],\n ["six", "five", 6, np.nan, "six"],\n ["seven", "four", 7, np.nan, "seven"],\n ["eight", "three", 8, np.nan, "eight"],\n ["nine", "two", 9, np.nan, "nine"],\n ["ten", "one", "ten", np.nan, "ten"],\n ],\n columns=[\n "fully_labeled",\n "fully_labeled2",\n "incompletely_labeled",\n "labeled_with_missings",\n "float_labelled",\n ],\n )\n\n # these are all categoricals\n for col in expected:\n orig = expected[col].copy()\n\n categories = np.asarray(expected["fully_labeled"][orig.notna()])\n if col == "incompletely_labeled":\n categories = orig\n\n cat = orig.astype("category")._values\n cat = cat.set_categories(categories, ordered=True)\n cat.categories.rename(None, inplace=True)\n\n expected[col] = cat\n\n # stata doesn't save .category metadata\n tm.assert_frame_equal(parsed, expected)\n\n # File containing strls\n def test_read_dta12(self, datapath):\n parsed_117 = self.read_dta(datapath("io", "data", "stata", "stata12_117.dta"))\n expected = DataFrame.from_records(\n [\n [1, "abc", "abcdefghi"],\n [3, "cba", "qwertywertyqwerty"],\n [93, "", "strl"],\n ],\n columns=["x", "y", "z"],\n )\n\n tm.assert_frame_equal(parsed_117, expected, check_dtype=False)\n\n def test_read_dta18(self, datapath):\n parsed_118 = self.read_dta(datapath("io", "data", "stata", "stata14_118.dta"))\n parsed_118["Bytes"] = parsed_118["Bytes"].astype("O")\n expected = DataFrame.from_records(\n [\n ["Cat", "Bogota", "Bogotá", 1, 1.0, "option b Ünicode", 1.0],\n ["Dog", "Boston", "Uzunköprü", np.nan, np.nan, np.nan, np.nan],\n ["Plane", "Rome", "Tromsø", 0, 0.0, "option a", 0.0],\n ["Potato", "Tokyo", "Elâzığ", -4, 4.0, 4, 4], # noqa: RUF001\n ["", "", "", 0, 0.3332999, "option a", 1 / 3.0],\n ],\n columns=[\n "Things",\n "Cities",\n "Unicode_Cities_Strl",\n "Ints",\n "Floats",\n "Bytes",\n "Longs",\n ],\n )\n expected["Floats"] = expected["Floats"].astype(np.float32)\n for col in parsed_118.columns:\n tm.assert_almost_equal(parsed_118[col], expected[col])\n\n with StataReader(datapath("io", "data", "stata", "stata14_118.dta")) as rdr:\n vl = rdr.variable_labels()\n vl_expected = {\n "Unicode_Cities_Strl": "Here are some strls with Ünicode chars",\n "Longs": "long data",\n "Things": "Here are some things",\n "Bytes": "byte data",\n "Ints": "int data",\n "Cities": "Here are some cities",\n "Floats": "float data",\n }\n tm.assert_dict_equal(vl, vl_expected)\n\n assert rdr.data_label == "This is a Ünicode data label"\n\n def test_read_write_dta5(self):\n original = DataFrame(\n [(np.nan, np.nan, np.nan, np.nan, np.nan)],\n columns=["float_miss", "double_miss", "byte_miss", "int_miss", "long_miss"],\n )\n original.index.name = "index"\n\n with tm.ensure_clean() as path:\n original.to_stata(path, convert_dates=None)\n written_and_read_again = self.read_dta(path)\n\n expected = original.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)\n\n def test_write_dta6(self, datapath):\n original = self.read_csv(datapath("io", "data", "stata", "stata3.csv"))\n original.index.name = "index"\n original.index = original.index.astype(np.int32)\n original["year"] = original["year"].astype(np.int32)\n original["quarter"] = original["quarter"].astype(np.int32)\n\n with tm.ensure_clean() as path:\n original.to_stata(path, convert_dates=None)\n written_and_read_again = self.read_dta(path)\n tm.assert_frame_equal(\n written_and_read_again.set_index("index"),\n original,\n check_index_type=False,\n )\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_read_write_dta10(self, version, using_infer_string):\n original = DataFrame(\n data=[["string", "object", 1, 1.1, np.datetime64("2003-12-25")]],\n columns=["string", "object", "integer", "floating", "datetime"],\n )\n original["object"] = Series(original["object"], dtype=object)\n original.index.name = "index"\n original.index = original.index.astype(np.int32)\n original["integer"] = original["integer"].astype(np.int32)\n\n with tm.ensure_clean() as path:\n original.to_stata(path, convert_dates={"datetime": "tc"}, version=version)\n written_and_read_again = self.read_dta(path)\n\n expected = original.copy()\n if using_infer_string:\n expected["object"] = expected["object"].astype("str")\n\n # original.index is np.int32, read index is np.int64\n tm.assert_frame_equal(\n written_and_read_again.set_index("index"),\n expected,\n check_index_type=False,\n )\n\n def test_stata_doc_examples(self):\n with tm.ensure_clean() as path:\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 2)), columns=list("AB")\n )\n df.to_stata(path)\n\n def test_write_preserves_original(self):\n # 9795\n\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 4)), columns=list("abcd")\n )\n df.loc[2, "a":"c"] = np.nan\n df_copy = df.copy()\n with tm.ensure_clean() as path:\n df.to_stata(path, write_index=False)\n tm.assert_frame_equal(df, df_copy)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_encoding(self, version, datapath):\n # GH 4626, proper encoding handling\n raw = read_stata(datapath("io", "data", "stata", "stata1_encoding.dta"))\n encoded = read_stata(datapath("io", "data", "stata", "stata1_encoding.dta"))\n result = encoded.kreis1849[0]\n\n expected = raw.kreis1849[0]\n assert result == expected\n assert isinstance(result, str)\n\n with tm.ensure_clean() as path:\n encoded.to_stata(path, write_index=False, version=version)\n reread_encoded = read_stata(path)\n tm.assert_frame_equal(encoded, reread_encoded)\n\n def test_read_write_dta11(self):\n original = DataFrame(\n [(1, 2, 3, 4)],\n columns=[\n "good",\n "b\u00E4d",\n "8number",\n "astringwithmorethan32characters______",\n ],\n )\n formatted = DataFrame(\n [(1, 2, 3, 4)],\n columns=["good", "b_d", "_8number", "astringwithmorethan32characters_"],\n )\n formatted.index.name = "index"\n formatted = formatted.astype(np.int32)\n\n with tm.ensure_clean() as path:\n with tm.assert_produces_warning(InvalidColumnName):\n original.to_stata(path, convert_dates=None)\n\n written_and_read_again = self.read_dta(path)\n\n expected = formatted.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_read_write_dta12(self, version):\n original = DataFrame(\n [(1, 2, 3, 4, 5, 6)],\n columns=[\n "astringwithmorethan32characters_1",\n "astringwithmorethan32characters_2",\n "+",\n "-",\n "short",\n "delete",\n ],\n )\n formatted = DataFrame(\n [(1, 2, 3, 4, 5, 6)],\n columns=[\n "astringwithmorethan32characters_",\n "_0astringwithmorethan32character",\n "_",\n "_1_",\n "_short",\n "_delete",\n ],\n )\n formatted.index.name = "index"\n formatted = formatted.astype(np.int32)\n\n with tm.ensure_clean() as path:\n with tm.assert_produces_warning(InvalidColumnName):\n original.to_stata(path, convert_dates=None, version=version)\n # should get a warning for that format.\n\n written_and_read_again = self.read_dta(path)\n\n expected = formatted.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)\n\n def test_read_write_dta13(self):\n s1 = Series(2**9, dtype=np.int16)\n s2 = Series(2**17, dtype=np.int32)\n s3 = Series(2**33, dtype=np.int64)\n original = DataFrame({"int16": s1, "int32": s2, "int64": s3})\n original.index.name = "index"\n\n formatted = original\n formatted["int64"] = formatted["int64"].astype(np.float64)\n\n with tm.ensure_clean() as path:\n original.to_stata(path)\n written_and_read_again = self.read_dta(path)\n\n expected = formatted.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n @pytest.mark.parametrize(\n "file", ["stata5_113", "stata5_114", "stata5_115", "stata5_117"]\n )\n def test_read_write_reread_dta14(self, file, parsed_114, version, datapath):\n file = datapath("io", "data", "stata", f"{file}.dta")\n parsed = self.read_dta(file)\n parsed.index.name = "index"\n\n tm.assert_frame_equal(parsed_114, parsed)\n\n with tm.ensure_clean() as path:\n parsed_114.to_stata(path, convert_dates={"date_td": "td"}, version=version)\n written_and_read_again = self.read_dta(path)\n\n expected = parsed_114.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)\n\n @pytest.mark.parametrize(\n "file", ["stata6_113", "stata6_114", "stata6_115", "stata6_117"]\n )\n def test_read_write_reread_dta15(self, file, datapath):\n expected = self.read_csv(datapath("io", "data", "stata", "stata6.csv"))\n expected["byte_"] = expected["byte_"].astype(np.int8)\n expected["int_"] = expected["int_"].astype(np.int16)\n expected["long_"] = expected["long_"].astype(np.int32)\n expected["float_"] = expected["float_"].astype(np.float32)\n expected["double_"] = expected["double_"].astype(np.float64)\n expected["date_td"] = expected["date_td"].apply(\n datetime.strptime, args=("%Y-%m-%d",)\n )\n\n file = datapath("io", "data", "stata", f"{file}.dta")\n parsed = self.read_dta(file)\n\n tm.assert_frame_equal(expected, parsed)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_timestamp_and_label(self, version):\n original = DataFrame([(1,)], columns=["variable"])\n time_stamp = datetime(2000, 2, 29, 14, 21)\n data_label = "This is a data file."\n with tm.ensure_clean() as path:\n original.to_stata(\n path, time_stamp=time_stamp, data_label=data_label, version=version\n )\n\n with StataReader(path) as reader:\n assert reader.time_stamp == "29 Feb 2000 14:21"\n assert reader.data_label == data_label\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_invalid_timestamp(self, version):\n original = DataFrame([(1,)], columns=["variable"])\n time_stamp = "01 Jan 2000, 00:00:00"\n with tm.ensure_clean() as path:\n msg = "time_stamp should be datetime type"\n with pytest.raises(ValueError, match=msg):\n original.to_stata(path, time_stamp=time_stamp, version=version)\n assert not os.path.isfile(path)\n\n def test_numeric_column_names(self):\n original = DataFrame(np.reshape(np.arange(25.0), (5, 5)))\n original.index.name = "index"\n with tm.ensure_clean() as path:\n # should get a warning for that format.\n with tm.assert_produces_warning(InvalidColumnName):\n original.to_stata(path)\n\n written_and_read_again = self.read_dta(path)\n\n written_and_read_again = written_and_read_again.set_index("index")\n columns = list(written_and_read_again.columns)\n convert_col_name = lambda x: int(x[1])\n written_and_read_again.columns = map(convert_col_name, columns)\n\n expected = original.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(expected, written_and_read_again)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_nan_to_missing_value(self, version):\n s1 = Series(np.arange(4.0), dtype=np.float32)\n s2 = Series(np.arange(4.0), dtype=np.float64)\n s1[::2] = np.nan\n s2[1::2] = np.nan\n original = DataFrame({"s1": s1, "s2": s2})\n original.index.name = "index"\n\n with tm.ensure_clean() as path:\n original.to_stata(path, version=version)\n written_and_read_again = self.read_dta(path)\n\n written_and_read_again = written_and_read_again.set_index("index")\n expected = original.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(written_and_read_again, expected)\n\n def test_no_index(self):\n columns = ["x", "y"]\n original = DataFrame(np.reshape(np.arange(10.0), (5, 2)), columns=columns)\n original.index.name = "index_not_written"\n with tm.ensure_clean() as path:\n original.to_stata(path, write_index=False)\n written_and_read_again = self.read_dta(path)\n with pytest.raises(KeyError, match=original.index.name):\n written_and_read_again["index_not_written"]\n\n def test_string_no_dates(self):\n s1 = Series(["a", "A longer string"])\n s2 = Series([1.0, 2.0], dtype=np.float64)\n original = DataFrame({"s1": s1, "s2": s2})\n original.index.name = "index"\n with tm.ensure_clean() as path:\n original.to_stata(path)\n written_and_read_again = self.read_dta(path)\n\n expected = original.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)\n\n def test_large_value_conversion(self):\n s0 = Series([1, 99], dtype=np.int8)\n s1 = Series([1, 127], dtype=np.int8)\n s2 = Series([1, 2**15 - 1], dtype=np.int16)\n s3 = Series([1, 2**63 - 1], dtype=np.int64)\n original = DataFrame({"s0": s0, "s1": s1, "s2": s2, "s3": s3})\n original.index.name = "index"\n with tm.ensure_clean() as path:\n with tm.assert_produces_warning(PossiblePrecisionLoss):\n original.to_stata(path)\n\n written_and_read_again = self.read_dta(path)\n\n modified = original.copy()\n modified["s1"] = Series(modified["s1"], dtype=np.int16)\n modified["s2"] = Series(modified["s2"], dtype=np.int32)\n modified["s3"] = Series(modified["s3"], dtype=np.float64)\n modified.index = original.index.astype(np.int32)\n tm.assert_frame_equal(written_and_read_again.set_index("index"), modified)\n\n def test_dates_invalid_column(self):\n original = DataFrame([datetime(2006, 11, 19, 23, 13, 20)])\n original.index.name = "index"\n with tm.ensure_clean() as path:\n with tm.assert_produces_warning(InvalidColumnName):\n original.to_stata(path, convert_dates={0: "tc"})\n\n written_and_read_again = self.read_dta(path)\n\n modified = original.copy()\n modified.columns = ["_0"]\n modified.index = original.index.astype(np.int32)\n tm.assert_frame_equal(written_and_read_again.set_index("index"), modified)\n\n def test_105(self, datapath):\n # Data obtained from:\n # http://go.worldbank.org/ZXY29PVJ21\n dpath = datapath("io", "data", "stata", "S4_EDUC1.dta")\n df = read_stata(dpath)\n df0 = [[1, 1, 3, -2], [2, 1, 2, -2], [4, 1, 1, -2]]\n df0 = DataFrame(df0)\n df0.columns = ["clustnum", "pri_schl", "psch_num", "psch_dis"]\n df0["clustnum"] = df0["clustnum"].astype(np.int16)\n df0["pri_schl"] = df0["pri_schl"].astype(np.int8)\n df0["psch_num"] = df0["psch_num"].astype(np.int8)\n df0["psch_dis"] = df0["psch_dis"].astype(np.float32)\n tm.assert_frame_equal(df.head(3), df0)\n\n def test_value_labels_old_format(self, datapath):\n # GH 19417\n #\n # Test that value_labels() returns an empty dict if the file format\n # predates supporting value labels.\n dpath = datapath("io", "data", "stata", "S4_EDUC1.dta")\n with StataReader(dpath) as reader:\n assert reader.value_labels() == {}\n\n def test_date_export_formats(self):\n columns = ["tc", "td", "tw", "tm", "tq", "th", "ty"]\n conversions = {c: c for c in columns}\n data = [datetime(2006, 11, 20, 23, 13, 20)] * len(columns)\n original = DataFrame([data], columns=columns)\n original.index.name = "index"\n expected_values = [\n datetime(2006, 11, 20, 23, 13, 20), # Time\n datetime(2006, 11, 20), # Day\n datetime(2006, 11, 19), # Week\n datetime(2006, 11, 1), # Month\n datetime(2006, 10, 1), # Quarter year\n datetime(2006, 7, 1), # Half year\n datetime(2006, 1, 1),\n ] # Year\n\n expected = DataFrame(\n [expected_values],\n index=pd.Index([0], dtype=np.int32, name="index"),\n columns=columns,\n )\n\n with tm.ensure_clean() as path:\n original.to_stata(path, convert_dates=conversions)\n written_and_read_again = self.read_dta(path)\n\n tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)\n\n def test_write_missing_strings(self):\n original = DataFrame([["1"], [None]], columns=["foo"])\n\n expected = DataFrame(\n [["1"], [""]],\n index=pd.Index([0, 1], dtype=np.int32, name="index"),\n columns=["foo"],\n )\n\n with tm.ensure_clean() as path:\n original.to_stata(path)\n written_and_read_again = self.read_dta(path)\n\n tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n @pytest.mark.parametrize("byteorder", [">", "<"])\n def test_bool_uint(self, byteorder, version):\n s0 = Series([0, 1, True], dtype=np.bool_)\n s1 = Series([0, 1, 100], dtype=np.uint8)\n s2 = Series([0, 1, 255], dtype=np.uint8)\n s3 = Series([0, 1, 2**15 - 100], dtype=np.uint16)\n s4 = Series([0, 1, 2**16 - 1], dtype=np.uint16)\n s5 = Series([0, 1, 2**31 - 100], dtype=np.uint32)\n s6 = Series([0, 1, 2**32 - 1], dtype=np.uint32)\n\n original = DataFrame(\n {"s0": s0, "s1": s1, "s2": s2, "s3": s3, "s4": s4, "s5": s5, "s6": s6}\n )\n original.index.name = "index"\n expected = original.copy()\n expected.index = original.index.astype(np.int32)\n expected_types = (\n np.int8,\n np.int8,\n np.int16,\n np.int16,\n np.int32,\n np.int32,\n np.float64,\n )\n for c, t in zip(expected.columns, expected_types):\n expected[c] = expected[c].astype(t)\n\n with tm.ensure_clean() as path:\n original.to_stata(path, byteorder=byteorder, version=version)\n written_and_read_again = self.read_dta(path)\n\n written_and_read_again = written_and_read_again.set_index("index")\n tm.assert_frame_equal(written_and_read_again, expected)\n\n def test_variable_labels(self, datapath):\n with StataReader(datapath("io", "data", "stata", "stata7_115.dta")) as rdr:\n sr_115 = rdr.variable_labels()\n with StataReader(datapath("io", "data", "stata", "stata7_117.dta")) as rdr:\n sr_117 = rdr.variable_labels()\n keys = ("var1", "var2", "var3")\n labels = ("label1", "label2", "label3")\n for k, v in sr_115.items():\n assert k in sr_117\n assert v == sr_117[k]\n assert k in keys\n assert v in labels\n\n def test_minimal_size_col(self):\n str_lens = (1, 100, 244)\n s = {}\n for str_len in str_lens:\n s["s" + str(str_len)] = Series(\n ["a" * str_len, "b" * str_len, "c" * str_len]\n )\n original = DataFrame(s)\n with tm.ensure_clean() as path:\n original.to_stata(path, write_index=False)\n\n with StataReader(path) as sr:\n sr._ensure_open() # The `_*list` variables are initialized here\n for variable, fmt, typ in zip(sr._varlist, sr._fmtlist, sr._typlist):\n assert int(variable[1:]) == int(fmt[1:-1])\n assert int(variable[1:]) == typ\n\n def test_excessively_long_string(self):\n str_lens = (1, 244, 500)\n s = {}\n for str_len in str_lens:\n s["s" + str(str_len)] = Series(\n ["a" * str_len, "b" * str_len, "c" * str_len]\n )\n original = DataFrame(s)\n msg = (\n r"Fixed width strings in Stata \.dta files are limited to 244 "\n r"\(or fewer\)\ncharacters\. Column 's500' does not satisfy "\n r"this restriction\. Use the\n'version=117' parameter to write "\n r"the newer \(Stata 13 and later\) format\."\n )\n with pytest.raises(ValueError, match=msg):\n with tm.ensure_clean() as path:\n original.to_stata(path)\n\n def test_missing_value_generator(self):\n types = ("b", "h", "l")\n df = DataFrame([[0.0]], columns=["float_"])\n with tm.ensure_clean() as path:\n df.to_stata(path)\n with StataReader(path) as rdr:\n valid_range = rdr.VALID_RANGE\n expected_values = ["." + chr(97 + i) for i in range(26)]\n expected_values.insert(0, ".")\n for t in types:\n offset = valid_range[t][1]\n for i in range(27):\n val = StataMissingValue(offset + 1 + i)\n assert val.string == expected_values[i]\n\n # Test extremes for floats\n val = StataMissingValue(struct.unpack("<f", b"\x00\x00\x00\x7f")[0])\n assert val.string == "."\n val = StataMissingValue(struct.unpack("<f", b"\x00\xd0\x00\x7f")[0])\n assert val.string == ".z"\n\n # Test extremes for floats\n val = StataMissingValue(\n struct.unpack("<d", b"\x00\x00\x00\x00\x00\x00\xe0\x7f")[0]\n )\n assert val.string == "."\n val = StataMissingValue(\n struct.unpack("<d", b"\x00\x00\x00\x00\x00\x1a\xe0\x7f")[0]\n )\n assert val.string == ".z"\n\n @pytest.mark.parametrize("file", ["stata8_113", "stata8_115", "stata8_117"])\n def test_missing_value_conversion(self, file, datapath):\n columns = ["int8_", "int16_", "int32_", "float32_", "float64_"]\n smv = StataMissingValue(101)\n keys = sorted(smv.MISSING_VALUES.keys())\n data = []\n for i in range(27):\n row = [StataMissingValue(keys[i + (j * 27)]) for j in range(5)]\n data.append(row)\n expected = DataFrame(data, columns=columns)\n\n parsed = read_stata(\n datapath("io", "data", "stata", f"{file}.dta"), convert_missing=True\n )\n tm.assert_frame_equal(parsed, expected)\n\n def test_big_dates(self, datapath):\n yr = [1960, 2000, 9999, 100, 2262, 1677]\n mo = [1, 1, 12, 1, 4, 9]\n dd = [1, 1, 31, 1, 22, 23]\n hr = [0, 0, 23, 0, 0, 0]\n mm = [0, 0, 59, 0, 0, 0]\n ss = [0, 0, 59, 0, 0, 0]\n expected = []\n for year, month, day, hour, minute, second in zip(yr, mo, dd, hr, mm, ss):\n row = []\n for j in range(7):\n if j == 0:\n row.append(datetime(year, month, day, hour, minute, second))\n elif j == 6:\n row.append(datetime(year, 1, 1))\n else:\n row.append(datetime(year, month, day))\n expected.append(row)\n expected.append([pd.NaT] * 7)\n columns = [\n "date_tc",\n "date_td",\n "date_tw",\n "date_tm",\n "date_tq",\n "date_th",\n "date_ty",\n ]\n\n # Fixes for weekly, quarterly,half,year\n expected[2][2] = datetime(9999, 12, 24)\n expected[2][3] = datetime(9999, 12, 1)\n expected[2][4] = datetime(9999, 10, 1)\n expected[2][5] = datetime(9999, 7, 1)\n expected[4][2] = datetime(2262, 4, 16)\n expected[4][3] = expected[4][4] = datetime(2262, 4, 1)\n expected[4][5] = expected[4][6] = datetime(2262, 1, 1)\n expected[5][2] = expected[5][3] = expected[5][4] = datetime(1677, 10, 1)\n expected[5][5] = expected[5][6] = datetime(1678, 1, 1)\n\n expected = DataFrame(expected, columns=columns, dtype=object)\n parsed_115 = read_stata(datapath("io", "data", "stata", "stata9_115.dta"))\n parsed_117 = read_stata(datapath("io", "data", "stata", "stata9_117.dta"))\n tm.assert_frame_equal(expected, parsed_115, check_datetimelike_compat=True)\n tm.assert_frame_equal(expected, parsed_117, check_datetimelike_compat=True)\n\n date_conversion = {c: c[-2:] for c in columns}\n # {c : c[-2:] for c in columns}\n with tm.ensure_clean() as path:\n expected.index.name = "index"\n expected.to_stata(path, convert_dates=date_conversion)\n written_and_read_again = self.read_dta(path)\n\n tm.assert_frame_equal(\n written_and_read_again.set_index("index"),\n expected.set_index(expected.index.astype(np.int32)),\n check_datetimelike_compat=True,\n )\n\n def test_dtype_conversion(self, datapath):\n expected = self.read_csv(datapath("io", "data", "stata", "stata6.csv"))\n expected["byte_"] = expected["byte_"].astype(np.int8)\n expected["int_"] = expected["int_"].astype(np.int16)\n expected["long_"] = expected["long_"].astype(np.int32)\n expected["float_"] = expected["float_"].astype(np.float32)\n expected["double_"] = expected["double_"].astype(np.float64)\n expected["date_td"] = expected["date_td"].apply(\n datetime.strptime, args=("%Y-%m-%d",)\n )\n\n no_conversion = read_stata(\n datapath("io", "data", "stata", "stata6_117.dta"), convert_dates=True\n )\n tm.assert_frame_equal(expected, no_conversion)\n\n conversion = read_stata(\n datapath("io", "data", "stata", "stata6_117.dta"),\n convert_dates=True,\n preserve_dtypes=False,\n )\n\n # read_csv types are the same\n expected = self.read_csv(datapath("io", "data", "stata", "stata6.csv"))\n expected["date_td"] = expected["date_td"].apply(\n datetime.strptime, args=("%Y-%m-%d",)\n )\n\n tm.assert_frame_equal(expected, conversion)\n\n def test_drop_column(self, datapath):\n expected = self.read_csv(datapath("io", "data", "stata", "stata6.csv"))\n expected["byte_"] = expected["byte_"].astype(np.int8)\n expected["int_"] = expected["int_"].astype(np.int16)\n expected["long_"] = expected["long_"].astype(np.int32)\n expected["float_"] = expected["float_"].astype(np.float32)\n expected["double_"] = expected["double_"].astype(np.float64)\n expected["date_td"] = expected["date_td"].apply(\n datetime.strptime, args=("%Y-%m-%d",)\n )\n\n columns = ["byte_", "int_", "long_"]\n expected = expected[columns]\n dropped = read_stata(\n datapath("io", "data", "stata", "stata6_117.dta"),\n convert_dates=True,\n columns=columns,\n )\n\n tm.assert_frame_equal(expected, dropped)\n\n # See PR 10757\n columns = ["int_", "long_", "byte_"]\n expected = expected[columns]\n reordered = read_stata(\n datapath("io", "data", "stata", "stata6_117.dta"),\n convert_dates=True,\n columns=columns,\n )\n tm.assert_frame_equal(expected, reordered)\n\n msg = "columns contains duplicate entries"\n with pytest.raises(ValueError, match=msg):\n columns = ["byte_", "byte_"]\n read_stata(\n datapath("io", "data", "stata", "stata6_117.dta"),\n convert_dates=True,\n columns=columns,\n )\n\n msg = "The following columns were not found in the Stata data set: not_found"\n with pytest.raises(ValueError, match=msg):\n columns = ["byte_", "int_", "long_", "not_found"]\n read_stata(\n datapath("io", "data", "stata", "stata6_117.dta"),\n convert_dates=True,\n columns=columns,\n )\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n @pytest.mark.filterwarnings(\n "ignore:\\nStata value:pandas.io.stata.ValueLabelTypeMismatch"\n )\n def test_categorical_writing(self, version):\n original = DataFrame.from_records(\n [\n ["one", "ten", "one", "one", "one", 1],\n ["two", "nine", "two", "two", "two", 2],\n ["three", "eight", "three", "three", "three", 3],\n ["four", "seven", 4, "four", "four", 4],\n ["five", "six", 5, np.nan, "five", 5],\n ["six", "five", 6, np.nan, "six", 6],\n ["seven", "four", 7, np.nan, "seven", 7],\n ["eight", "three", 8, np.nan, "eight", 8],\n ["nine", "two", 9, np.nan, "nine", 9],\n ["ten", "one", "ten", np.nan, "ten", 10],\n ],\n columns=[\n "fully_labeled",\n "fully_labeled2",\n "incompletely_labeled",\n "labeled_with_missings",\n "float_labelled",\n "unlabeled",\n ],\n )\n expected = original.copy()\n\n # these are all categoricals\n original = pd.concat(\n [original[col].astype("category") for col in original], axis=1\n )\n expected.index = expected.index.set_names("index").astype(np.int32)\n\n expected["incompletely_labeled"] = expected["incompletely_labeled"].apply(str)\n expected["unlabeled"] = expected["unlabeled"].apply(str)\n for col in expected:\n orig = expected[col].copy()\n\n cat = orig.astype("category")._values\n cat = cat.as_ordered()\n if col == "unlabeled":\n cat = cat.set_categories(orig, ordered=True)\n\n cat.categories.rename(None, inplace=True)\n\n expected[col] = cat\n\n with tm.ensure_clean() as path:\n original.to_stata(path, version=version)\n written_and_read_again = self.read_dta(path)\n\n res = written_and_read_again.set_index("index")\n tm.assert_frame_equal(res, expected)\n\n def test_categorical_warnings_and_errors(self):\n # Warning for non-string labels\n # Error for labels too long\n original = DataFrame.from_records(\n [["a" * 10000], ["b" * 10000], ["c" * 10000], ["d" * 10000]],\n columns=["Too_long"],\n )\n\n original = pd.concat(\n [original[col].astype("category") for col in original], axis=1\n )\n with tm.ensure_clean() as path:\n msg = (\n "Stata value labels for a single variable must have "\n r"a combined length less than 32,000 characters\."\n )\n with pytest.raises(ValueError, match=msg):\n original.to_stata(path)\n\n original = DataFrame.from_records(\n [["a"], ["b"], ["c"], ["d"], [1]], columns=["Too_long"]\n )\n original = pd.concat(\n [original[col].astype("category") for col in original], axis=1\n )\n\n with tm.assert_produces_warning(ValueLabelTypeMismatch):\n original.to_stata(path)\n # should get a warning for mixed content\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_categorical_with_stata_missing_values(self, version):\n values = [["a" + str(i)] for i in range(120)]\n values.append([np.nan])\n original = DataFrame.from_records(values, columns=["many_labels"])\n original = pd.concat(\n [original[col].astype("category") for col in original], axis=1\n )\n original.index.name = "index"\n with tm.ensure_clean() as path:\n original.to_stata(path, version=version)\n written_and_read_again = self.read_dta(path)\n\n res = written_and_read_again.set_index("index")\n\n expected = original.copy()\n for col in expected:\n cat = expected[col]._values\n new_cats = cat.remove_unused_categories().categories\n cat = cat.set_categories(new_cats, ordered=True)\n expected[col] = cat\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(res, expected)\n\n @pytest.mark.parametrize("file", ["stata10_115", "stata10_117"])\n def test_categorical_order(self, file, datapath):\n # Directly construct using expected codes\n # Format is is_cat, col_name, labels (in order), underlying data\n expected = [\n (True, "ordered", ["a", "b", "c", "d", "e"], np.arange(5)),\n (True, "reverse", ["a", "b", "c", "d", "e"], np.arange(5)[::-1]),\n (True, "noorder", ["a", "b", "c", "d", "e"], np.array([2, 1, 4, 0, 3])),\n (True, "floating", ["a", "b", "c", "d", "e"], np.arange(0, 5)),\n (True, "float_missing", ["a", "d", "e"], np.array([0, 1, 2, -1, -1])),\n (False, "nolabel", [1.0, 2.0, 3.0, 4.0, 5.0], np.arange(5)),\n (True, "int32_mixed", ["d", 2, "e", "b", "a"], np.arange(5)),\n ]\n cols = []\n for is_cat, col, labels, codes in expected:\n if is_cat:\n cols.append(\n (col, pd.Categorical.from_codes(codes, labels, ordered=True))\n )\n else:\n cols.append((col, Series(labels, dtype=np.float32)))\n expected = DataFrame.from_dict(dict(cols))\n\n # Read with and with out categoricals, ensure order is identical\n file = datapath("io", "data", "stata", f"{file}.dta")\n parsed = read_stata(file)\n tm.assert_frame_equal(expected, parsed)\n\n # Check identity of codes\n for col in expected:\n if isinstance(expected[col].dtype, CategoricalDtype):\n tm.assert_series_equal(expected[col].cat.codes, parsed[col].cat.codes)\n tm.assert_index_equal(\n expected[col].cat.categories, parsed[col].cat.categories\n )\n\n @pytest.mark.parametrize("file", ["stata11_115", "stata11_117"])\n def test_categorical_sorting(self, file, datapath):\n parsed = read_stata(datapath("io", "data", "stata", f"{file}.dta"))\n\n # Sort based on codes, not strings\n parsed = parsed.sort_values("srh", na_position="first")\n\n # Don't sort index\n parsed.index = pd.RangeIndex(len(parsed))\n codes = [-1, -1, 0, 1, 1, 1, 2, 2, 3, 4]\n categories = ["Poor", "Fair", "Good", "Very good", "Excellent"]\n cat = pd.Categorical.from_codes(\n codes=codes, categories=categories, ordered=True\n )\n expected = Series(cat, name="srh")\n tm.assert_series_equal(expected, parsed["srh"])\n\n @pytest.mark.parametrize("file", ["stata10_115", "stata10_117"])\n def test_categorical_ordering(self, file, datapath):\n file = datapath("io", "data", "stata", f"{file}.dta")\n parsed = read_stata(file)\n\n parsed_unordered = read_stata(file, order_categoricals=False)\n for col in parsed:\n if not isinstance(parsed[col].dtype, CategoricalDtype):\n continue\n assert parsed[col].cat.ordered\n assert not parsed_unordered[col].cat.ordered\n\n @pytest.mark.filterwarnings("ignore::UserWarning")\n @pytest.mark.parametrize(\n "file",\n [\n "stata1_117",\n "stata2_117",\n "stata3_117",\n "stata4_117",\n "stata5_117",\n "stata6_117",\n "stata7_117",\n "stata8_117",\n "stata9_117",\n "stata10_117",\n "stata11_117",\n ],\n )\n @pytest.mark.parametrize("chunksize", [1, 2])\n @pytest.mark.parametrize("convert_categoricals", [False, True])\n @pytest.mark.parametrize("convert_dates", [False, True])\n def test_read_chunks_117(\n self, file, chunksize, convert_categoricals, convert_dates, datapath\n ):\n fname = datapath("io", "data", "stata", f"{file}.dta")\n\n parsed = read_stata(\n fname,\n convert_categoricals=convert_categoricals,\n convert_dates=convert_dates,\n )\n with read_stata(\n fname,\n iterator=True,\n convert_categoricals=convert_categoricals,\n convert_dates=convert_dates,\n ) as itr:\n pos = 0\n for j in range(5):\n try:\n chunk = itr.read(chunksize)\n except StopIteration:\n break\n from_frame = parsed.iloc[pos : pos + chunksize, :].copy()\n from_frame = self._convert_categorical(from_frame)\n tm.assert_frame_equal(\n from_frame, chunk, check_dtype=False, check_datetimelike_compat=True\n )\n pos += chunksize\n\n @staticmethod\n def _convert_categorical(from_frame: DataFrame) -> DataFrame:\n """\n Emulate the categorical casting behavior we expect from roundtripping.\n """\n for col in from_frame:\n ser = from_frame[col]\n if isinstance(ser.dtype, CategoricalDtype):\n cat = ser._values.remove_unused_categories()\n if cat.categories.dtype == object:\n categories = pd.Index._with_infer(cat.categories._values)\n cat = cat.set_categories(categories)\n elif cat.categories.dtype == "string" and len(cat.categories) == 0:\n # if the read categories are empty, it comes back as object dtype\n categories = cat.categories.astype(object)\n cat = cat.set_categories(categories)\n from_frame[col] = cat\n return from_frame\n\n def test_iterator(self, datapath):\n fname = datapath("io", "data", "stata", "stata3_117.dta")\n\n parsed = read_stata(fname)\n\n with read_stata(fname, iterator=True) as itr:\n chunk = itr.read(5)\n tm.assert_frame_equal(parsed.iloc[0:5, :], chunk)\n\n with read_stata(fname, chunksize=5) as itr:\n chunk = list(itr)\n tm.assert_frame_equal(parsed.iloc[0:5, :], chunk[0])\n\n with read_stata(fname, iterator=True) as itr:\n chunk = itr.get_chunk(5)\n tm.assert_frame_equal(parsed.iloc[0:5, :], chunk)\n\n with read_stata(fname, chunksize=5) as itr:\n chunk = itr.get_chunk()\n tm.assert_frame_equal(parsed.iloc[0:5, :], chunk)\n\n # GH12153\n with read_stata(fname, chunksize=4) as itr:\n from_chunks = pd.concat(itr)\n tm.assert_frame_equal(parsed, from_chunks)\n\n @pytest.mark.filterwarnings("ignore::UserWarning")\n @pytest.mark.parametrize(\n "file",\n [\n "stata2_115",\n "stata3_115",\n "stata4_115",\n "stata5_115",\n "stata6_115",\n "stata7_115",\n "stata8_115",\n "stata9_115",\n "stata10_115",\n "stata11_115",\n ],\n )\n @pytest.mark.parametrize("chunksize", [1, 2])\n @pytest.mark.parametrize("convert_categoricals", [False, True])\n @pytest.mark.parametrize("convert_dates", [False, True])\n def test_read_chunks_115(\n self, file, chunksize, convert_categoricals, convert_dates, datapath\n ):\n fname = datapath("io", "data", "stata", f"{file}.dta")\n\n # Read the whole file\n parsed = read_stata(\n fname,\n convert_categoricals=convert_categoricals,\n convert_dates=convert_dates,\n )\n\n # Compare to what we get when reading by chunk\n with read_stata(\n fname,\n iterator=True,\n convert_dates=convert_dates,\n convert_categoricals=convert_categoricals,\n ) as itr:\n pos = 0\n for j in range(5):\n try:\n chunk = itr.read(chunksize)\n except StopIteration:\n break\n from_frame = parsed.iloc[pos : pos + chunksize, :].copy()\n from_frame = self._convert_categorical(from_frame)\n tm.assert_frame_equal(\n from_frame, chunk, check_dtype=False, check_datetimelike_compat=True\n )\n pos += chunksize\n\n def test_read_chunks_columns(self, datapath):\n fname = datapath("io", "data", "stata", "stata3_117.dta")\n columns = ["quarter", "cpi", "m1"]\n chunksize = 2\n\n parsed = read_stata(fname, columns=columns)\n with read_stata(fname, iterator=True) as itr:\n pos = 0\n for j in range(5):\n chunk = itr.read(chunksize, columns=columns)\n if chunk is None:\n break\n from_frame = parsed.iloc[pos : pos + chunksize, :]\n tm.assert_frame_equal(from_frame, chunk, check_dtype=False)\n pos += chunksize\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_write_variable_labels(self, version, mixed_frame):\n # GH 13631, add support for writing variable labels\n mixed_frame.index.name = "index"\n variable_labels = {"a": "City Rank", "b": "City Exponent", "c": "City"}\n with tm.ensure_clean() as path:\n mixed_frame.to_stata(path, variable_labels=variable_labels, version=version)\n with StataReader(path) as sr:\n read_labels = sr.variable_labels()\n expected_labels = {\n "index": "",\n "a": "City Rank",\n "b": "City Exponent",\n "c": "City",\n }\n assert read_labels == expected_labels\n\n variable_labels["index"] = "The Index"\n with tm.ensure_clean() as path:\n mixed_frame.to_stata(path, variable_labels=variable_labels, version=version)\n with StataReader(path) as sr:\n read_labels = sr.variable_labels()\n assert read_labels == variable_labels\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_invalid_variable_labels(self, version, mixed_frame):\n mixed_frame.index.name = "index"\n variable_labels = {"a": "very long" * 10, "b": "City Exponent", "c": "City"}\n with tm.ensure_clean() as path:\n msg = "Variable labels must be 80 characters or fewer"\n with pytest.raises(ValueError, match=msg):\n mixed_frame.to_stata(\n path, variable_labels=variable_labels, version=version\n )\n\n @pytest.mark.parametrize("version", [114, 117])\n def test_invalid_variable_label_encoding(self, version, mixed_frame):\n mixed_frame.index.name = "index"\n variable_labels = {"a": "very long" * 10, "b": "City Exponent", "c": "City"}\n variable_labels["a"] = "invalid character Œ"\n with tm.ensure_clean() as path:\n with pytest.raises(\n ValueError, match="Variable labels must contain only characters"\n ):\n mixed_frame.to_stata(\n path, variable_labels=variable_labels, version=version\n )\n\n def test_write_variable_label_errors(self, mixed_frame):\n values = ["\u03A1", "\u0391", "\u039D", "\u0394", "\u0391", "\u03A3"]\n\n variable_labels_utf8 = {\n "a": "City Rank",\n "b": "City Exponent",\n "c": "".join(values),\n }\n\n msg = (\n "Variable labels must contain only characters that can be "\n "encoded in Latin-1"\n )\n with pytest.raises(ValueError, match=msg):\n with tm.ensure_clean() as path:\n mixed_frame.to_stata(path, variable_labels=variable_labels_utf8)\n\n variable_labels_long = {\n "a": "City Rank",\n "b": "City Exponent",\n "c": "A very, very, very long variable label "\n "that is too long for Stata which means "\n "that it has more than 80 characters",\n }\n\n msg = "Variable labels must be 80 characters or fewer"\n with pytest.raises(ValueError, match=msg):\n with tm.ensure_clean() as path:\n mixed_frame.to_stata(path, variable_labels=variable_labels_long)\n\n def test_default_date_conversion(self):\n # GH 12259\n dates = [\n dt.datetime(1999, 12, 31, 12, 12, 12, 12000),\n dt.datetime(2012, 12, 21, 12, 21, 12, 21000),\n dt.datetime(1776, 7, 4, 7, 4, 7, 4000),\n ]\n original = DataFrame(\n {\n "nums": [1.0, 2.0, 3.0],\n "strs": ["apple", "banana", "cherry"],\n "dates": dates,\n }\n )\n\n with tm.ensure_clean() as path:\n original.to_stata(path, write_index=False)\n reread = read_stata(path, convert_dates=True)\n tm.assert_frame_equal(original, reread)\n\n original.to_stata(path, write_index=False, convert_dates={"dates": "tc"})\n direct = read_stata(path, convert_dates=True)\n tm.assert_frame_equal(reread, direct)\n\n dates_idx = original.columns.tolist().index("dates")\n original.to_stata(path, write_index=False, convert_dates={dates_idx: "tc"})\n direct = read_stata(path, convert_dates=True)\n tm.assert_frame_equal(reread, direct)\n\n def test_unsupported_type(self):\n original = DataFrame({"a": [1 + 2j, 2 + 4j]})\n\n msg = "Data type complex128 not supported"\n with pytest.raises(NotImplementedError, match=msg):\n with tm.ensure_clean() as path:\n original.to_stata(path)\n\n def test_unsupported_datetype(self):\n dates = [\n dt.datetime(1999, 12, 31, 12, 12, 12, 12000),\n dt.datetime(2012, 12, 21, 12, 21, 12, 21000),\n dt.datetime(1776, 7, 4, 7, 4, 7, 4000),\n ]\n original = DataFrame(\n {\n "nums": [1.0, 2.0, 3.0],\n "strs": ["apple", "banana", "cherry"],\n "dates": dates,\n }\n )\n\n msg = "Format %tC not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n with tm.ensure_clean() as path:\n original.to_stata(path, convert_dates={"dates": "tC"})\n\n dates = pd.date_range("1-1-1990", periods=3, tz="Asia/Hong_Kong")\n original = DataFrame(\n {\n "nums": [1.0, 2.0, 3.0],\n "strs": ["apple", "banana", "cherry"],\n "dates": dates,\n }\n )\n with pytest.raises(NotImplementedError, match="Data type datetime64"):\n with tm.ensure_clean() as path:\n original.to_stata(path)\n\n def test_repeated_column_labels(self, datapath):\n # GH 13923, 25772\n msg = """\nValue labels for column ethnicsn are not unique. These cannot be converted to\npandas categoricals.\n\nEither read the file with `convert_categoricals` set to False or use the\nlow level interface in `StataReader` to separately read the values and the\nvalue_labels.\n\nThe repeated labels are:\n-+\nwolof\n"""\n with pytest.raises(ValueError, match=msg):\n read_stata(\n datapath("io", "data", "stata", "stata15.dta"),\n convert_categoricals=True,\n )\n\n def test_stata_111(self, datapath):\n # 111 is an old version but still used by current versions of\n # SAS when exporting to Stata format. We do not know of any\n # on-line documentation for this version.\n df = read_stata(datapath("io", "data", "stata", "stata7_111.dta"))\n original = DataFrame(\n {\n "y": [1, 1, 1, 1, 1, 0, 0, np.nan, 0, 0],\n "x": [1, 2, 1, 3, np.nan, 4, 3, 5, 1, 6],\n "w": [2, np.nan, 5, 2, 4, 4, 3, 1, 2, 3],\n "z": ["a", "b", "c", "d", "e", "", "g", "h", "i", "j"],\n }\n )\n original = original[["y", "x", "w", "z"]]\n tm.assert_frame_equal(original, df)\n\n def test_out_of_range_double(self):\n # GH 14618\n df = DataFrame(\n {\n "ColumnOk": [0.0, np.finfo(np.double).eps, 4.49423283715579e307],\n "ColumnTooBig": [0.0, np.finfo(np.double).eps, np.finfo(np.double).max],\n }\n )\n msg = (\n r"Column ColumnTooBig has a maximum value \(.+\) outside the range "\n r"supported by Stata \(.+\)"\n )\n with pytest.raises(ValueError, match=msg):\n with tm.ensure_clean() as path:\n df.to_stata(path)\n\n def test_out_of_range_float(self):\n original = DataFrame(\n {\n "ColumnOk": [\n 0.0,\n np.finfo(np.float32).eps,\n np.finfo(np.float32).max / 10.0,\n ],\n "ColumnTooBig": [\n 0.0,\n np.finfo(np.float32).eps,\n np.finfo(np.float32).max,\n ],\n }\n )\n original.index.name = "index"\n for col in original:\n original[col] = original[col].astype(np.float32)\n\n with tm.ensure_clean() as path:\n original.to_stata(path)\n reread = read_stata(path)\n\n original["ColumnTooBig"] = original["ColumnTooBig"].astype(np.float64)\n expected = original.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(reread.set_index("index"), expected)\n\n @pytest.mark.parametrize("infval", [np.inf, -np.inf])\n def test_inf(self, infval):\n # GH 45350\n df = DataFrame({"WithoutInf": [0.0, 1.0], "WithInf": [2.0, infval]})\n msg = (\n "Column WithInf contains infinity or -infinity"\n "which is outside the range supported by Stata."\n )\n with pytest.raises(ValueError, match=msg):\n with tm.ensure_clean() as path:\n df.to_stata(path)\n\n def test_path_pathlib(self):\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n df.index.name = "index"\n reader = lambda x: read_stata(x).set_index("index")\n result = tm.round_trip_pathlib(df.to_stata, reader)\n tm.assert_frame_equal(df, result)\n\n def test_pickle_path_localpath(self):\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n df.index.name = "index"\n reader = lambda x: read_stata(x).set_index("index")\n result = tm.round_trip_localpath(df.to_stata, reader)\n tm.assert_frame_equal(df, result)\n\n @pytest.mark.parametrize("write_index", [True, False])\n def test_value_labels_iterator(self, write_index):\n # GH 16923\n d = {"A": ["B", "E", "C", "A", "E"]}\n df = DataFrame(data=d)\n df["A"] = df["A"].astype("category")\n with tm.ensure_clean() as path:\n df.to_stata(path, write_index=write_index)\n\n with read_stata(path, iterator=True) as dta_iter:\n value_labels = dta_iter.value_labels()\n assert value_labels == {"A": {0: "A", 1: "B", 2: "C", 3: "E"}}\n\n def test_set_index(self):\n # GH 17328\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n df.index.name = "index"\n with tm.ensure_clean() as path:\n df.to_stata(path)\n reread = read_stata(path, index_col="index")\n tm.assert_frame_equal(df, reread)\n\n @pytest.mark.parametrize(\n "column", ["ms", "day", "week", "month", "qtr", "half", "yr"]\n )\n def test_date_parsing_ignores_format_details(self, column, datapath):\n # GH 17797\n #\n # Test that display formats are ignored when determining if a numeric\n # column is a date value.\n #\n # All date types are stored as numbers and format associated with the\n # column denotes both the type of the date and the display format.\n #\n # STATA supports 9 date types which each have distinct units. We test 7\n # of the 9 types, ignoring %tC and %tb. %tC is a variant of %tc that\n # accounts for leap seconds and %tb relies on STATAs business calendar.\n df = read_stata(datapath("io", "data", "stata", "stata13_dates.dta"))\n unformatted = df.loc[0, column]\n formatted = df.loc[0, column + "_fmt"]\n assert unformatted == formatted\n\n def test_writer_117(self, using_infer_string):\n original = DataFrame(\n data=[\n [\n "string",\n "object",\n 1,\n 1,\n 1,\n 1.1,\n 1.1,\n np.datetime64("2003-12-25"),\n "a",\n "a" * 2045,\n "a" * 5000,\n "a",\n ],\n [\n "string-1",\n "object-1",\n 1,\n 1,\n 1,\n 1.1,\n 1.1,\n np.datetime64("2003-12-26"),\n "b",\n "b" * 2045,\n "",\n "",\n ],\n ],\n columns=[\n "string",\n "object",\n "int8",\n "int16",\n "int32",\n "float32",\n "float64",\n "datetime",\n "s1",\n "s2045",\n "srtl",\n "forced_strl",\n ],\n )\n original["object"] = Series(original["object"], dtype=object)\n original["int8"] = Series(original["int8"], dtype=np.int8)\n original["int16"] = Series(original["int16"], dtype=np.int16)\n original["int32"] = original["int32"].astype(np.int32)\n original["float32"] = Series(original["float32"], dtype=np.float32)\n original.index.name = "index"\n original.index = original.index.astype(np.int32)\n copy = original.copy()\n with tm.ensure_clean() as path:\n original.to_stata(\n path,\n convert_dates={"datetime": "tc"},\n convert_strl=["forced_strl"],\n version=117,\n )\n written_and_read_again = self.read_dta(path)\n\n expected = original[:]\n if using_infer_string:\n # object dtype (with only strings/None) comes back as string dtype\n expected["object"] = expected["object"].astype("str")\n\n tm.assert_frame_equal(\n written_and_read_again.set_index("index"),\n expected,\n )\n tm.assert_frame_equal(original, copy)\n\n def test_convert_strl_name_swap(self):\n original = DataFrame(\n [["a" * 3000, "A", "apple"], ["b" * 1000, "B", "banana"]],\n columns=["long1" * 10, "long", 1],\n )\n original.index.name = "index"\n\n with tm.assert_produces_warning(InvalidColumnName):\n with tm.ensure_clean() as path:\n original.to_stata(path, convert_strl=["long", 1], version=117)\n reread = self.read_dta(path)\n reread = reread.set_index("index")\n reread.columns = original.columns\n tm.assert_frame_equal(reread, original, check_index_type=False)\n\n def test_invalid_date_conversion(self):\n # GH 12259\n dates = [\n dt.datetime(1999, 12, 31, 12, 12, 12, 12000),\n dt.datetime(2012, 12, 21, 12, 21, 12, 21000),\n dt.datetime(1776, 7, 4, 7, 4, 7, 4000),\n ]\n original = DataFrame(\n {\n "nums": [1.0, 2.0, 3.0],\n "strs": ["apple", "banana", "cherry"],\n "dates": dates,\n }\n )\n\n with tm.ensure_clean() as path:\n msg = "convert_dates key must be a column or an integer"\n with pytest.raises(ValueError, match=msg):\n original.to_stata(path, convert_dates={"wrong_name": "tc"})\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_nonfile_writing(self, version):\n # GH 21041\n bio = io.BytesIO()\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n df.index.name = "index"\n with tm.ensure_clean() as path:\n df.to_stata(bio, version=version)\n bio.seek(0)\n with open(path, "wb") as dta:\n dta.write(bio.read())\n reread = read_stata(path, index_col="index")\n tm.assert_frame_equal(df, reread)\n\n def test_gzip_writing(self):\n # writing version 117 requires seek and cannot be used with gzip\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=pd.Index(list("ABCD")),\n index=pd.Index([f"i-{i}" for i in range(30)]),\n )\n df.index.name = "index"\n with tm.ensure_clean() as path:\n with gzip.GzipFile(path, "wb") as gz:\n df.to_stata(gz, version=114)\n with gzip.GzipFile(path, "rb") as gz:\n reread = read_stata(gz, index_col="index")\n tm.assert_frame_equal(df, reread)\n\n def test_unicode_dta_118(self, datapath):\n unicode_df = self.read_dta(datapath("io", "data", "stata", "stata16_118.dta"))\n\n columns = ["utf8", "latin1", "ascii", "utf8_strl", "ascii_strl"]\n values = [\n ["ραηδας", "PÄNDÄS", "p", "ραηδας", "p"],\n ["ƤĀńĐąŜ", "Ö", "a", "ƤĀńĐąŜ", "a"],\n ["ᴘᴀᴎᴅᴀS", "Ü", "n", "ᴘᴀᴎᴅᴀS", "n"],\n [" ", " ", "d", " ", "d"],\n [" ", "", "a", " ", "a"],\n ["", "", "s", "", "s"],\n ["", "", " ", "", " "],\n ]\n expected = DataFrame(values, columns=columns)\n\n tm.assert_frame_equal(unicode_df, expected)\n\n def test_mixed_string_strl(self, using_infer_string):\n # GH 23633\n output = [{"mixed": "string" * 500, "number": 0}, {"mixed": None, "number": 1}]\n output = DataFrame(output)\n output.number = output.number.astype("int32")\n\n with tm.ensure_clean() as path:\n output.to_stata(path, write_index=False, version=117)\n reread = read_stata(path)\n expected = output.fillna("")\n tm.assert_frame_equal(reread, expected)\n\n # Check strl supports all None (null)\n output["mixed"] = None\n output.to_stata(\n path, write_index=False, convert_strl=["mixed"], version=117\n )\n reread = read_stata(path)\n expected = output.copy()\n if using_infer_string:\n expected["mixed"] = expected["mixed"].astype("str")\n expected = expected.fillna("")\n tm.assert_frame_equal(reread, expected)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_all_none_exception(self, version):\n output = [{"none": "none", "number": 0}, {"none": None, "number": 1}]\n output = DataFrame(output)\n output["none"] = None\n with tm.ensure_clean() as path:\n with pytest.raises(ValueError, match="Column `none` cannot be exported"):\n output.to_stata(path, version=version)\n\n @pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n def test_invalid_file_not_written(self, version):\n content = "Here is one __�__ Another one __·__ Another one __½__"\n df = DataFrame([content], columns=["invalid"])\n with tm.ensure_clean() as path:\n msg1 = (\n r"'latin-1' codec can't encode character '\\ufffd' "\n r"in position 14: ordinal not in range\(256\)"\n )\n msg2 = (\n "'ascii' codec can't decode byte 0xef in position 14: "\n r"ordinal not in range\(128\)"\n )\n with pytest.raises(UnicodeEncodeError, match=f"{msg1}|{msg2}"):\n df.to_stata(path)\n\n def test_strl_latin1(self):\n # GH 23573, correct GSO data to reflect correct size\n output = DataFrame(\n [["pandas"] * 2, ["þâÑÐŧ"] * 2], columns=["var_str", "var_strl"]\n )\n\n with tm.ensure_clean() as path:\n output.to_stata(path, version=117, convert_strl=["var_strl"])\n with open(path, "rb") as reread:\n content = reread.read()\n expected = "þâÑÐŧ"\n assert expected.encode("latin-1") in content\n assert expected.encode("utf-8") in content\n gsos = content.split(b"strls")[1][1:-2]\n for gso in gsos.split(b"GSO")[1:]:\n val = gso.split(b"\x00")[-2]\n size = gso[gso.find(b"\x82") + 1]\n assert len(val) == size - 1\n\n def test_encoding_latin1_118(self, datapath):\n # GH 25960\n msg = """\nOne or more strings in the dta file could not be decoded using utf-8, and\nso the fallback encoding of latin-1 is being used. This can happen when a file\nhas been incorrectly encoded by Stata or some other software. You should verify\nthe string values returned are correct."""\n # Move path outside of read_stata, or else assert_produces_warning\n # will block pytests skip mechanism from triggering (failing the test)\n # if the path is not present\n path = datapath("io", "data", "stata", "stata1_encoding_118.dta")\n with tm.assert_produces_warning(UnicodeWarning, filter_level="once") as w:\n encoded = read_stata(path)\n # with filter_level="always", produces 151 warnings which can be slow\n assert len(w) == 1\n assert w[0].message.args[0] == msg\n\n expected = DataFrame([["Düsseldorf"]] * 151, columns=["kreis1849"])\n tm.assert_frame_equal(encoded, expected)\n\n @pytest.mark.slow\n def test_stata_119(self, datapath):\n # Gzipped since contains 32,999 variables and uncompressed is 20MiB\n # Just validate that the reader reports correct number of variables\n # to avoid high peak memory\n with gzip.open(\n datapath("io", "data", "stata", "stata1_119.dta.gz"), "rb"\n ) as gz:\n with StataReader(gz) as reader:\n reader._ensure_open()\n assert reader._nvar == 32999\n\n @pytest.mark.filterwarnings("ignore:Downcasting behavior:FutureWarning")\n @pytest.mark.parametrize("version", [118, 119, None])\n def test_utf8_writer(self, version):\n cat = pd.Categorical(["a", "β", "ĉ"], ordered=True)\n data = DataFrame(\n [\n [1.0, 1, "ᴬ", "ᴀ relatively long ŝtring"],\n [2.0, 2, "ᴮ", ""],\n [3.0, 3, "ᴰ", None],\n ],\n columns=["Å", "β", "ĉ", "strls"],\n )\n data["ᴐᴬᵀ"] = cat\n variable_labels = {\n "Å": "apple",\n "β": "ᵈᵉᵊ",\n "ĉ": "ᴎტჄႲႳႴႶႺ",\n "strls": "Long Strings",\n "ᴐᴬᵀ": "",\n }\n data_label = "ᴅaᵀa-label"\n value_labels = {"β": {1: "label", 2: "æøå", 3: "ŋot valid latin-1"}}\n data["β"] = data["β"].astype(np.int32)\n with tm.ensure_clean() as path:\n writer = StataWriterUTF8(\n path,\n data,\n data_label=data_label,\n convert_strl=["strls"],\n variable_labels=variable_labels,\n write_index=False,\n version=version,\n value_labels=value_labels,\n )\n writer.write_file()\n reread_encoded = read_stata(path)\n # Missing is intentionally converted to empty strl\n data["strls"] = data["strls"].fillna("")\n # Variable with value labels is reread as categorical\n data["β"] = (\n data["β"].replace(value_labels["β"]).astype("category").cat.as_ordered()\n )\n tm.assert_frame_equal(data, reread_encoded)\n with StataReader(path) as reader:\n assert reader.data_label == data_label\n assert reader.variable_labels() == variable_labels\n\n data.to_stata(path, version=version, write_index=False)\n reread_to_stata = read_stata(path)\n tm.assert_frame_equal(data, reread_to_stata)\n\n def test_writer_118_exceptions(self):\n df = DataFrame(np.zeros((1, 33000), dtype=np.int8))\n with tm.ensure_clean() as path:\n with pytest.raises(ValueError, match="version must be either 118 or 119."):\n StataWriterUTF8(path, df, version=117)\n with tm.ensure_clean() as path:\n with pytest.raises(ValueError, match="You must use version 119"):\n StataWriterUTF8(path, df, version=118)\n\n @pytest.mark.parametrize(\n "dtype_backend",\n ["numpy_nullable", pytest.param("pyarrow", marks=td.skip_if_no("pyarrow"))],\n )\n def test_read_write_ea_dtypes(self, dtype_backend):\n df = DataFrame(\n {\n "a": [1, 2, None],\n "b": ["a", "b", "c"],\n "c": [True, False, None],\n "d": [1.5, 2.5, 3.5],\n "e": pd.date_range("2020-12-31", periods=3, freq="D"),\n },\n index=pd.Index([0, 1, 2], name="index"),\n )\n df = df.convert_dtypes(dtype_backend=dtype_backend)\n df.to_stata("test_stata.dta", version=118)\n\n with tm.ensure_clean() as path:\n df.to_stata(path)\n written_and_read_again = self.read_dta(path)\n\n expected = DataFrame(\n {\n "a": [1, 2, np.nan],\n "b": ["a", "b", "c"],\n "c": [1.0, 0, np.nan],\n "d": [1.5, 2.5, 3.5],\n "e": pd.date_range("2020-12-31", periods=3, freq="D"),\n },\n index=pd.Index([0, 1, 2], name="index", dtype=np.int32),\n )\n\n tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)\n\n\n@pytest.mark.parametrize("version", [105, 108, 111, 113, 114])\ndef test_backward_compat(version, datapath):\n data_base = datapath("io", "data", "stata")\n ref = os.path.join(data_base, "stata-compat-118.dta")\n old = os.path.join(data_base, f"stata-compat-{version}.dta")\n expected = read_stata(ref)\n old_dta = read_stata(old)\n tm.assert_frame_equal(old_dta, expected, check_dtype=False)\n\n\ndef test_direct_read(datapath, monkeypatch):\n file_path = datapath("io", "data", "stata", "stata-compat-118.dta")\n\n # Test that opening a file path doesn't buffer the file.\n with StataReader(file_path) as reader:\n # Must not have been buffered to memory\n assert not reader.read().empty\n assert not isinstance(reader._path_or_buf, io.BytesIO)\n\n # Test that we use a given fp exactly, if possible.\n with open(file_path, "rb") as fp:\n with StataReader(fp) as reader:\n assert not reader.read().empty\n assert reader._path_or_buf is fp\n\n # Test that we use a given BytesIO exactly, if possible.\n with open(file_path, "rb") as fp:\n with io.BytesIO(fp.read()) as bio:\n with StataReader(bio) as reader:\n assert not reader.read().empty\n assert reader._path_or_buf is bio\n\n\ndef test_statareader_warns_when_used_without_context(datapath):\n file_path = datapath("io", "data", "stata", "stata-compat-118.dta")\n with tm.assert_produces_warning(\n ResourceWarning,\n match="without using a context manager",\n ):\n sr = StataReader(file_path)\n sr.read()\n with tm.assert_produces_warning(\n FutureWarning,\n match="is not part of the public API",\n ):\n sr.close()\n\n\n@pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n@pytest.mark.parametrize("use_dict", [True, False])\n@pytest.mark.parametrize("infer", [True, False])\ndef test_compression(compression, version, use_dict, infer, compression_to_extension):\n file_name = "dta_inferred_compression.dta"\n if compression:\n if use_dict:\n file_ext = compression\n else:\n file_ext = compression_to_extension[compression]\n file_name += f".{file_ext}"\n compression_arg = compression\n if infer:\n compression_arg = "infer"\n if use_dict:\n compression_arg = {"method": compression}\n\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 2)), columns=list("AB")\n )\n df.index.name = "index"\n with tm.ensure_clean(file_name) as path:\n df.to_stata(path, version=version, compression=compression_arg)\n if compression == "gzip":\n with gzip.open(path, "rb") as comp:\n fp = io.BytesIO(comp.read())\n elif compression == "zip":\n with zipfile.ZipFile(path, "r") as comp:\n fp = io.BytesIO(comp.read(comp.filelist[0]))\n elif compression == "tar":\n with tarfile.open(path) as tar:\n fp = io.BytesIO(tar.extractfile(tar.getnames()[0]).read())\n elif compression == "bz2":\n with bz2.open(path, "rb") as comp:\n fp = io.BytesIO(comp.read())\n elif compression == "zstd":\n zstd = pytest.importorskip("zstandard")\n with zstd.open(path, "rb") as comp:\n fp = io.BytesIO(comp.read())\n elif compression == "xz":\n lzma = pytest.importorskip("lzma")\n with lzma.open(path, "rb") as comp:\n fp = io.BytesIO(comp.read())\n elif compression is None:\n fp = path\n reread = read_stata(fp, index_col="index")\n\n expected = df.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(reread, expected)\n\n\n@pytest.mark.parametrize("method", ["zip", "infer"])\n@pytest.mark.parametrize("file_ext", [None, "dta", "zip"])\ndef test_compression_dict(method, file_ext):\n file_name = f"test.{file_ext}"\n archive_name = "test.dta"\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 2)), columns=list("AB")\n )\n df.index.name = "index"\n with tm.ensure_clean(file_name) as path:\n compression = {"method": method, "archive_name": archive_name}\n df.to_stata(path, compression=compression)\n if method == "zip" or file_ext == "zip":\n with zipfile.ZipFile(path, "r") as zp:\n assert len(zp.filelist) == 1\n assert zp.filelist[0].filename == archive_name\n fp = io.BytesIO(zp.read(zp.filelist[0]))\n else:\n fp = path\n reread = read_stata(fp, index_col="index")\n\n expected = df.copy()\n expected.index = expected.index.astype(np.int32)\n tm.assert_frame_equal(reread, expected)\n\n\n@pytest.mark.parametrize("version", [114, 117, 118, 119, None])\ndef test_chunked_categorical(version):\n df = DataFrame({"cats": Series(["a", "b", "a", "b", "c"], dtype="category")})\n df.index.name = "index"\n\n expected = df.copy()\n expected.index = expected.index.astype(np.int32)\n\n with tm.ensure_clean() as path:\n df.to_stata(path, version=version)\n with StataReader(path, chunksize=2, order_categoricals=False) as reader:\n for i, block in enumerate(reader):\n block = block.set_index("index")\n assert "cats" in block\n tm.assert_series_equal(\n block.cats, expected.cats.iloc[2 * i : 2 * (i + 1)]\n )\n\n\ndef test_chunked_categorical_partial(datapath):\n dta_file = datapath("io", "data", "stata", "stata-dta-partially-labeled.dta")\n values = ["a", "b", "a", "b", 3.0]\n with StataReader(dta_file, chunksize=2) as reader:\n with tm.assert_produces_warning(CategoricalConversionWarning):\n for i, block in enumerate(reader):\n assert list(block.cats) == values[2 * i : 2 * (i + 1)]\n if i < 2:\n idx = pd.Index(["a", "b"])\n else:\n idx = pd.Index([3.0], dtype="float64")\n tm.assert_index_equal(block.cats.cat.categories, idx)\n with tm.assert_produces_warning(CategoricalConversionWarning):\n with StataReader(dta_file, chunksize=5) as reader:\n large_chunk = reader.__next__()\n direct = read_stata(dta_file)\n tm.assert_frame_equal(direct, large_chunk)\n\n\n@pytest.mark.parametrize("chunksize", (-1, 0, "apple"))\ndef test_iterator_errors(datapath, chunksize):\n dta_file = datapath("io", "data", "stata", "stata-dta-partially-labeled.dta")\n with pytest.raises(ValueError, match="chunksize must be a positive"):\n with StataReader(dta_file, chunksize=chunksize):\n pass\n\n\ndef test_iterator_value_labels():\n # GH 31544\n values = ["c_label", "b_label"] + ["a_label"] * 500\n df = DataFrame({f"col{k}": pd.Categorical(values, ordered=True) for k in range(2)})\n with tm.ensure_clean() as path:\n df.to_stata(path, write_index=False)\n expected = pd.Index(["a_label", "b_label", "c_label"])\n with read_stata(path, chunksize=100) as reader:\n for j, chunk in enumerate(reader):\n for i in range(2):\n tm.assert_index_equal(chunk.dtypes.iloc[i].categories, expected)\n tm.assert_frame_equal(chunk, df.iloc[j * 100 : (j + 1) * 100])\n\n\ndef test_precision_loss():\n df = DataFrame(\n [[sum(2**i for i in range(60)), sum(2**i for i in range(52))]],\n columns=["big", "little"],\n )\n with tm.ensure_clean() as path:\n with tm.assert_produces_warning(\n PossiblePrecisionLoss, match="Column converted from int64 to float64"\n ):\n df.to_stata(path, write_index=False)\n reread = read_stata(path)\n expected_dt = Series([np.float64, np.float64], index=["big", "little"])\n tm.assert_series_equal(reread.dtypes, expected_dt)\n assert reread.loc[0, "little"] == df.loc[0, "little"]\n assert reread.loc[0, "big"] == float(df.loc[0, "big"])\n\n\ndef test_compression_roundtrip(compression):\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 df.index.name = "index"\n\n with tm.ensure_clean() as path:\n df.to_stata(path, compression=compression)\n reread = read_stata(path, compression=compression, index_col="index")\n tm.assert_frame_equal(df, reread)\n\n # explicitly ensure file was compressed.\n with tm.decompress_file(path, compression) as fh:\n contents = io.BytesIO(fh.read())\n reread = read_stata(contents, index_col="index")\n tm.assert_frame_equal(df, reread)\n\n\n@pytest.mark.parametrize("to_infer", [True, False])\n@pytest.mark.parametrize("read_infer", [True, False])\ndef test_stata_compression(\n compression_only, read_infer, to_infer, compression_to_extension\n):\n compression = compression_only\n\n ext = compression_to_extension[compression]\n filename = f"test.{ext}"\n\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 df.index.name = "index"\n\n to_compression = "infer" if to_infer else compression\n read_compression = "infer" if read_infer else compression\n\n with tm.ensure_clean(filename) as path:\n df.to_stata(path, compression=to_compression)\n result = read_stata(path, compression=read_compression, index_col="index")\n tm.assert_frame_equal(result, df)\n\n\ndef test_non_categorical_value_labels():\n data = DataFrame(\n {\n "fully_labelled": [1, 2, 3, 3, 1],\n "partially_labelled": [1.0, 2.0, np.nan, 9.0, np.nan],\n "Y": [7, 7, 9, 8, 10],\n "Z": pd.Categorical(["j", "k", "l", "k", "j"]),\n }\n )\n\n with tm.ensure_clean() as path:\n value_labels = {\n "fully_labelled": {1: "one", 2: "two", 3: "three"},\n "partially_labelled": {1.0: "one", 2.0: "two"},\n }\n expected = {**value_labels, "Z": {0: "j", 1: "k", 2: "l"}}\n\n writer = StataWriter(path, data, value_labels=value_labels)\n writer.write_file()\n\n with StataReader(path) as reader:\n reader_value_labels = reader.value_labels()\n assert reader_value_labels == expected\n\n msg = "Can't create value labels for notY, it wasn't found in the dataset."\n with pytest.raises(KeyError, match=msg):\n value_labels = {"notY": {7: "label1", 8: "label2"}}\n StataWriter(path, data, value_labels=value_labels)\n\n msg = (\n "Can't create value labels for Z, value labels "\n "can only be applied to numeric columns."\n )\n with pytest.raises(ValueError, match=msg):\n value_labels = {"Z": {1: "a", 2: "k", 3: "j", 4: "i"}}\n StataWriter(path, data, value_labels=value_labels)\n\n\ndef test_non_categorical_value_label_name_conversion():\n # Check conversion of invalid variable names\n data = DataFrame(\n {\n "invalid~!": [1, 1, 2, 3, 5, 8], # Only alphanumeric and _\n "6_invalid": [1, 1, 2, 3, 5, 8], # Must start with letter or _\n "invalid_name_longer_than_32_characters": [8, 8, 9, 9, 8, 8], # Too long\n "aggregate": [2, 5, 5, 6, 6, 9], # Reserved words\n (1, 2): [1, 2, 3, 4, 5, 6], # Hashable non-string\n }\n )\n\n value_labels = {\n "invalid~!": {1: "label1", 2: "label2"},\n "6_invalid": {1: "label1", 2: "label2"},\n "invalid_name_longer_than_32_characters": {8: "eight", 9: "nine"},\n "aggregate": {5: "five"},\n (1, 2): {3: "three"},\n }\n\n expected = {\n "invalid__": {1: "label1", 2: "label2"},\n "_6_invalid": {1: "label1", 2: "label2"},\n "invalid_name_longer_than_32_char": {8: "eight", 9: "nine"},\n "_aggregate": {5: "five"},\n "_1__2_": {3: "three"},\n }\n\n with tm.ensure_clean() as path:\n with tm.assert_produces_warning(InvalidColumnName):\n data.to_stata(path, value_labels=value_labels)\n\n with StataReader(path) as reader:\n reader_value_labels = reader.value_labels()\n assert reader_value_labels == expected\n\n\ndef test_non_categorical_value_label_convert_categoricals_error():\n # Mapping more than one value to the same label is valid for Stata\n # labels, but can't be read with convert_categoricals=True\n value_labels = {\n "repeated_labels": {10: "Ten", 20: "More than ten", 40: "More than ten"}\n }\n\n data = DataFrame(\n {\n "repeated_labels": [10, 10, 20, 20, 40, 40],\n }\n )\n\n with tm.ensure_clean() as path:\n data.to_stata(path, value_labels=value_labels)\n\n with StataReader(path, convert_categoricals=False) as reader:\n reader_value_labels = reader.value_labels()\n assert reader_value_labels == value_labels\n\n col = "repeated_labels"\n repeats = "-" * 80 + "\n" + "\n".join(["More than ten"])\n\n msg = f"""\nValue labels for column {col} are not unique. These cannot be converted to\npandas categoricals.\n\nEither read the file with `convert_categoricals` set to False or use the\nlow level interface in `StataReader` to separately read the values and the\nvalue_labels.\n\nThe repeated labels are:\n{repeats}\n"""\n with pytest.raises(ValueError, match=msg):\n read_stata(path, convert_categoricals=True)\n\n\n@pytest.mark.parametrize("version", [114, 117, 118, 119, None])\n@pytest.mark.parametrize(\n "dtype",\n [\n pd.BooleanDtype,\n pd.Int8Dtype,\n pd.Int16Dtype,\n pd.Int32Dtype,\n pd.Int64Dtype,\n pd.UInt8Dtype,\n pd.UInt16Dtype,\n pd.UInt32Dtype,\n pd.UInt64Dtype,\n ],\n)\ndef test_nullable_support(dtype, version):\n df = DataFrame(\n {\n "a": Series([1.0, 2.0, 3.0]),\n "b": Series([1, pd.NA, pd.NA], dtype=dtype.name),\n "c": Series(["a", "b", None]),\n }\n )\n dtype_name = df.b.dtype.numpy_dtype.name\n # Only use supported names: no uint, bool or int64\n dtype_name = dtype_name.replace("u", "")\n if dtype_name == "int64":\n dtype_name = "int32"\n elif dtype_name == "bool":\n dtype_name = "int8"\n value = StataMissingValue.BASE_MISSING_VALUES[dtype_name]\n smv = StataMissingValue(value)\n expected_b = Series([1, smv, smv], dtype=object, name="b")\n expected_c = Series(["a", "b", ""], name="c")\n with tm.ensure_clean() as path:\n df.to_stata(path, write_index=False, version=version)\n reread = read_stata(path, convert_missing=True)\n tm.assert_series_equal(df.a, reread.a)\n tm.assert_series_equal(reread.b, expected_b)\n tm.assert_series_equal(reread.c, expected_c)\n\n\ndef test_empty_frame():\n # GH 46240\n # create an empty DataFrame with int64 and float64 dtypes\n df = DataFrame(data={"a": range(3), "b": [1.0, 2.0, 3.0]}).head(0)\n with tm.ensure_clean() as path:\n df.to_stata(path, write_index=False, version=117)\n # Read entire dataframe\n df2 = read_stata(path)\n assert "b" in df2\n # Dtypes don't match since no support for int32\n dtypes = Series({"a": np.dtype("int32"), "b": np.dtype("float64")})\n tm.assert_series_equal(df2.dtypes, dtypes)\n # read one column of empty .dta file\n df3 = read_stata(path, columns=["a"])\n assert "b" not in df3\n tm.assert_series_equal(df3.dtypes, dtypes.loc[["a"]])\n
.venv\Lib\site-packages\pandas\tests\io\test_stata.py
test_stata.py
Python
92,899
0.75
0.084237
0.052306
node-utils
213
2024-09-02T22:51:28.003669
BSD-3-Clause
true
17dec36e061348e2ad3010a82d170c91
import functools\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\n\nimport pandas as pd\nimport pandas._testing as tm\n\npytest.importorskip("odf")\n\nif is_platform_windows():\n pytestmark = pytest.mark.single_cpu\n\n\n@pytest.fixture(autouse=True)\ndef cd_and_set_engine(monkeypatch, datapath):\n func = functools.partial(pd.read_excel, engine="odf")\n monkeypatch.setattr(pd, "read_excel", func)\n monkeypatch.chdir(datapath("io", "data", "excel"))\n\n\ndef test_read_invalid_types_raises():\n # the invalid_value_type.ods required manually editing\n # of the included content.xml file\n with pytest.raises(ValueError, match="Unrecognized type awesome_new_type"):\n pd.read_excel("invalid_value_type.ods")\n\n\ndef test_read_writer_table():\n # Also test reading tables from an text OpenDocument file\n # (.odt)\n index = pd.Index(["Row 1", "Row 2", "Row 3"], name="Header")\n expected = pd.DataFrame(\n [[1, np.nan, 7], [2, np.nan, 8], [3, np.nan, 9]],\n index=index,\n columns=["Column 1", "Unnamed: 2", "Column 3"],\n )\n\n result = pd.read_excel("writertable.odt", sheet_name="Table1", index_col=0)\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_read_newlines_between_xml_elements_table():\n # GH#45598\n expected = pd.DataFrame(\n [[1.0, 4.0, 7], [np.nan, np.nan, 8], [3.0, 6.0, 9]],\n columns=["Column 1", "Column 2", "Column 3"],\n )\n\n result = pd.read_excel("test_newlines.ods")\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_read_unempty_cells():\n expected = pd.DataFrame(\n [1, np.nan, 3, np.nan, 5],\n columns=["Column 1"],\n )\n\n result = pd.read_excel("test_unempty_cells.ods")\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_read_cell_annotation():\n expected = pd.DataFrame(\n ["test", np.nan, "test 3"],\n columns=["Column 1"],\n )\n\n result = pd.read_excel("test_cell_annotation.ods")\n\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\io\excel\test_odf.py
test_odf.py
Python
1,999
0.95
0.090909
0.096154
react-lib
795
2024-11-10T20:43:51.844674
MIT
true
439955885eb4745df2b75cf4b61a7631
from datetime import (\n date,\n datetime,\n)\nimport re\n\nimport pytest\n\nfrom pandas.compat import is_platform_windows\n\nimport pandas as pd\nimport pandas._testing as tm\n\nfrom pandas.io.excel import ExcelWriter\n\nodf = pytest.importorskip("odf")\n\nif is_platform_windows():\n pytestmark = pytest.mark.single_cpu\n\n\n@pytest.fixture\ndef ext():\n return ".ods"\n\n\ndef test_write_append_mode_raises(ext):\n msg = "Append mode is not supported with odf!"\n\n with tm.ensure_clean(ext) as f:\n with pytest.raises(ValueError, match=msg):\n ExcelWriter(f, engine="odf", mode="a")\n\n\n@pytest.mark.parametrize("engine_kwargs", [None, {"kwarg": 1}])\ndef test_engine_kwargs(ext, engine_kwargs):\n # GH 42286\n # GH 43445\n # test for error: OpenDocumentSpreadsheet does not accept any arguments\n with tm.ensure_clean(ext) as f:\n if engine_kwargs is not None:\n error = re.escape(\n "OpenDocumentSpreadsheet() got an unexpected keyword argument 'kwarg'"\n )\n with pytest.raises(\n TypeError,\n match=error,\n ):\n ExcelWriter(f, engine="odf", engine_kwargs=engine_kwargs)\n else:\n with ExcelWriter(f, engine="odf", engine_kwargs=engine_kwargs) as _:\n pass\n\n\ndef test_book_and_sheets_consistent(ext):\n # GH#45687 - Ensure sheets is updated if user modifies book\n with tm.ensure_clean(ext) as f:\n with ExcelWriter(f) as writer:\n assert writer.sheets == {}\n table = odf.table.Table(name="test_name")\n writer.book.spreadsheet.addElement(table)\n assert writer.sheets == {"test_name": table}\n\n\n@pytest.mark.parametrize(\n ["value", "cell_value_type", "cell_value_attribute", "cell_value"],\n argvalues=[\n (True, "boolean", "boolean-value", "true"),\n ("test string", "string", "string-value", "test string"),\n (1, "float", "value", "1"),\n (1.5, "float", "value", "1.5"),\n (\n datetime(2010, 10, 10, 10, 10, 10),\n "date",\n "date-value",\n "2010-10-10T10:10:10",\n ),\n (date(2010, 10, 10), "date", "date-value", "2010-10-10"),\n ],\n)\ndef test_cell_value_type(ext, value, cell_value_type, cell_value_attribute, cell_value):\n # GH#54994 ODS: cell attributes should follow specification\n # http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html#refTable13\n from odf.namespaces import OFFICENS\n from odf.table import (\n TableCell,\n TableRow,\n )\n\n table_cell_name = TableCell().qname\n\n with tm.ensure_clean(ext) as f:\n pd.DataFrame([[value]]).to_excel(f, header=False, index=False)\n\n with pd.ExcelFile(f) as wb:\n sheet = wb._reader.get_sheet_by_index(0)\n sheet_rows = sheet.getElementsByType(TableRow)\n sheet_cells = [\n x\n for x in sheet_rows[0].childNodes\n if hasattr(x, "qname") and x.qname == table_cell_name\n ]\n\n cell = sheet_cells[0]\n assert cell.attributes.get((OFFICENS, "value-type")) == cell_value_type\n assert cell.attributes.get((OFFICENS, cell_value_attribute)) == cell_value\n
.venv\Lib\site-packages\pandas\tests\io\excel\test_odswriter.py
test_odswriter.py
Python
3,268
0.95
0.103774
0.070588
python-kit
230
2024-04-28T18:48:40.715250
GPL-3.0
true
efb6a3e4c7192b192703492498fbed86
import contextlib\nfrom pathlib import Path\nimport re\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\n\nimport pandas as pd\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\nfrom pandas.io.excel import (\n ExcelWriter,\n _OpenpyxlWriter,\n)\nfrom pandas.io.excel._openpyxl import OpenpyxlReader\n\nopenpyxl = pytest.importorskip("openpyxl")\n\nif is_platform_windows():\n pytestmark = pytest.mark.single_cpu\n\n\n@pytest.fixture\ndef ext():\n return ".xlsx"\n\n\ndef test_to_excel_styleconverter():\n from openpyxl import styles\n\n hstyle = {\n "font": {"color": "00FF0000", "bold": True},\n "borders": {"top": "thin", "right": "thin", "bottom": "thin", "left": "thin"},\n "alignment": {"horizontal": "center", "vertical": "top"},\n "fill": {"patternType": "solid", "fgColor": {"rgb": "006666FF", "tint": 0.3}},\n "number_format": {"format_code": "0.00"},\n "protection": {"locked": True, "hidden": False},\n }\n\n font_color = styles.Color("00FF0000")\n font = styles.Font(bold=True, color=font_color)\n side = styles.Side(style=styles.borders.BORDER_THIN)\n border = styles.Border(top=side, right=side, bottom=side, left=side)\n alignment = styles.Alignment(horizontal="center", vertical="top")\n fill_color = styles.Color(rgb="006666FF", tint=0.3)\n fill = styles.PatternFill(patternType="solid", fgColor=fill_color)\n\n number_format = "0.00"\n\n protection = styles.Protection(locked=True, hidden=False)\n\n kw = _OpenpyxlWriter._convert_to_style_kwargs(hstyle)\n assert kw["font"] == font\n assert kw["border"] == border\n assert kw["alignment"] == alignment\n assert kw["fill"] == fill\n assert kw["number_format"] == number_format\n assert kw["protection"] == protection\n\n\ndef test_write_cells_merge_styled(ext):\n from pandas.io.formats.excel import ExcelCell\n\n sheet_name = "merge_styled"\n\n sty_b1 = {"font": {"color": "00FF0000"}}\n sty_a2 = {"font": {"color": "0000FF00"}}\n\n initial_cells = [\n ExcelCell(col=1, row=0, val=42, style=sty_b1),\n ExcelCell(col=0, row=1, val=99, style=sty_a2),\n ]\n\n sty_merged = {"font": {"color": "000000FF", "bold": True}}\n sty_kwargs = _OpenpyxlWriter._convert_to_style_kwargs(sty_merged)\n openpyxl_sty_merged = sty_kwargs["font"]\n merge_cells = [\n ExcelCell(\n col=0, row=0, val="pandas", mergestart=1, mergeend=1, style=sty_merged\n )\n ]\n\n with tm.ensure_clean(ext) as path:\n with _OpenpyxlWriter(path) as writer:\n writer._write_cells(initial_cells, sheet_name=sheet_name)\n writer._write_cells(merge_cells, sheet_name=sheet_name)\n\n wks = writer.sheets[sheet_name]\n xcell_b1 = wks["B1"]\n xcell_a2 = wks["A2"]\n assert xcell_b1.font == openpyxl_sty_merged\n assert xcell_a2.font == openpyxl_sty_merged\n\n\n@pytest.mark.parametrize("iso_dates", [True, False])\ndef test_engine_kwargs_write(ext, iso_dates):\n # GH 42286 GH 43445\n engine_kwargs = {"iso_dates": iso_dates}\n with tm.ensure_clean(ext) as f:\n with ExcelWriter(f, engine="openpyxl", engine_kwargs=engine_kwargs) as writer:\n assert writer.book.iso_dates == iso_dates\n # ExcelWriter won't allow us to close without writing something\n DataFrame().to_excel(writer)\n\n\ndef test_engine_kwargs_append_invalid(ext):\n # GH 43445\n # test whether an invalid engine kwargs actually raises\n with tm.ensure_clean(ext) as f:\n DataFrame(["hello", "world"]).to_excel(f)\n with pytest.raises(\n TypeError,\n match=re.escape(\n "load_workbook() got an unexpected keyword argument 'apple_banana'"\n ),\n ):\n with ExcelWriter(\n f, engine="openpyxl", mode="a", engine_kwargs={"apple_banana": "fruit"}\n ) as writer:\n # ExcelWriter needs us to write something to close properly\n DataFrame(["good"]).to_excel(writer, sheet_name="Sheet2")\n\n\n@pytest.mark.parametrize("data_only, expected", [(True, 0), (False, "=1+1")])\ndef test_engine_kwargs_append_data_only(ext, data_only, expected):\n # GH 43445\n # tests whether the data_only engine_kwarg actually works well for\n # openpyxl's load_workbook\n with tm.ensure_clean(ext) as f:\n DataFrame(["=1+1"]).to_excel(f)\n with ExcelWriter(\n f, engine="openpyxl", mode="a", engine_kwargs={"data_only": data_only}\n ) as writer:\n assert writer.sheets["Sheet1"]["B2"].value == expected\n # ExcelWriter needs us to writer something to close properly?\n DataFrame().to_excel(writer, sheet_name="Sheet2")\n\n # ensure that data_only also works for reading\n # and that formulas/values roundtrip\n assert (\n pd.read_excel(\n f,\n sheet_name="Sheet1",\n engine="openpyxl",\n engine_kwargs={"data_only": data_only},\n ).iloc[0, 1]\n == expected\n )\n\n\n@pytest.mark.parametrize("kwarg_name", ["read_only", "data_only"])\n@pytest.mark.parametrize("kwarg_value", [True, False])\ndef test_engine_kwargs_append_reader(datapath, ext, kwarg_name, kwarg_value):\n # GH 55027\n # test that `read_only` and `data_only` can be passed to\n # `openpyxl.reader.excel.load_workbook` via `engine_kwargs`\n filename = datapath("io", "data", "excel", "test1" + ext)\n with contextlib.closing(\n OpenpyxlReader(filename, engine_kwargs={kwarg_name: kwarg_value})\n ) as reader:\n assert getattr(reader.book, kwarg_name) == kwarg_value\n\n\n@pytest.mark.parametrize(\n "mode,expected", [("w", ["baz"]), ("a", ["foo", "bar", "baz"])]\n)\ndef test_write_append_mode(ext, mode, expected):\n df = DataFrame([1], columns=["baz"])\n\n with tm.ensure_clean(ext) as f:\n wb = openpyxl.Workbook()\n wb.worksheets[0].title = "foo"\n wb.worksheets[0]["A1"].value = "foo"\n wb.create_sheet("bar")\n wb.worksheets[1]["A1"].value = "bar"\n wb.save(f)\n\n with ExcelWriter(f, engine="openpyxl", mode=mode) as writer:\n df.to_excel(writer, sheet_name="baz", index=False)\n\n with contextlib.closing(openpyxl.load_workbook(f)) as wb2:\n result = [sheet.title for sheet in wb2.worksheets]\n assert result == expected\n\n for index, cell_value in enumerate(expected):\n assert wb2.worksheets[index]["A1"].value == cell_value\n\n\n@pytest.mark.parametrize(\n "if_sheet_exists,num_sheets,expected",\n [\n ("new", 2, ["apple", "banana"]),\n ("replace", 1, ["pear"]),\n ("overlay", 1, ["pear", "banana"]),\n ],\n)\ndef test_if_sheet_exists_append_modes(ext, if_sheet_exists, num_sheets, expected):\n # GH 40230\n df1 = DataFrame({"fruit": ["apple", "banana"]})\n df2 = DataFrame({"fruit": ["pear"]})\n\n with tm.ensure_clean(ext) as f:\n df1.to_excel(f, engine="openpyxl", sheet_name="foo", index=False)\n with ExcelWriter(\n f, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists\n ) as writer:\n df2.to_excel(writer, sheet_name="foo", index=False)\n\n with contextlib.closing(openpyxl.load_workbook(f)) as wb:\n assert len(wb.sheetnames) == num_sheets\n assert wb.sheetnames[0] == "foo"\n result = pd.read_excel(wb, "foo", engine="openpyxl")\n assert list(result["fruit"]) == expected\n if len(wb.sheetnames) == 2:\n result = pd.read_excel(wb, wb.sheetnames[1], engine="openpyxl")\n tm.assert_frame_equal(result, df2)\n\n\n@pytest.mark.parametrize(\n "startrow, startcol, greeting, goodbye",\n [\n (0, 0, ["poop", "world"], ["goodbye", "people"]),\n (0, 1, ["hello", "world"], ["poop", "people"]),\n (1, 0, ["hello", "poop"], ["goodbye", "people"]),\n (1, 1, ["hello", "world"], ["goodbye", "poop"]),\n ],\n)\ndef test_append_overlay_startrow_startcol(ext, startrow, startcol, greeting, goodbye):\n df1 = DataFrame({"greeting": ["hello", "world"], "goodbye": ["goodbye", "people"]})\n df2 = DataFrame(["poop"])\n\n with tm.ensure_clean(ext) as f:\n df1.to_excel(f, engine="openpyxl", sheet_name="poo", index=False)\n with ExcelWriter(\n f, engine="openpyxl", mode="a", if_sheet_exists="overlay"\n ) as writer:\n # use startrow+1 because we don't have a header\n df2.to_excel(\n writer,\n index=False,\n header=False,\n startrow=startrow + 1,\n startcol=startcol,\n sheet_name="poo",\n )\n\n result = pd.read_excel(f, sheet_name="poo", engine="openpyxl")\n expected = DataFrame({"greeting": greeting, "goodbye": goodbye})\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "if_sheet_exists,msg",\n [\n (\n "invalid",\n "'invalid' is not valid for if_sheet_exists. Valid options "\n "are 'error', 'new', 'replace' and 'overlay'.",\n ),\n (\n "error",\n "Sheet 'foo' already exists and if_sheet_exists is set to 'error'.",\n ),\n (\n None,\n "Sheet 'foo' already exists and if_sheet_exists is set to 'error'.",\n ),\n ],\n)\ndef test_if_sheet_exists_raises(ext, if_sheet_exists, msg):\n # GH 40230\n df = DataFrame({"fruit": ["pear"]})\n with tm.ensure_clean(ext) as f:\n with pytest.raises(ValueError, match=re.escape(msg)):\n df.to_excel(f, sheet_name="foo", engine="openpyxl")\n with ExcelWriter(\n f, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists\n ) as writer:\n df.to_excel(writer, sheet_name="foo")\n\n\ndef test_to_excel_with_openpyxl_engine(ext):\n # GH 29854\n with tm.ensure_clean(ext) as filename:\n df1 = DataFrame({"A": np.linspace(1, 10, 10)})\n df2 = DataFrame({"B": np.linspace(1, 20, 10)})\n df = pd.concat([df1, df2], axis=1)\n styled = df.style.map(\n lambda val: f"color: {'red' if val < 0 else 'black'}"\n ).highlight_max()\n\n styled.to_excel(filename, engine="openpyxl")\n\n\n@pytest.mark.parametrize("read_only", [True, False])\ndef test_read_workbook(datapath, ext, read_only):\n # GH 39528\n filename = datapath("io", "data", "excel", "test1" + ext)\n with contextlib.closing(\n openpyxl.load_workbook(filename, read_only=read_only)\n ) as wb:\n result = pd.read_excel(wb, engine="openpyxl")\n expected = pd.read_excel(filename)\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "header, expected_data",\n [\n (\n 0,\n {\n "Title": [np.nan, "A", 1, 2, 3],\n "Unnamed: 1": [np.nan, "B", 4, 5, 6],\n "Unnamed: 2": [np.nan, "C", 7, 8, 9],\n },\n ),\n (2, {"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}),\n ],\n)\n@pytest.mark.parametrize(\n "filename", ["dimension_missing", "dimension_small", "dimension_large"]\n)\n# When read_only is None, use read_excel instead of a workbook\n@pytest.mark.parametrize("read_only", [True, False, None])\ndef test_read_with_bad_dimension(\n datapath, ext, header, expected_data, filename, read_only\n):\n # GH 38956, 39001 - no/incorrect dimension information\n path = datapath("io", "data", "excel", f"{filename}{ext}")\n if read_only is None:\n result = pd.read_excel(path, header=header)\n else:\n with contextlib.closing(\n openpyxl.load_workbook(path, read_only=read_only)\n ) as wb:\n result = pd.read_excel(wb, engine="openpyxl", header=header)\n expected = DataFrame(expected_data)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_append_mode_file(ext):\n # GH 39576\n df = DataFrame()\n\n with tm.ensure_clean(ext) as f:\n df.to_excel(f, engine="openpyxl")\n\n with ExcelWriter(\n f, mode="a", engine="openpyxl", if_sheet_exists="new"\n ) as writer:\n df.to_excel(writer)\n\n # make sure that zip files are not concatenated by making sure that\n # "docProps/app.xml" only occurs twice in the file\n data = Path(f).read_bytes()\n first = data.find(b"docProps/app.xml")\n second = data.find(b"docProps/app.xml", first + 1)\n third = data.find(b"docProps/app.xml", second + 1)\n assert second != -1 and third == -1\n\n\n# When read_only is None, use read_excel instead of a workbook\n@pytest.mark.parametrize("read_only", [True, False, None])\ndef test_read_with_empty_trailing_rows(datapath, ext, read_only):\n # GH 39181\n path = datapath("io", "data", "excel", f"empty_trailing_rows{ext}")\n if read_only is None:\n result = pd.read_excel(path)\n else:\n with contextlib.closing(\n openpyxl.load_workbook(path, read_only=read_only)\n ) as wb:\n result = pd.read_excel(wb, engine="openpyxl")\n expected = DataFrame(\n {\n "Title": [np.nan, "A", 1, 2, 3],\n "Unnamed: 1": [np.nan, "B", 4, 5, 6],\n "Unnamed: 2": [np.nan, "C", 7, 8, 9],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\n# When read_only is None, use read_excel instead of a workbook\n@pytest.mark.parametrize("read_only", [True, False, None])\ndef test_read_empty_with_blank_row(datapath, ext, read_only):\n # GH 39547 - empty excel file with a row that has no data\n path = datapath("io", "data", "excel", f"empty_with_blank_row{ext}")\n if read_only is None:\n result = pd.read_excel(path)\n else:\n with contextlib.closing(\n openpyxl.load_workbook(path, read_only=read_only)\n ) as wb:\n result = pd.read_excel(wb, engine="openpyxl")\n expected = DataFrame()\n tm.assert_frame_equal(result, expected)\n\n\ndef test_book_and_sheets_consistent(ext):\n # GH#45687 - Ensure sheets is updated if user modifies book\n with tm.ensure_clean(ext) as f:\n with ExcelWriter(f, engine="openpyxl") as writer:\n assert writer.sheets == {}\n sheet = writer.book.create_sheet("test_name", 0)\n assert writer.sheets == {"test_name": sheet}\n\n\ndef test_ints_spelled_with_decimals(datapath, ext):\n # GH 46988 - openpyxl returns this sheet with floats\n path = datapath("io", "data", "excel", f"ints_spelled_with_decimals{ext}")\n result = pd.read_excel(path)\n expected = DataFrame(range(2, 12), columns=[1])\n tm.assert_frame_equal(result, expected)\n\n\ndef test_read_multiindex_header_no_index_names(datapath, ext):\n # GH#47487\n path = datapath("io", "data", "excel", f"multiindex_no_index_names{ext}")\n result = pd.read_excel(path, index_col=[0, 1, 2], header=[0, 1, 2])\n expected = DataFrame(\n [[np.nan, "x", "x", "x"], ["x", np.nan, np.nan, np.nan]],\n columns=pd.MultiIndex.from_tuples(\n [("X", "Y", "A1"), ("X", "Y", "A2"), ("XX", "YY", "B1"), ("XX", "YY", "B2")]\n ),\n index=pd.MultiIndex.from_tuples([("A", "AA", "AAA"), ("A", "BB", "BBB")]),\n )\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\io\excel\test_openpyxl.py
test_openpyxl.py
Python
15,227
0.95
0.074074
0.085635
vue-tools
106
2024-07-16T11:11:43.636734
MIT
true
33cafa007d61b0f94d59a901a091a187
from __future__ import annotations\n\nfrom datetime import (\n datetime,\n time,\n)\nfrom functools import partial\nfrom io import BytesIO\nimport os\nfrom pathlib import Path\nimport platform\nimport re\nfrom urllib.error import URLError\nfrom zipfile import BadZipFile\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n Series,\n read_csv,\n)\nimport pandas._testing as tm\n\nif is_platform_windows():\n pytestmark = pytest.mark.single_cpu\n\nread_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"]\nengine_params = [\n # Add any engines to test here\n # When defusedxml is installed it triggers deprecation warnings for\n # xlrd and openpyxl, so catch those here\n pytest.param(\n "xlrd",\n marks=[\n td.skip_if_no("xlrd"),\n ],\n ),\n pytest.param(\n "openpyxl",\n marks=[\n td.skip_if_no("openpyxl"),\n ],\n ),\n pytest.param(\n None,\n marks=[\n td.skip_if_no("xlrd"),\n ],\n ),\n pytest.param("pyxlsb", marks=td.skip_if_no("pyxlsb")),\n pytest.param("odf", marks=td.skip_if_no("odf")),\n pytest.param("calamine", marks=td.skip_if_no("python_calamine")),\n]\n\n\ndef _is_valid_engine_ext_pair(engine, read_ext: str) -> bool:\n """\n Filter out invalid (engine, ext) pairs instead of skipping, as that\n produces 500+ pytest.skips.\n """\n engine = engine.values[0]\n if engine == "openpyxl" and read_ext == ".xls":\n return False\n if engine == "odf" and read_ext != ".ods":\n return False\n if read_ext == ".ods" and engine not in {"odf", "calamine"}:\n return False\n if engine == "pyxlsb" and read_ext != ".xlsb":\n return False\n if read_ext == ".xlsb" and engine not in {"pyxlsb", "calamine"}:\n return False\n if engine == "xlrd" and read_ext != ".xls":\n return False\n return True\n\n\ndef _transfer_marks(engine, read_ext):\n """\n engine gives us a pytest.param object with some marks, read_ext is just\n a string. We need to generate a new pytest.param inheriting the marks.\n """\n values = engine.values + (read_ext,)\n new_param = pytest.param(values, marks=engine.marks)\n return new_param\n\n\n@pytest.fixture(\n params=[\n _transfer_marks(eng, ext)\n for eng in engine_params\n for ext in read_ext_params\n if _is_valid_engine_ext_pair(eng, ext)\n ],\n ids=str,\n)\ndef engine_and_read_ext(request):\n """\n Fixture for Excel reader engine and read_ext, only including valid pairs.\n """\n return request.param\n\n\n@pytest.fixture\ndef engine(engine_and_read_ext):\n engine, read_ext = engine_and_read_ext\n return engine\n\n\n@pytest.fixture\ndef read_ext(engine_and_read_ext):\n engine, read_ext = engine_and_read_ext\n return read_ext\n\n\n@pytest.fixture\ndef df_ref(datapath):\n """\n Obtain the reference data from read_csv with the Python engine.\n """\n filepath = datapath("io", "data", "csv", "test1.csv")\n df_ref = read_csv(filepath, index_col=0, parse_dates=True, engine="python")\n return df_ref\n\n\ndef get_exp_unit(read_ext: str, engine: str | None) -> str:\n return "ns"\n\n\ndef adjust_expected(expected: DataFrame, read_ext: str, engine: str) -> None:\n expected.index.name = None\n unit = get_exp_unit(read_ext, engine)\n # error: "Index" has no attribute "as_unit"\n expected.index = expected.index.as_unit(unit) # type: ignore[attr-defined]\n\n\ndef xfail_datetimes_with_pyxlsb(engine, request):\n if engine == "pyxlsb":\n request.applymarker(\n pytest.mark.xfail(\n reason="Sheets containing datetimes not supported by pyxlsb"\n )\n )\n\n\nclass TestReaders:\n @pytest.fixture(autouse=True)\n def cd_and_set_engine(self, engine, datapath, monkeypatch):\n """\n Change directory and set engine for read_excel calls.\n """\n func = partial(pd.read_excel, engine=engine)\n monkeypatch.chdir(datapath("io", "data", "excel"))\n monkeypatch.setattr(pd, "read_excel", func)\n\n def test_engine_used(self, read_ext, engine, monkeypatch):\n # GH 38884\n def parser(self, *args, **kwargs):\n return self.engine\n\n monkeypatch.setattr(pd.ExcelFile, "parse", parser)\n\n expected_defaults = {\n "xlsx": "openpyxl",\n "xlsm": "openpyxl",\n "xlsb": "pyxlsb",\n "xls": "xlrd",\n "ods": "odf",\n }\n\n with open("test1" + read_ext, "rb") as f:\n result = pd.read_excel(f)\n\n if engine is not None:\n expected = engine\n else:\n expected = expected_defaults[read_ext[1:]]\n assert result == expected\n\n def test_engine_kwargs(self, read_ext, engine):\n # GH#52214\n expected_defaults = {\n "xlsx": {"foo": "abcd"},\n "xlsm": {"foo": 123},\n "xlsb": {"foo": "True"},\n "xls": {"foo": True},\n "ods": {"foo": "abcd"},\n }\n\n if engine in {"xlrd", "pyxlsb"}:\n msg = re.escape(r"open_workbook() got an unexpected keyword argument 'foo'")\n elif engine == "odf":\n msg = re.escape(r"load() got an unexpected keyword argument 'foo'")\n else:\n msg = re.escape(r"load_workbook() got an unexpected keyword argument 'foo'")\n\n if engine is not None:\n with pytest.raises(TypeError, match=msg):\n pd.read_excel(\n "test1" + read_ext,\n sheet_name="Sheet1",\n index_col=0,\n engine_kwargs=expected_defaults[read_ext[1:]],\n )\n\n def test_usecols_int(self, read_ext):\n # usecols as int\n msg = "Passing an integer for `usecols`"\n with pytest.raises(ValueError, match=msg):\n pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=3\n )\n\n # usecols as int\n with pytest.raises(ValueError, match=msg):\n pd.read_excel(\n "test1" + read_ext,\n sheet_name="Sheet2",\n skiprows=[1],\n index_col=0,\n usecols=3,\n )\n\n def test_usecols_list(self, request, engine, read_ext, df_ref):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n expected = df_ref[["B", "C"]]\n adjust_expected(expected, read_ext, engine)\n\n df1 = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=[0, 2, 3]\n )\n df2 = pd.read_excel(\n "test1" + read_ext,\n sheet_name="Sheet2",\n skiprows=[1],\n index_col=0,\n usecols=[0, 2, 3],\n )\n\n # TODO add index to xls file)\n tm.assert_frame_equal(df1, expected)\n tm.assert_frame_equal(df2, expected)\n\n def test_usecols_str(self, request, engine, read_ext, df_ref):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n expected = df_ref[["A", "B", "C"]]\n adjust_expected(expected, read_ext, engine)\n\n df2 = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A:D"\n )\n df3 = pd.read_excel(\n "test1" + read_ext,\n sheet_name="Sheet2",\n skiprows=[1],\n index_col=0,\n usecols="A:D",\n )\n\n # TODO add index to xls, read xls ignores index name ?\n tm.assert_frame_equal(df2, expected)\n tm.assert_frame_equal(df3, expected)\n\n expected = df_ref[["B", "C"]]\n adjust_expected(expected, read_ext, engine)\n\n df2 = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,C,D"\n )\n df3 = pd.read_excel(\n "test1" + read_ext,\n sheet_name="Sheet2",\n skiprows=[1],\n index_col=0,\n usecols="A,C,D",\n )\n # TODO add index to xls file\n tm.assert_frame_equal(df2, expected)\n tm.assert_frame_equal(df3, expected)\n\n df2 = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,C:D"\n )\n df3 = pd.read_excel(\n "test1" + read_ext,\n sheet_name="Sheet2",\n skiprows=[1],\n index_col=0,\n usecols="A,C:D",\n )\n tm.assert_frame_equal(df2, expected)\n tm.assert_frame_equal(df3, expected)\n\n @pytest.mark.parametrize(\n "usecols", [[0, 1, 3], [0, 3, 1], [1, 0, 3], [1, 3, 0], [3, 0, 1], [3, 1, 0]]\n )\n def test_usecols_diff_positional_int_columns_order(\n self, request, engine, read_ext, usecols, df_ref\n ):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n expected = df_ref[["A", "C"]]\n adjust_expected(expected, read_ext, engine)\n\n result = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=usecols\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("usecols", [["B", "D"], ["D", "B"]])\n def test_usecols_diff_positional_str_columns_order(self, read_ext, usecols, df_ref):\n expected = df_ref[["B", "D"]]\n expected.index = range(len(expected))\n\n result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", usecols=usecols)\n tm.assert_frame_equal(result, expected)\n\n def test_read_excel_without_slicing(self, request, engine, read_ext, df_ref):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n expected = df_ref\n adjust_expected(expected, read_ext, engine)\n\n result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0)\n tm.assert_frame_equal(result, expected)\n\n def test_usecols_excel_range_str(self, request, engine, read_ext, df_ref):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n expected = df_ref[["C", "D"]]\n adjust_expected(expected, read_ext, engine)\n\n result = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,D:E"\n )\n tm.assert_frame_equal(result, expected)\n\n def test_usecols_excel_range_str_invalid(self, read_ext):\n msg = "Invalid column name: E1"\n\n with pytest.raises(ValueError, match=msg):\n pd.read_excel("test1" + read_ext, sheet_name="Sheet1", usecols="D:E1")\n\n def test_index_col_label_error(self, read_ext):\n msg = "list indices must be integers.*, not str"\n\n with pytest.raises(TypeError, match=msg):\n pd.read_excel(\n "test1" + read_ext,\n sheet_name="Sheet1",\n index_col=["A"],\n usecols=["A", "C"],\n )\n\n def test_index_col_str(self, read_ext):\n # see gh-52716\n result = pd.read_excel("test1" + read_ext, sheet_name="Sheet3", index_col="A")\n expected = DataFrame(\n columns=["B", "C", "D", "E", "F"], index=Index([], name="A")\n )\n tm.assert_frame_equal(result, expected)\n\n def test_index_col_empty(self, read_ext):\n # see gh-9208\n result = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet3", index_col=["A", "B", "C"]\n )\n expected = DataFrame(\n columns=["D", "E", "F"],\n index=MultiIndex(levels=[[]] * 3, codes=[[]] * 3, names=["A", "B", "C"]),\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("index_col", [None, 2])\n def test_index_col_with_unnamed(self, read_ext, index_col):\n # see gh-18792\n result = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet4", index_col=index_col\n )\n expected = DataFrame(\n [["i1", "a", "x"], ["i2", "b", "y"]], columns=["Unnamed: 0", "col1", "col2"]\n )\n if index_col:\n expected = expected.set_index(expected.columns[index_col])\n\n tm.assert_frame_equal(result, expected)\n\n def test_usecols_pass_non_existent_column(self, read_ext):\n msg = (\n "Usecols do not match columns, "\n "columns expected but not found: "\n r"\['E'\]"\n )\n\n with pytest.raises(ValueError, match=msg):\n pd.read_excel("test1" + read_ext, usecols=["E"])\n\n def test_usecols_wrong_type(self, read_ext):\n msg = (\n "'usecols' must either be list-like of "\n "all strings, all unicode, all integers or a callable."\n )\n\n with pytest.raises(ValueError, match=msg):\n pd.read_excel("test1" + read_ext, usecols=["E1", 0])\n\n def test_excel_stop_iterator(self, read_ext):\n parsed = pd.read_excel("test2" + read_ext, sheet_name="Sheet1")\n expected = DataFrame([["aaaa", "bbbbb"]], columns=["Test", "Test1"])\n tm.assert_frame_equal(parsed, expected)\n\n def test_excel_cell_error_na(self, request, engine, read_ext):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n # https://github.com/tafia/calamine/issues/355\n if engine == "calamine" and read_ext == ".ods":\n request.applymarker(\n pytest.mark.xfail(reason="Calamine can't extract error from ods files")\n )\n\n parsed = pd.read_excel("test3" + read_ext, sheet_name="Sheet1")\n expected = DataFrame([[np.nan]], columns=["Test"])\n tm.assert_frame_equal(parsed, expected)\n\n def test_excel_table(self, request, engine, read_ext, df_ref):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n expected = df_ref\n adjust_expected(expected, read_ext, engine)\n\n df1 = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0)\n df2 = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet2", skiprows=[1], index_col=0\n )\n # TODO add index to file\n tm.assert_frame_equal(df1, expected)\n tm.assert_frame_equal(df2, expected)\n\n df3 = pd.read_excel(\n "test1" + read_ext, sheet_name="Sheet1", index_col=0, skipfooter=1\n )\n tm.assert_frame_equal(df3, df1.iloc[:-1])\n\n def test_reader_special_dtypes(self, request, engine, read_ext):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n unit = get_exp_unit(read_ext, engine)\n expected = DataFrame.from_dict(\n {\n "IntCol": [1, 2, -3, 4, 0],\n "FloatCol": [1.25, 2.25, 1.83, 1.92, 0.0000000005],\n "BoolCol": [True, False, True, True, False],\n "StrCol": [1, 2, 3, 4, 5],\n "Str2Col": ["a", 3, "c", "d", "e"],\n "DateCol": Index(\n [\n datetime(2013, 10, 30),\n datetime(2013, 10, 31),\n datetime(1905, 1, 1),\n datetime(2013, 12, 14),\n datetime(2015, 3, 14),\n ],\n dtype=f"M8[{unit}]",\n ),\n },\n )\n basename = "test_types"\n\n # should read in correctly and infer types\n actual = pd.read_excel(basename + read_ext, sheet_name="Sheet1")\n tm.assert_frame_equal(actual, expected)\n\n # if not coercing number, then int comes in as float\n float_expected = expected.copy()\n float_expected.loc[float_expected.index[1], "Str2Col"] = 3.0\n actual = pd.read_excel(basename + read_ext, sheet_name="Sheet1")\n tm.assert_frame_equal(actual, float_expected)\n\n # check setting Index (assuming xls and xlsx are the same here)\n for icol, name in enumerate(expected.columns):\n actual = pd.read_excel(\n basename + read_ext, sheet_name="Sheet1", index_col=icol\n )\n exp = expected.set_index(name)\n tm.assert_frame_equal(actual, exp)\n\n expected["StrCol"] = expected["StrCol"].apply(str)\n actual = pd.read_excel(\n basename + read_ext, sheet_name="Sheet1", converters={"StrCol": str}\n )\n tm.assert_frame_equal(actual, expected)\n\n # GH8212 - support for converters and missing values\n def test_reader_converters(self, read_ext):\n basename = "test_converters"\n\n expected = DataFrame.from_dict(\n {\n "IntCol": [1, 2, -3, -1000, 0],\n "FloatCol": [12.5, np.nan, 18.3, 19.2, 0.000000005],\n "BoolCol": ["Found", "Found", "Found", "Not found", "Found"],\n "StrCol": ["1", np.nan, "3", "4", "5"],\n }\n )\n\n converters = {\n "IntCol": lambda x: int(x) if x != "" else -1000,\n "FloatCol": lambda x: 10 * x if x else np.nan,\n 2: lambda x: "Found" if x != "" else "Not found",\n 3: lambda x: str(x) if x else "",\n }\n\n # should read in correctly and set types of single cells (not array\n # dtypes)\n actual = pd.read_excel(\n basename + read_ext, sheet_name="Sheet1", converters=converters\n )\n tm.assert_frame_equal(actual, expected)\n\n def test_reader_dtype(self, read_ext):\n # GH 8212\n basename = "testdtype"\n actual = pd.read_excel(basename + read_ext)\n\n expected = DataFrame(\n {\n "a": [1, 2, 3, 4],\n "b": [2.5, 3.5, 4.5, 5.5],\n "c": [1, 2, 3, 4],\n "d": [1.0, 2.0, np.nan, 4.0],\n }\n )\n\n tm.assert_frame_equal(actual, expected)\n\n actual = pd.read_excel(\n basename + read_ext, dtype={"a": "float64", "b": "float32", "c": str}\n )\n\n expected["a"] = expected["a"].astype("float64")\n expected["b"] = expected["b"].astype("float32")\n expected["c"] = Series(["001", "002", "003", "004"], dtype="str")\n tm.assert_frame_equal(actual, expected)\n\n msg = "Unable to convert column d to type int64"\n with pytest.raises(ValueError, match=msg):\n pd.read_excel(basename + read_ext, dtype={"d": "int64"})\n\n @pytest.mark.parametrize(\n "dtype,expected",\n [\n (\n None,\n DataFrame(\n {\n "a": [1, 2, 3, 4],\n "b": [2.5, 3.5, 4.5, 5.5],\n "c": [1, 2, 3, 4],\n "d": [1.0, 2.0, np.nan, 4.0],\n }\n ),\n ),\n (\n {"a": "float64", "b": "float32", "c": str, "d": str},\n DataFrame(\n {\n "a": Series([1, 2, 3, 4], dtype="float64"),\n "b": Series([2.5, 3.5, 4.5, 5.5], dtype="float32"),\n "c": Series(["001", "002", "003", "004"], dtype="str"),\n "d": Series(["1", "2", np.nan, "4"], dtype="str"),\n },\n ),\n ),\n ],\n )\n def test_reader_dtype_str(self, read_ext, dtype, expected):\n # see gh-20377\n basename = "testdtype"\n\n actual = pd.read_excel(basename + read_ext, dtype=dtype)\n tm.assert_frame_equal(actual, expected)\n\n def test_dtype_backend(self, read_ext, dtype_backend, engine):\n # GH#36712\n if read_ext in (".xlsb", ".xls"):\n pytest.skip(f"No engine for filetype: '{read_ext}'")\n\n df = DataFrame(\n {\n "a": Series([1, 3], dtype="Int64"),\n "b": Series([2.5, 4.5], dtype="Float64"),\n "c": Series([True, False], dtype="boolean"),\n "d": Series(["a", "b"], dtype="string"),\n "e": Series([pd.NA, 6], dtype="Int64"),\n "f": Series([pd.NA, 7.5], dtype="Float64"),\n "g": Series([pd.NA, True], dtype="boolean"),\n "h": Series([pd.NA, "a"], dtype="string"),\n "i": Series([pd.Timestamp("2019-12-31")] * 2),\n "j": Series([pd.NA, pd.NA], dtype="Int64"),\n }\n )\n with tm.ensure_clean(read_ext) as file_path:\n df.to_excel(file_path, sheet_name="test", index=False)\n result = pd.read_excel(\n file_path, sheet_name="test", dtype_backend=dtype_backend\n )\n if dtype_backend == "pyarrow":\n import pyarrow as pa\n\n from pandas.arrays import ArrowExtensionArray\n\n expected = DataFrame(\n {\n col: ArrowExtensionArray(pa.array(df[col], from_pandas=True))\n for col in df.columns\n }\n )\n # pyarrow by default infers timestamp resolution as us, not ns\n expected["i"] = ArrowExtensionArray(\n expected["i"].array._pa_array.cast(pa.timestamp(unit="us"))\n )\n # pyarrow supports a null type, so don't have to default to Int64\n expected["j"] = ArrowExtensionArray(pa.array([None, None]))\n else:\n expected = df\n unit = get_exp_unit(read_ext, engine)\n expected["i"] = expected["i"].astype(f"M8[{unit}]")\n\n tm.assert_frame_equal(result, expected)\n\n def test_dtype_backend_and_dtype(self, read_ext):\n # GH#36712\n if read_ext in (".xlsb", ".xls"):\n pytest.skip(f"No engine for filetype: '{read_ext}'")\n\n df = DataFrame({"a": [np.nan, 1.0], "b": [2.5, np.nan]})\n with tm.ensure_clean(read_ext) as file_path:\n df.to_excel(file_path, sheet_name="test", index=False)\n result = pd.read_excel(\n file_path,\n sheet_name="test",\n dtype_backend="numpy_nullable",\n dtype="float64",\n )\n tm.assert_frame_equal(result, df)\n\n def test_dtype_backend_string(self, read_ext, string_storage):\n # GH#36712\n if read_ext in (".xlsb", ".xls"):\n pytest.skip(f"No engine for filetype: '{read_ext}'")\n\n with pd.option_context("mode.string_storage", string_storage):\n df = DataFrame(\n {\n "a": np.array(["a", "b"], dtype=np.object_),\n "b": np.array(["x", pd.NA], dtype=np.object_),\n }\n )\n\n with tm.ensure_clean(read_ext) as file_path:\n df.to_excel(file_path, sheet_name="test", index=False)\n result = pd.read_excel(\n file_path, sheet_name="test", dtype_backend="numpy_nullable"\n )\n\n expected = DataFrame(\n {\n "a": Series(["a", "b"], dtype=pd.StringDtype(string_storage)),\n "b": Series(["x", None], dtype=pd.StringDtype(string_storage)),\n }\n )\n # the storage of the str columns' Index is also affected by the\n # string_storage setting -> ignore that for checking the result\n tm.assert_frame_equal(result, expected, check_column_type=False)\n\n @pytest.mark.parametrize("dtypes, exp_value", [({}, 1), ({"a.1": "int64"}, 1)])\n def test_dtype_mangle_dup_cols(self, read_ext, dtypes, exp_value):\n # GH#35211\n basename = "df_mangle_dup_col_dtypes"\n dtype_dict = {"a": object, **dtypes}\n dtype_dict_copy = dtype_dict.copy()\n # GH#42462\n result = pd.read_excel(basename + read_ext, dtype=dtype_dict)\n expected = DataFrame(\n {\n "a": Series([1], dtype=object),\n "a.1": Series([exp_value], dtype=object if not dtypes else None),\n }\n )\n assert dtype_dict == dtype_dict_copy, "dtype dict changed"\n tm.assert_frame_equal(result, expected)\n\n def test_reader_spaces(self, read_ext):\n # see gh-32207\n basename = "test_spaces"\n\n actual = pd.read_excel(basename + read_ext)\n expected = DataFrame(\n {\n "testcol": [\n "this is great",\n "4 spaces",\n "1 trailing ",\n " 1 leading",\n "2 spaces multiple times",\n ]\n }\n )\n tm.assert_frame_equal(actual, expected)\n\n # gh-36122, gh-35802\n @pytest.mark.parametrize(\n "basename,expected",\n [\n ("gh-35802", DataFrame({"COLUMN": ["Test (1)"]})),\n ("gh-36122", DataFrame(columns=["got 2nd sa"])),\n ],\n )\n def test_read_excel_ods_nested_xml(self, engine, read_ext, basename, expected):\n # see gh-35802\n if engine != "odf":\n pytest.skip(f"Skipped for engine: {engine}")\n\n actual = pd.read_excel(basename + read_ext)\n tm.assert_frame_equal(actual, expected)\n\n def test_reading_all_sheets(self, read_ext):\n # Test reading all sheet names by setting sheet_name to None,\n # Ensure a dict is returned.\n # See PR #9450\n basename = "test_multisheet"\n dfs = pd.read_excel(basename + read_ext, sheet_name=None)\n # ensure this is not alphabetical to test order preservation\n expected_keys = ["Charlie", "Alpha", "Beta"]\n tm.assert_contains_all(expected_keys, dfs.keys())\n # Issue 9930\n # Ensure sheet order is preserved\n assert expected_keys == list(dfs.keys())\n\n def test_reading_multiple_specific_sheets(self, read_ext):\n # Test reading specific sheet names by specifying a mixed list\n # of integers and strings, and confirm that duplicated sheet\n # references (positions/names) are removed properly.\n # Ensure a dict is returned\n # See PR #9450\n basename = "test_multisheet"\n # Explicitly request duplicates. Only the set should be returned.\n expected_keys = [2, "Charlie", "Charlie"]\n dfs = pd.read_excel(basename + read_ext, sheet_name=expected_keys)\n expected_keys = list(set(expected_keys))\n tm.assert_contains_all(expected_keys, dfs.keys())\n assert len(expected_keys) == len(dfs.keys())\n\n def test_reading_all_sheets_with_blank(self, read_ext):\n # Test reading all sheet names by setting sheet_name to None,\n # In the case where some sheets are blank.\n # Issue #11711\n basename = "blank_with_header"\n dfs = pd.read_excel(basename + read_ext, sheet_name=None)\n expected_keys = ["Sheet1", "Sheet2", "Sheet3"]\n tm.assert_contains_all(expected_keys, dfs.keys())\n\n # GH6403\n def test_read_excel_blank(self, read_ext):\n actual = pd.read_excel("blank" + read_ext, sheet_name="Sheet1")\n tm.assert_frame_equal(actual, DataFrame())\n\n def test_read_excel_blank_with_header(self, read_ext):\n expected = DataFrame(columns=["col_1", "col_2"])\n actual = pd.read_excel("blank_with_header" + read_ext, sheet_name="Sheet1")\n tm.assert_frame_equal(actual, expected)\n\n def test_exception_message_includes_sheet_name(self, read_ext):\n # GH 48706\n with pytest.raises(ValueError, match=r" \(sheet: Sheet1\)$"):\n pd.read_excel("blank_with_header" + read_ext, header=[1], sheet_name=None)\n with pytest.raises(ZeroDivisionError, match=r" \(sheet: Sheet1\)$"):\n pd.read_excel("test1" + read_ext, usecols=lambda x: 1 / 0, sheet_name=None)\n\n @pytest.mark.filterwarnings("ignore:Cell A4 is marked:UserWarning:openpyxl")\n def test_date_conversion_overflow(self, request, engine, read_ext):\n # GH 10001 : pandas.ExcelFile ignore parse_dates=False\n xfail_datetimes_with_pyxlsb(engine, request)\n\n expected = DataFrame(\n [\n [pd.Timestamp("2016-03-12"), "Marc Johnson"],\n [pd.Timestamp("2016-03-16"), "Jack Black"],\n [1e20, "Timothy Brown"],\n ],\n columns=["DateColWithBigInt", "StringCol"],\n )\n\n if engine == "openpyxl":\n request.applymarker(\n pytest.mark.xfail(reason="Maybe not supported by openpyxl")\n )\n\n if engine is None and read_ext in (".xlsx", ".xlsm"):\n # GH 35029\n request.applymarker(\n pytest.mark.xfail(reason="Defaults to openpyxl, maybe not supported")\n )\n\n result = pd.read_excel("testdateoverflow" + read_ext)\n tm.assert_frame_equal(result, expected)\n\n def test_sheet_name(self, request, read_ext, engine, df_ref):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n filename = "test1"\n sheet_name = "Sheet1"\n\n expected = df_ref\n adjust_expected(expected, read_ext, engine)\n\n df1 = pd.read_excel(\n filename + read_ext, sheet_name=sheet_name, index_col=0\n ) # doc\n df2 = pd.read_excel(filename + read_ext, index_col=0, sheet_name=sheet_name)\n\n tm.assert_frame_equal(df1, expected)\n tm.assert_frame_equal(df2, expected)\n\n def test_excel_read_buffer(self, read_ext):\n pth = "test1" + read_ext\n expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0)\n with open(pth, "rb") as f:\n actual = pd.read_excel(f, sheet_name="Sheet1", index_col=0)\n tm.assert_frame_equal(expected, actual)\n\n def test_bad_engine_raises(self):\n bad_engine = "foo"\n with pytest.raises(ValueError, match="Unknown engine: foo"):\n pd.read_excel("", engine=bad_engine)\n\n @pytest.mark.parametrize(\n "sheet_name",\n [3, [0, 3], [3, 0], "Sheet4", ["Sheet1", "Sheet4"], ["Sheet4", "Sheet1"]],\n )\n def test_bad_sheetname_raises(self, read_ext, sheet_name):\n # GH 39250\n msg = "Worksheet index 3 is invalid|Worksheet named 'Sheet4' not found"\n with pytest.raises(ValueError, match=msg):\n pd.read_excel("blank" + read_ext, sheet_name=sheet_name)\n\n def test_missing_file_raises(self, read_ext):\n bad_file = f"foo{read_ext}"\n # CI tests with other languages, translates to "No such file or directory"\n match = "|".join(\n [\n "(No such file or directory",\n "没有那个文件或目录",\n "File o directory non esistente)",\n ]\n )\n with pytest.raises(FileNotFoundError, match=match):\n pd.read_excel(bad_file)\n\n def test_corrupt_bytes_raises(self, engine):\n bad_stream = b"foo"\n if engine is None:\n error = ValueError\n msg = (\n "Excel file format cannot be determined, you must "\n "specify an engine manually."\n )\n elif engine == "xlrd":\n from xlrd import XLRDError\n\n error = XLRDError\n msg = (\n "Unsupported format, or corrupt file: Expected BOF "\n "record; found b'foo'"\n )\n elif engine == "calamine":\n from python_calamine import CalamineError\n\n error = CalamineError\n msg = "Cannot detect file format"\n else:\n error = BadZipFile\n msg = "File is not a zip file"\n with pytest.raises(error, match=msg):\n pd.read_excel(BytesIO(bad_stream))\n\n @pytest.mark.network\n @pytest.mark.single_cpu\n def test_read_from_http_url(self, httpserver, read_ext):\n with open("test1" + read_ext, "rb") as f:\n httpserver.serve_content(content=f.read())\n url_table = pd.read_excel(httpserver.url)\n local_table = pd.read_excel("test1" + read_ext)\n tm.assert_frame_equal(url_table, local_table)\n\n @td.skip_if_not_us_locale\n @pytest.mark.single_cpu\n def test_read_from_s3_url(self, read_ext, s3_public_bucket, s3so):\n # Bucket created in tests/io/conftest.py\n with open("test1" + read_ext, "rb") as f:\n s3_public_bucket.put_object(Key="test1" + read_ext, Body=f)\n\n url = f"s3://{s3_public_bucket.name}/test1" + read_ext\n\n url_table = pd.read_excel(url, storage_options=s3so)\n local_table = pd.read_excel("test1" + read_ext)\n tm.assert_frame_equal(url_table, local_table)\n\n @pytest.mark.single_cpu\n def test_read_from_s3_object(self, read_ext, s3_public_bucket, s3so):\n # GH 38788\n # Bucket created in tests/io/conftest.py\n with open("test1" + read_ext, "rb") as f:\n s3_public_bucket.put_object(Key="test1" + read_ext, Body=f)\n\n import s3fs\n\n s3 = s3fs.S3FileSystem(**s3so)\n\n with s3.open(f"s3://{s3_public_bucket.name}/test1" + read_ext) as f:\n url_table = pd.read_excel(f)\n\n local_table = pd.read_excel("test1" + read_ext)\n tm.assert_frame_equal(url_table, local_table)\n\n @pytest.mark.slow\n def test_read_from_file_url(self, read_ext, datapath):\n # FILE\n localtable = os.path.join(datapath("io", "data", "excel"), "test1" + read_ext)\n local_table = pd.read_excel(localtable)\n\n try:\n url_table = pd.read_excel("file://localhost/" + localtable)\n except URLError:\n # fails on some systems\n platform_info = " ".join(platform.uname()).strip()\n pytest.skip(f"failing on {platform_info}")\n\n tm.assert_frame_equal(url_table, local_table)\n\n def test_read_from_pathlib_path(self, read_ext):\n # GH12655\n str_path = "test1" + read_ext\n expected = pd.read_excel(str_path, sheet_name="Sheet1", index_col=0)\n\n path_obj = Path("test1" + read_ext)\n actual = pd.read_excel(path_obj, sheet_name="Sheet1", index_col=0)\n\n tm.assert_frame_equal(expected, actual)\n\n @td.skip_if_no("py.path")\n def test_read_from_py_localpath(self, read_ext):\n # GH12655\n from py.path import local as LocalPath\n\n str_path = os.path.join("test1" + read_ext)\n expected = pd.read_excel(str_path, sheet_name="Sheet1", index_col=0)\n\n path_obj = LocalPath().join("test1" + read_ext)\n actual = pd.read_excel(path_obj, sheet_name="Sheet1", index_col=0)\n\n tm.assert_frame_equal(expected, actual)\n\n def test_close_from_py_localpath(self, read_ext):\n # GH31467\n str_path = os.path.join("test1" + read_ext)\n with open(str_path, "rb") as f:\n x = pd.read_excel(f, sheet_name="Sheet1", index_col=0)\n del x\n # should not throw an exception because the passed file was closed\n f.read()\n\n def test_reader_seconds(self, request, engine, read_ext):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n # GH 55045\n if engine == "calamine" and read_ext == ".ods":\n request.applymarker(\n pytest.mark.xfail(\n reason="ODS file contains bad datetime (seconds as text)"\n )\n )\n\n # Test reading times with and without milliseconds. GH5945.\n expected = DataFrame.from_dict(\n {\n "Time": [\n time(1, 2, 3),\n time(2, 45, 56, 100000),\n time(4, 29, 49, 200000),\n time(6, 13, 42, 300000),\n time(7, 57, 35, 400000),\n time(9, 41, 28, 500000),\n time(11, 25, 21, 600000),\n time(13, 9, 14, 700000),\n time(14, 53, 7, 800000),\n time(16, 37, 0, 900000),\n time(18, 20, 54),\n ]\n }\n )\n\n actual = pd.read_excel("times_1900" + read_ext, sheet_name="Sheet1")\n tm.assert_frame_equal(actual, expected)\n\n actual = pd.read_excel("times_1904" + read_ext, sheet_name="Sheet1")\n tm.assert_frame_equal(actual, expected)\n\n def test_read_excel_multiindex(self, request, engine, read_ext):\n # see gh-4679\n xfail_datetimes_with_pyxlsb(engine, request)\n\n unit = get_exp_unit(read_ext, engine)\n\n mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]])\n mi_file = "testmultiindex" + read_ext\n\n # "mi_column" sheet\n expected = DataFrame(\n [\n [1, 2.5, pd.Timestamp("2015-01-01"), True],\n [2, 3.5, pd.Timestamp("2015-01-02"), False],\n [3, 4.5, pd.Timestamp("2015-01-03"), False],\n [4, 5.5, pd.Timestamp("2015-01-04"), True],\n ],\n columns=mi,\n )\n expected[mi[2]] = expected[mi[2]].astype(f"M8[{unit}]")\n\n actual = pd.read_excel(\n mi_file, sheet_name="mi_column", header=[0, 1], index_col=0\n )\n tm.assert_frame_equal(actual, expected)\n\n # "mi_index" sheet\n expected.index = mi\n expected.columns = ["a", "b", "c", "d"]\n\n actual = pd.read_excel(mi_file, sheet_name="mi_index", index_col=[0, 1])\n tm.assert_frame_equal(actual, expected)\n\n # "both" sheet\n expected.columns = mi\n\n actual = pd.read_excel(\n mi_file, sheet_name="both", index_col=[0, 1], header=[0, 1]\n )\n tm.assert_frame_equal(actual, expected)\n\n # "mi_index_name" sheet\n expected.columns = ["a", "b", "c", "d"]\n expected.index = mi.set_names(["ilvl1", "ilvl2"])\n\n actual = pd.read_excel(mi_file, sheet_name="mi_index_name", index_col=[0, 1])\n tm.assert_frame_equal(actual, expected)\n\n # "mi_column_name" sheet\n expected.index = list(range(4))\n expected.columns = mi.set_names(["c1", "c2"])\n actual = pd.read_excel(\n mi_file, sheet_name="mi_column_name", header=[0, 1], index_col=0\n )\n tm.assert_frame_equal(actual, expected)\n\n # see gh-11317\n # "name_with_int" sheet\n expected.columns = mi.set_levels([1, 2], level=1).set_names(["c1", "c2"])\n\n actual = pd.read_excel(\n mi_file, sheet_name="name_with_int", index_col=0, header=[0, 1]\n )\n tm.assert_frame_equal(actual, expected)\n\n # "both_name" sheet\n expected.columns = mi.set_names(["c1", "c2"])\n expected.index = mi.set_names(["ilvl1", "ilvl2"])\n\n actual = pd.read_excel(\n mi_file, sheet_name="both_name", index_col=[0, 1], header=[0, 1]\n )\n tm.assert_frame_equal(actual, expected)\n\n # "both_skiprows" sheet\n actual = pd.read_excel(\n mi_file,\n sheet_name="both_name_skiprows",\n index_col=[0, 1],\n header=[0, 1],\n skiprows=2,\n )\n tm.assert_frame_equal(actual, expected)\n\n @pytest.mark.parametrize(\n "sheet_name,idx_lvl2",\n [\n ("both_name_blank_after_mi_name", [np.nan, "b", "a", "b"]),\n ("both_name_multiple_blanks", [np.nan] * 4),\n ],\n )\n def test_read_excel_multiindex_blank_after_name(\n self, request, engine, read_ext, sheet_name, idx_lvl2\n ):\n # GH34673\n xfail_datetimes_with_pyxlsb(engine, request)\n\n mi_file = "testmultiindex" + read_ext\n mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]], names=["c1", "c2"])\n\n unit = get_exp_unit(read_ext, engine)\n\n expected = DataFrame(\n [\n [1, 2.5, pd.Timestamp("2015-01-01"), True],\n [2, 3.5, pd.Timestamp("2015-01-02"), False],\n [3, 4.5, pd.Timestamp("2015-01-03"), False],\n [4, 5.5, pd.Timestamp("2015-01-04"), True],\n ],\n columns=mi,\n index=MultiIndex.from_arrays(\n (["foo", "foo", "bar", "bar"], idx_lvl2),\n names=["ilvl1", "ilvl2"],\n ),\n )\n expected[mi[2]] = expected[mi[2]].astype(f"M8[{unit}]")\n result = pd.read_excel(\n mi_file,\n sheet_name=sheet_name,\n index_col=[0, 1],\n header=[0, 1],\n )\n tm.assert_frame_equal(result, expected)\n\n def test_read_excel_multiindex_header_only(self, read_ext):\n # see gh-11733.\n #\n # Don't try to parse a header name if there isn't one.\n mi_file = "testmultiindex" + read_ext\n result = pd.read_excel(mi_file, sheet_name="index_col_none", header=[0, 1])\n\n exp_columns = MultiIndex.from_product([("A", "B"), ("key", "val")])\n expected = DataFrame([[1, 2, 3, 4]] * 2, columns=exp_columns)\n tm.assert_frame_equal(result, expected)\n\n def test_excel_old_index_format(self, read_ext):\n # see gh-4679\n filename = "test_index_name_pre17" + read_ext\n\n # We detect headers to determine if index names exist, so\n # that "index" name in the "names" version of the data will\n # now be interpreted as rows that include null data.\n data = np.array(\n [\n [np.nan, np.nan, np.nan, np.nan, np.nan],\n ["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"],\n ["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"],\n ["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"],\n ["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"],\n ["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"],\n ],\n dtype=object,\n )\n columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"]\n mi = MultiIndex(\n levels=[\n ["R0", "R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"],\n ["R1", "R_l1_g0", "R_l1_g1", "R_l1_g2", "R_l1_g3", "R_l1_g4"],\n ],\n codes=[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]],\n names=[None, None],\n )\n si = Index(\n ["R0", "R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"], name=None\n )\n\n expected = DataFrame(data, index=si, columns=columns)\n\n actual = pd.read_excel(filename, sheet_name="single_names", index_col=0)\n tm.assert_frame_equal(actual, expected)\n\n expected.index = mi\n\n actual = pd.read_excel(filename, sheet_name="multi_names", index_col=[0, 1])\n tm.assert_frame_equal(actual, expected)\n\n # The analogous versions of the "names" version data\n # where there are explicitly no names for the indices.\n data = np.array(\n [\n ["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"],\n ["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"],\n ["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"],\n ["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"],\n ["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"],\n ]\n )\n columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"]\n mi = MultiIndex(\n levels=[\n ["R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"],\n ["R_l1_g0", "R_l1_g1", "R_l1_g2", "R_l1_g3", "R_l1_g4"],\n ],\n codes=[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]],\n names=[None, None],\n )\n si = Index(["R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"], name=None)\n\n expected = DataFrame(data, index=si, columns=columns)\n\n actual = pd.read_excel(filename, sheet_name="single_no_names", index_col=0)\n tm.assert_frame_equal(actual, expected)\n\n expected.index = mi\n\n actual = pd.read_excel(filename, sheet_name="multi_no_names", index_col=[0, 1])\n tm.assert_frame_equal(actual, expected)\n\n def test_read_excel_bool_header_arg(self, read_ext):\n # GH 6114\n msg = "Passing a bool to header is invalid"\n for arg in [True, False]:\n with pytest.raises(TypeError, match=msg):\n pd.read_excel("test1" + read_ext, header=arg)\n\n def test_read_excel_skiprows(self, request, engine, read_ext):\n # GH 4903\n xfail_datetimes_with_pyxlsb(engine, request)\n\n unit = get_exp_unit(read_ext, engine)\n\n actual = pd.read_excel(\n "testskiprows" + read_ext, sheet_name="skiprows_list", skiprows=[0, 2]\n )\n expected = DataFrame(\n [\n [1, 2.5, pd.Timestamp("2015-01-01"), True],\n [2, 3.5, pd.Timestamp("2015-01-02"), False],\n [3, 4.5, pd.Timestamp("2015-01-03"), False],\n [4, 5.5, pd.Timestamp("2015-01-04"), True],\n ],\n columns=["a", "b", "c", "d"],\n )\n expected["c"] = expected["c"].astype(f"M8[{unit}]")\n tm.assert_frame_equal(actual, expected)\n\n actual = pd.read_excel(\n "testskiprows" + read_ext,\n sheet_name="skiprows_list",\n skiprows=np.array([0, 2]),\n )\n tm.assert_frame_equal(actual, expected)\n\n # GH36435\n actual = pd.read_excel(\n "testskiprows" + read_ext,\n sheet_name="skiprows_list",\n skiprows=lambda x: x in [0, 2],\n )\n tm.assert_frame_equal(actual, expected)\n\n actual = pd.read_excel(\n "testskiprows" + read_ext,\n sheet_name="skiprows_list",\n skiprows=3,\n names=["a", "b", "c", "d"],\n )\n expected = DataFrame(\n [\n # [1, 2.5, pd.Timestamp("2015-01-01"), True],\n [2, 3.5, pd.Timestamp("2015-01-02"), False],\n [3, 4.5, pd.Timestamp("2015-01-03"), False],\n [4, 5.5, pd.Timestamp("2015-01-04"), True],\n ],\n columns=["a", "b", "c", "d"],\n )\n expected["c"] = expected["c"].astype(f"M8[{unit}]")\n tm.assert_frame_equal(actual, expected)\n\n def test_read_excel_skiprows_callable_not_in(self, request, engine, read_ext):\n # GH 4903\n xfail_datetimes_with_pyxlsb(engine, request)\n unit = get_exp_unit(read_ext, engine)\n\n actual = pd.read_excel(\n "testskiprows" + read_ext,\n sheet_name="skiprows_list",\n skiprows=lambda x: x not in [1, 3, 5],\n )\n expected = DataFrame(\n [\n [1, 2.5, pd.Timestamp("2015-01-01"), True],\n # [2, 3.5, pd.Timestamp("2015-01-02"), False],\n [3, 4.5, pd.Timestamp("2015-01-03"), False],\n # [4, 5.5, pd.Timestamp("2015-01-04"), True],\n ],\n columns=["a", "b", "c", "d"],\n )\n expected["c"] = expected["c"].astype(f"M8[{unit}]")\n tm.assert_frame_equal(actual, expected)\n\n def test_read_excel_nrows(self, read_ext):\n # GH 16645\n num_rows_to_pull = 5\n actual = pd.read_excel("test1" + read_ext, nrows=num_rows_to_pull)\n expected = pd.read_excel("test1" + read_ext)\n expected = expected[:num_rows_to_pull]\n tm.assert_frame_equal(actual, expected)\n\n def test_read_excel_nrows_greater_than_nrows_in_file(self, read_ext):\n # GH 16645\n expected = pd.read_excel("test1" + read_ext)\n num_records_in_file = len(expected)\n num_rows_to_pull = num_records_in_file + 10\n actual = pd.read_excel("test1" + read_ext, nrows=num_rows_to_pull)\n tm.assert_frame_equal(actual, expected)\n\n def test_read_excel_nrows_non_integer_parameter(self, read_ext):\n # GH 16645\n msg = "'nrows' must be an integer >=0"\n with pytest.raises(ValueError, match=msg):\n pd.read_excel("test1" + read_ext, nrows="5")\n\n @pytest.mark.parametrize(\n "filename,sheet_name,header,index_col,skiprows",\n [\n ("testmultiindex", "mi_column", [0, 1], 0, None),\n ("testmultiindex", "mi_index", None, [0, 1], None),\n ("testmultiindex", "both", [0, 1], [0, 1], None),\n ("testmultiindex", "mi_column_name", [0, 1], 0, None),\n ("testskiprows", "skiprows_list", None, None, [0, 2]),\n ("testskiprows", "skiprows_list", None, None, lambda x: x in (0, 2)),\n ],\n )\n def test_read_excel_nrows_params(\n self, read_ext, filename, sheet_name, header, index_col, skiprows\n ):\n """\n For various parameters, we should get the same result whether we\n limit the rows during load (nrows=3) or after (df.iloc[:3]).\n """\n # GH 46894\n expected = pd.read_excel(\n filename + read_ext,\n sheet_name=sheet_name,\n header=header,\n index_col=index_col,\n skiprows=skiprows,\n ).iloc[:3]\n actual = pd.read_excel(\n filename + read_ext,\n sheet_name=sheet_name,\n header=header,\n index_col=index_col,\n skiprows=skiprows,\n nrows=3,\n )\n tm.assert_frame_equal(actual, expected)\n\n def test_deprecated_kwargs(self, read_ext):\n with pytest.raises(TypeError, match="but 3 positional arguments"):\n pd.read_excel("test1" + read_ext, "Sheet1", 0)\n\n def test_no_header_with_list_index_col(self, read_ext):\n # GH 31783\n file_name = "testmultiindex" + read_ext\n data = [("B", "B"), ("key", "val"), (3, 4), (3, 4)]\n idx = MultiIndex.from_tuples(\n [("A", "A"), ("key", "val"), (1, 2), (1, 2)], names=(0, 1)\n )\n expected = DataFrame(data, index=idx, columns=(2, 3))\n result = pd.read_excel(\n file_name, sheet_name="index_col_none", index_col=[0, 1], header=None\n )\n tm.assert_frame_equal(expected, result)\n\n def test_one_col_noskip_blank_line(self, read_ext):\n # GH 39808\n file_name = "one_col_blank_line" + read_ext\n data = [0.5, np.nan, 1, 2]\n expected = DataFrame(data, columns=["numbers"])\n result = pd.read_excel(file_name)\n tm.assert_frame_equal(result, expected)\n\n def test_multiheader_two_blank_lines(self, read_ext):\n # GH 40442\n file_name = "testmultiindex" + read_ext\n columns = MultiIndex.from_tuples([("a", "A"), ("b", "B")])\n data = [[np.nan, np.nan], [np.nan, np.nan], [1, 3], [2, 4]]\n expected = DataFrame(data, columns=columns)\n result = pd.read_excel(\n file_name, sheet_name="mi_column_empty_rows", header=[0, 1]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_trailing_blanks(self, read_ext):\n """\n Sheets can contain blank cells with no data. Some of our readers\n were including those cells, creating many empty rows and columns\n """\n file_name = "trailing_blanks" + read_ext\n result = pd.read_excel(file_name)\n assert result.shape == (3, 3)\n\n def test_ignore_chartsheets_by_str(self, request, engine, read_ext):\n # GH 41448\n if read_ext == ".ods":\n pytest.skip("chartsheets do not exist in the ODF format")\n if engine == "pyxlsb":\n request.applymarker(\n pytest.mark.xfail(\n reason="pyxlsb can't distinguish chartsheets from worksheets"\n )\n )\n with pytest.raises(ValueError, match="Worksheet named 'Chart1' not found"):\n pd.read_excel("chartsheet" + read_ext, sheet_name="Chart1")\n\n def test_ignore_chartsheets_by_int(self, request, engine, read_ext):\n # GH 41448\n if read_ext == ".ods":\n pytest.skip("chartsheets do not exist in the ODF format")\n if engine == "pyxlsb":\n request.applymarker(\n pytest.mark.xfail(\n reason="pyxlsb can't distinguish chartsheets from worksheets"\n )\n )\n with pytest.raises(\n ValueError, match="Worksheet index 1 is invalid, 1 worksheets found"\n ):\n pd.read_excel("chartsheet" + read_ext, sheet_name=1)\n\n def test_euro_decimal_format(self, read_ext):\n # copied from read_csv\n result = pd.read_excel("test_decimal" + read_ext, decimal=",", skiprows=1)\n expected = DataFrame(\n [\n [1, 1521.1541, 187101.9543, "ABC", "poi", 4.738797819],\n [2, 121.12, 14897.76, "DEF", "uyt", 0.377320872],\n [3, 878.158, 108013.434, "GHI", "rez", 2.735694704],\n ],\n columns=["Id", "Number1", "Number2", "Text1", "Text2", "Number3"],\n )\n tm.assert_frame_equal(result, expected)\n\n\nclass TestExcelFileRead:\n def test_deprecate_bytes_input(self, engine, read_ext):\n # GH 53830\n msg = (\n "Passing bytes to 'read_excel' is deprecated and "\n "will be removed in a future version. To read from a "\n "byte string, wrap it in a `BytesIO` object."\n )\n\n with tm.assert_produces_warning(\n FutureWarning, match=msg, raise_on_extra_warnings=False\n ):\n with open("test1" + read_ext, "rb") as f:\n pd.read_excel(f.read(), engine=engine)\n\n @pytest.fixture(autouse=True)\n def cd_and_set_engine(self, engine, datapath, monkeypatch):\n """\n Change directory and set engine for ExcelFile objects.\n """\n func = partial(pd.ExcelFile, engine=engine)\n monkeypatch.chdir(datapath("io", "data", "excel"))\n monkeypatch.setattr(pd, "ExcelFile", func)\n\n def test_engine_used(self, read_ext, engine):\n expected_defaults = {\n "xlsx": "openpyxl",\n "xlsm": "openpyxl",\n "xlsb": "pyxlsb",\n "xls": "xlrd",\n "ods": "odf",\n }\n\n with pd.ExcelFile("test1" + read_ext) as excel:\n result = excel.engine\n\n if engine is not None:\n expected = engine\n else:\n expected = expected_defaults[read_ext[1:]]\n assert result == expected\n\n def test_excel_passes_na(self, read_ext):\n with pd.ExcelFile("test4" + read_ext) as excel:\n parsed = pd.read_excel(\n excel, sheet_name="Sheet1", keep_default_na=False, na_values=["apple"]\n )\n expected = DataFrame(\n [["NA"], [1], ["NA"], [np.nan], ["rabbit"]], columns=["Test"]\n )\n tm.assert_frame_equal(parsed, expected)\n\n with pd.ExcelFile("test4" + read_ext) as excel:\n parsed = pd.read_excel(\n excel, sheet_name="Sheet1", keep_default_na=True, na_values=["apple"]\n )\n expected = DataFrame(\n [[np.nan], [1], [np.nan], [np.nan], ["rabbit"]], columns=["Test"]\n )\n tm.assert_frame_equal(parsed, expected)\n\n # 13967\n with pd.ExcelFile("test5" + read_ext) as excel:\n parsed = pd.read_excel(\n excel, sheet_name="Sheet1", keep_default_na=False, na_values=["apple"]\n )\n expected = DataFrame(\n [["1.#QNAN"], [1], ["nan"], [np.nan], ["rabbit"]], columns=["Test"]\n )\n tm.assert_frame_equal(parsed, expected)\n\n with pd.ExcelFile("test5" + read_ext) as excel:\n parsed = pd.read_excel(\n excel, sheet_name="Sheet1", keep_default_na=True, na_values=["apple"]\n )\n expected = DataFrame(\n [[np.nan], [1], [np.nan], [np.nan], ["rabbit"]], columns=["Test"]\n )\n tm.assert_frame_equal(parsed, expected)\n\n @pytest.mark.parametrize("na_filter", [None, True, False])\n def test_excel_passes_na_filter(self, read_ext, na_filter):\n # gh-25453\n kwargs = {}\n\n if na_filter is not None:\n kwargs["na_filter"] = na_filter\n\n with pd.ExcelFile("test5" + read_ext) as excel:\n parsed = pd.read_excel(\n excel,\n sheet_name="Sheet1",\n keep_default_na=True,\n na_values=["apple"],\n **kwargs,\n )\n\n if na_filter is False:\n expected = [["1.#QNAN"], [1], ["nan"], ["apple"], ["rabbit"]]\n else:\n expected = [[np.nan], [1], [np.nan], [np.nan], ["rabbit"]]\n\n expected = DataFrame(expected, columns=["Test"])\n tm.assert_frame_equal(parsed, expected)\n\n def test_excel_table_sheet_by_index(self, request, engine, read_ext, df_ref):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n expected = df_ref\n adjust_expected(expected, read_ext, engine)\n\n with pd.ExcelFile("test1" + read_ext) as excel:\n df1 = pd.read_excel(excel, sheet_name=0, index_col=0)\n df2 = pd.read_excel(excel, sheet_name=1, skiprows=[1], index_col=0)\n tm.assert_frame_equal(df1, expected)\n tm.assert_frame_equal(df2, expected)\n\n with pd.ExcelFile("test1" + read_ext) as excel:\n df1 = excel.parse(0, index_col=0)\n df2 = excel.parse(1, skiprows=[1], index_col=0)\n tm.assert_frame_equal(df1, expected)\n tm.assert_frame_equal(df2, expected)\n\n with pd.ExcelFile("test1" + read_ext) as excel:\n df3 = pd.read_excel(excel, sheet_name=0, index_col=0, skipfooter=1)\n tm.assert_frame_equal(df3, df1.iloc[:-1])\n\n with pd.ExcelFile("test1" + read_ext) as excel:\n df3 = excel.parse(0, index_col=0, skipfooter=1)\n\n tm.assert_frame_equal(df3, df1.iloc[:-1])\n\n def test_sheet_name(self, request, engine, read_ext, df_ref):\n xfail_datetimes_with_pyxlsb(engine, request)\n\n expected = df_ref\n adjust_expected(expected, read_ext, engine)\n\n filename = "test1"\n sheet_name = "Sheet1"\n\n with pd.ExcelFile(filename + read_ext) as excel:\n df1_parse = excel.parse(sheet_name=sheet_name, index_col=0) # doc\n\n with pd.ExcelFile(filename + read_ext) as excel:\n df2_parse = excel.parse(index_col=0, sheet_name=sheet_name)\n\n tm.assert_frame_equal(df1_parse, expected)\n tm.assert_frame_equal(df2_parse, expected)\n\n @pytest.mark.parametrize(\n "sheet_name",\n [3, [0, 3], [3, 0], "Sheet4", ["Sheet1", "Sheet4"], ["Sheet4", "Sheet1"]],\n )\n def test_bad_sheetname_raises(self, read_ext, sheet_name):\n # GH 39250\n msg = "Worksheet index 3 is invalid|Worksheet named 'Sheet4' not found"\n with pytest.raises(ValueError, match=msg):\n with pd.ExcelFile("blank" + read_ext) as excel:\n excel.parse(sheet_name=sheet_name)\n\n def test_excel_read_buffer(self, engine, read_ext):\n pth = "test1" + read_ext\n expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0, engine=engine)\n\n with open(pth, "rb") as f:\n with pd.ExcelFile(f) as xls:\n actual = pd.read_excel(xls, sheet_name="Sheet1", index_col=0)\n\n tm.assert_frame_equal(expected, actual)\n\n def test_reader_closes_file(self, engine, read_ext):\n with open("test1" + read_ext, "rb") as f:\n with pd.ExcelFile(f) as xlsx:\n # parses okay\n pd.read_excel(xlsx, sheet_name="Sheet1", index_col=0, engine=engine)\n\n assert f.closed\n\n def test_conflicting_excel_engines(self, read_ext):\n # GH 26566\n msg = "Engine should not be specified when passing an ExcelFile"\n\n with pd.ExcelFile("test1" + read_ext) as xl:\n with pytest.raises(ValueError, match=msg):\n pd.read_excel(xl, engine="foo")\n\n def test_excel_read_binary(self, engine, read_ext):\n # GH 15914\n expected = pd.read_excel("test1" + read_ext, engine=engine)\n\n with open("test1" + read_ext, "rb") as f:\n data = f.read()\n\n actual = pd.read_excel(BytesIO(data), engine=engine)\n tm.assert_frame_equal(expected, actual)\n\n def test_excel_read_binary_via_read_excel(self, read_ext, engine):\n # GH 38424\n with open("test1" + read_ext, "rb") as f:\n result = pd.read_excel(f, engine=engine)\n expected = pd.read_excel("test1" + read_ext, engine=engine)\n tm.assert_frame_equal(result, expected)\n\n def test_read_excel_header_index_out_of_range(self, engine):\n # GH#43143\n with open("df_header_oob.xlsx", "rb") as f:\n with pytest.raises(ValueError, match="exceeds maximum"):\n pd.read_excel(f, header=[0, 1])\n\n @pytest.mark.parametrize("filename", ["df_empty.xlsx", "df_equals.xlsx"])\n def test_header_with_index_col(self, filename):\n # GH 33476\n idx = Index(["Z"], name="I2")\n cols = MultiIndex.from_tuples([("A", "B"), ("A", "B.1")], names=["I11", "I12"])\n expected = DataFrame([[1, 3]], index=idx, columns=cols, dtype="int64")\n result = pd.read_excel(\n filename, sheet_name="Sheet1", index_col=0, header=[0, 1]\n )\n tm.assert_frame_equal(expected, result)\n\n def test_read_datetime_multiindex(self, request, engine, read_ext):\n # GH 34748\n xfail_datetimes_with_pyxlsb(engine, request)\n\n f = "test_datetime_mi" + read_ext\n with pd.ExcelFile(f) as excel:\n actual = pd.read_excel(excel, header=[0, 1], index_col=0, engine=engine)\n\n unit = get_exp_unit(read_ext, engine)\n dti = pd.DatetimeIndex(["2020-02-29", "2020-03-01"], dtype=f"M8[{unit}]")\n expected_column_index = MultiIndex.from_arrays(\n [dti[:1], dti[1:]],\n names=[\n dti[0].to_pydatetime(),\n dti[1].to_pydatetime(),\n ],\n )\n expected = DataFrame([], index=[], columns=expected_column_index)\n\n tm.assert_frame_equal(expected, actual)\n\n def test_engine_invalid_option(self, read_ext):\n # read_ext includes the '.' hence the weird formatting\n with pytest.raises(ValueError, match="Value must be one of *"):\n with pd.option_context(f"io.excel{read_ext}.reader", "abc"):\n pass\n\n def test_ignore_chartsheets(self, request, engine, read_ext):\n # GH 41448\n if read_ext == ".ods":\n pytest.skip("chartsheets do not exist in the ODF format")\n if engine == "pyxlsb":\n request.applymarker(\n pytest.mark.xfail(\n reason="pyxlsb can't distinguish chartsheets from worksheets"\n )\n )\n with pd.ExcelFile("chartsheet" + read_ext) as excel:\n assert excel.sheet_names == ["Sheet1"]\n\n def test_corrupt_files_closed(self, engine, read_ext):\n # GH41778\n errors = (BadZipFile,)\n if engine is None:\n pytest.skip(f"Invalid test for engine={engine}")\n elif engine == "xlrd":\n import xlrd\n\n errors = (BadZipFile, xlrd.biffh.XLRDError)\n elif engine == "calamine":\n from python_calamine import CalamineError\n\n errors = (CalamineError,)\n\n with tm.ensure_clean(f"corrupt{read_ext}") as file:\n Path(file).write_text("corrupt", encoding="utf-8")\n with tm.assert_produces_warning(False):\n try:\n pd.ExcelFile(file, engine=engine)\n except errors:\n pass\n
.venv\Lib\site-packages\pandas\tests\io\excel\test_readers.py
test_readers.py
Python
62,778
0.75
0.094524
0.0818
vue-tools
91
2025-01-06T21:19:28.067668
GPL-3.0
true
d72eaae76bb4875ef1f22243adfb367b
import contextlib\nimport time\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n DataFrame,\n read_excel,\n)\nimport pandas._testing as tm\n\nfrom pandas.io.excel import ExcelWriter\nfrom pandas.io.formats.excel import ExcelFormatter\n\npytest.importorskip("jinja2")\n# jinja2 is currently required for Styler.__init__(). Technically Styler.to_excel\n# could compute styles and render to excel without jinja2, since there is no\n# 'template' file, but this needs the import error to delayed until render time.\n\nif is_platform_windows():\n pytestmark = pytest.mark.single_cpu\n\n\ndef assert_equal_cell_styles(cell1, cell2):\n # TODO: should find a better way to check equality\n assert cell1.alignment.__dict__ == cell2.alignment.__dict__\n assert cell1.border.__dict__ == cell2.border.__dict__\n assert cell1.fill.__dict__ == cell2.fill.__dict__\n assert cell1.font.__dict__ == cell2.font.__dict__\n assert cell1.number_format == cell2.number_format\n assert cell1.protection.__dict__ == cell2.protection.__dict__\n\n\n@pytest.mark.parametrize(\n "engine",\n ["xlsxwriter", "openpyxl"],\n)\ndef test_styler_to_excel_unstyled(engine):\n # compare DataFrame.to_excel and Styler.to_excel when no styles applied\n pytest.importorskip(engine)\n df = DataFrame(np.random.default_rng(2).standard_normal((2, 2)))\n with tm.ensure_clean(".xlsx") as path:\n with ExcelWriter(path, engine=engine) as writer:\n df.to_excel(writer, sheet_name="dataframe")\n df.style.to_excel(writer, sheet_name="unstyled")\n\n openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl\n with contextlib.closing(openpyxl.load_workbook(path)) as wb:\n for col1, col2 in zip(wb["dataframe"].columns, wb["unstyled"].columns):\n assert len(col1) == len(col2)\n for cell1, cell2 in zip(col1, col2):\n assert cell1.value == cell2.value\n assert_equal_cell_styles(cell1, cell2)\n\n\nshared_style_params = [\n (\n "background-color: #111222",\n ["fill", "fgColor", "rgb"],\n {"xlsxwriter": "FF111222", "openpyxl": "00111222"},\n ),\n (\n "color: #111222",\n ["font", "color", "value"],\n {"xlsxwriter": "FF111222", "openpyxl": "00111222"},\n ),\n ("font-family: Arial;", ["font", "name"], "arial"),\n ("font-weight: bold;", ["font", "b"], True),\n ("font-style: italic;", ["font", "i"], True),\n ("text-decoration: underline;", ["font", "u"], "single"),\n ("number-format: $??,???.00;", ["number_format"], "$??,???.00"),\n ("text-align: left;", ["alignment", "horizontal"], "left"),\n (\n "vertical-align: bottom;",\n ["alignment", "vertical"],\n {"xlsxwriter": None, "openpyxl": "bottom"}, # xlsxwriter Fails\n ),\n ("vertical-align: middle;", ["alignment", "vertical"], "center"),\n # Border widths\n ("border-left: 2pt solid red", ["border", "left", "style"], "medium"),\n ("border-left: 1pt dotted red", ["border", "left", "style"], "dotted"),\n ("border-left: 2pt dotted red", ["border", "left", "style"], "mediumDashDotDot"),\n ("border-left: 1pt dashed red", ["border", "left", "style"], "dashed"),\n ("border-left: 2pt dashed red", ["border", "left", "style"], "mediumDashed"),\n ("border-left: 1pt solid red", ["border", "left", "style"], "thin"),\n ("border-left: 3pt solid red", ["border", "left", "style"], "thick"),\n # Border expansion\n (\n "border-left: 2pt solid #111222",\n ["border", "left", "color", "rgb"],\n {"xlsxwriter": "FF111222", "openpyxl": "00111222"},\n ),\n ("border: 1pt solid red", ["border", "top", "style"], "thin"),\n (\n "border: 1pt solid #111222",\n ["border", "top", "color", "rgb"],\n {"xlsxwriter": "FF111222", "openpyxl": "00111222"},\n ),\n ("border: 1pt solid red", ["border", "right", "style"], "thin"),\n (\n "border: 1pt solid #111222",\n ["border", "right", "color", "rgb"],\n {"xlsxwriter": "FF111222", "openpyxl": "00111222"},\n ),\n ("border: 1pt solid red", ["border", "bottom", "style"], "thin"),\n (\n "border: 1pt solid #111222",\n ["border", "bottom", "color", "rgb"],\n {"xlsxwriter": "FF111222", "openpyxl": "00111222"},\n ),\n ("border: 1pt solid red", ["border", "left", "style"], "thin"),\n (\n "border: 1pt solid #111222",\n ["border", "left", "color", "rgb"],\n {"xlsxwriter": "FF111222", "openpyxl": "00111222"},\n ),\n # Border styles\n (\n "border-left-style: hair; border-left-color: black",\n ["border", "left", "style"],\n "hair",\n ),\n]\n\n\n@pytest.mark.parametrize(\n "engine",\n ["xlsxwriter", "openpyxl"],\n)\n@pytest.mark.parametrize("css, attrs, expected", shared_style_params)\ndef test_styler_to_excel_basic(engine, css, attrs, expected):\n pytest.importorskip(engine)\n df = DataFrame(np.random.default_rng(2).standard_normal((1, 1)))\n styler = df.style.map(lambda x: css)\n\n with tm.ensure_clean(".xlsx") as path:\n with ExcelWriter(path, engine=engine) as writer:\n df.to_excel(writer, sheet_name="dataframe")\n styler.to_excel(writer, sheet_name="styled")\n\n openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl\n with contextlib.closing(openpyxl.load_workbook(path)) as wb:\n # test unstyled data cell does not have expected styles\n # test styled cell has expected styles\n u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2)\n for attr in attrs:\n u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr)\n\n if isinstance(expected, dict):\n assert u_cell is None or u_cell != expected[engine]\n assert s_cell == expected[engine]\n else:\n assert u_cell is None or u_cell != expected\n assert s_cell == expected\n\n\n@pytest.mark.parametrize(\n "engine",\n ["xlsxwriter", "openpyxl"],\n)\n@pytest.mark.parametrize("css, attrs, expected", shared_style_params)\ndef test_styler_to_excel_basic_indexes(engine, css, attrs, expected):\n pytest.importorskip(engine)\n df = DataFrame(np.random.default_rng(2).standard_normal((1, 1)))\n\n styler = df.style\n styler.map_index(lambda x: css, axis=0)\n styler.map_index(lambda x: css, axis=1)\n\n null_styler = df.style\n null_styler.map(lambda x: "null: css;")\n null_styler.map_index(lambda x: "null: css;", axis=0)\n null_styler.map_index(lambda x: "null: css;", axis=1)\n\n with tm.ensure_clean(".xlsx") as path:\n with ExcelWriter(path, engine=engine) as writer:\n null_styler.to_excel(writer, sheet_name="null_styled")\n styler.to_excel(writer, sheet_name="styled")\n\n openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl\n with contextlib.closing(openpyxl.load_workbook(path)) as wb:\n # test null styled index cells does not have expected styles\n # test styled cell has expected styles\n ui_cell, si_cell = wb["null_styled"].cell(2, 1), wb["styled"].cell(2, 1)\n uc_cell, sc_cell = wb["null_styled"].cell(1, 2), wb["styled"].cell(1, 2)\n for attr in attrs:\n ui_cell, si_cell = getattr(ui_cell, attr, None), getattr(si_cell, attr)\n uc_cell, sc_cell = getattr(uc_cell, attr, None), getattr(sc_cell, attr)\n\n if isinstance(expected, dict):\n assert ui_cell is None or ui_cell != expected[engine]\n assert si_cell == expected[engine]\n assert uc_cell is None or uc_cell != expected[engine]\n assert sc_cell == expected[engine]\n else:\n assert ui_cell is None or ui_cell != expected\n assert si_cell == expected\n assert uc_cell is None or uc_cell != expected\n assert sc_cell == expected\n\n\n# From https://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles.borders.html\n# Note: Leaving behavior of "width"-type styles undefined; user should use border-width\n# instead\nexcel_border_styles = [\n # "thin",\n "dashed",\n "mediumDashDot",\n "dashDotDot",\n "hair",\n "dotted",\n "mediumDashDotDot",\n # "medium",\n "double",\n "dashDot",\n "slantDashDot",\n # "thick",\n "mediumDashed",\n]\n\n\n@pytest.mark.parametrize(\n "engine",\n ["xlsxwriter", "openpyxl"],\n)\n@pytest.mark.parametrize("border_style", excel_border_styles)\ndef test_styler_to_excel_border_style(engine, border_style):\n css = f"border-left: {border_style} black thin"\n attrs = ["border", "left", "style"]\n expected = border_style\n\n pytest.importorskip(engine)\n df = DataFrame(np.random.default_rng(2).standard_normal((1, 1)))\n styler = df.style.map(lambda x: css)\n\n with tm.ensure_clean(".xlsx") as path:\n with ExcelWriter(path, engine=engine) as writer:\n df.to_excel(writer, sheet_name="dataframe")\n styler.to_excel(writer, sheet_name="styled")\n\n openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl\n with contextlib.closing(openpyxl.load_workbook(path)) as wb:\n # test unstyled data cell does not have expected styles\n # test styled cell has expected styles\n u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2)\n for attr in attrs:\n u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr)\n\n if isinstance(expected, dict):\n assert u_cell is None or u_cell != expected[engine]\n assert s_cell == expected[engine]\n else:\n assert u_cell is None or u_cell != expected\n assert s_cell == expected\n\n\ndef test_styler_custom_converter():\n openpyxl = pytest.importorskip("openpyxl")\n\n def custom_converter(css):\n return {"font": {"color": {"rgb": "111222"}}}\n\n df = DataFrame(np.random.default_rng(2).standard_normal((1, 1)))\n styler = df.style.map(lambda x: "color: #888999")\n with tm.ensure_clean(".xlsx") as path:\n with ExcelWriter(path, engine="openpyxl") as writer:\n ExcelFormatter(styler, style_converter=custom_converter).write(\n writer, sheet_name="custom"\n )\n\n with contextlib.closing(openpyxl.load_workbook(path)) as wb:\n assert wb["custom"].cell(2, 2).font.color.value == "00111222"\n\n\n@pytest.mark.single_cpu\n@td.skip_if_not_us_locale\ndef test_styler_to_s3(s3_public_bucket, s3so):\n # GH#46381\n\n mock_bucket_name, target_file = s3_public_bucket.name, "test.xlsx"\n df = DataFrame({"x": [1, 2, 3], "y": [2, 4, 6]})\n styler = df.style.set_sticky(axis="index")\n styler.to_excel(f"s3://{mock_bucket_name}/{target_file}", storage_options=s3so)\n timeout = 5\n while True:\n if target_file in (obj.key for obj in s3_public_bucket.objects.all()):\n break\n time.sleep(0.1)\n timeout -= 0.1\n assert timeout > 0, "Timed out waiting for file to appear on moto"\n result = read_excel(\n f"s3://{mock_bucket_name}/{target_file}", index_col=0, storage_options=s3so\n )\n tm.assert_frame_equal(result, df)\n
.venv\Lib\site-packages\pandas\tests\io\excel\test_style.py
test_style.py
Python
11,284
0.95
0.073826
0.081712
python-kit
201
2024-08-18T12:39:44.400780
BSD-3-Clause
true
8b3fd2d74aabda055e10cb0c112b8244
from datetime import (\n date,\n datetime,\n timedelta,\n)\nfrom functools import partial\nfrom io import BytesIO\nimport os\nimport re\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\nfrom pandas.compat._constants import PY310\nfrom pandas.compat._optional import import_optional_dependency\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n date_range,\n option_context,\n)\nimport pandas._testing as tm\n\nfrom pandas.io.excel import (\n ExcelFile,\n ExcelWriter,\n _OpenpyxlWriter,\n _XlsxWriter,\n register_writer,\n)\nfrom pandas.io.excel._util import _writers\n\nif is_platform_windows():\n pytestmark = pytest.mark.single_cpu\n\n\ndef get_exp_unit(path: str) -> str:\n return "ns"\n\n\n@pytest.fixture\ndef frame(float_frame):\n """\n Returns the first ten items in fixture "float_frame".\n """\n return float_frame[:10]\n\n\n@pytest.fixture(params=[True, False])\ndef merge_cells(request):\n return request.param\n\n\n@pytest.fixture\ndef path(ext):\n """\n Fixture to open file for use in each test case.\n """\n with tm.ensure_clean(ext) as file_path:\n yield file_path\n\n\n@pytest.fixture\ndef set_engine(engine, ext):\n """\n Fixture to set engine for use in each test case.\n\n Rather than requiring `engine=...` to be provided explicitly as an\n argument in each test, this fixture sets a global option to dictate\n which engine should be used to write Excel files. After executing\n the test it rolls back said change to the global option.\n """\n option_name = f"io.excel.{ext.strip('.')}.writer"\n with option_context(option_name, engine):\n yield\n\n\n@pytest.mark.parametrize(\n "ext",\n [\n pytest.param(".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]),\n pytest.param(".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]),\n pytest.param(\n ".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")]\n ),\n pytest.param(".ods", marks=td.skip_if_no("odf")),\n ],\n)\nclass TestRoundTrip:\n @pytest.mark.parametrize(\n "header,expected",\n [(None, DataFrame([np.nan] * 4)), (0, DataFrame({"Unnamed: 0": [np.nan] * 3}))],\n )\n def test_read_one_empty_col_no_header(self, ext, header, expected):\n # xref gh-12292\n filename = "no_header"\n df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]])\n\n with tm.ensure_clean(ext) as path:\n df.to_excel(path, sheet_name=filename, index=False, header=False)\n result = pd.read_excel(\n path, sheet_name=filename, usecols=[0], header=header\n )\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "header,expected",\n [(None, DataFrame([0] + [np.nan] * 4)), (0, DataFrame([np.nan] * 4))],\n )\n def test_read_one_empty_col_with_header(self, ext, header, expected):\n filename = "with_header"\n df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]])\n\n with tm.ensure_clean(ext) as path:\n df.to_excel(path, sheet_name="with_header", index=False, header=True)\n result = pd.read_excel(\n path, sheet_name=filename, usecols=[0], header=header\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_set_column_names_in_parameter(self, ext):\n # GH 12870 : pass down column names associated with\n # keyword argument names\n refdf = DataFrame([[1, "foo"], [2, "bar"], [3, "baz"]], columns=["a", "b"])\n\n with tm.ensure_clean(ext) as pth:\n with ExcelWriter(pth) as writer:\n refdf.to_excel(\n writer, sheet_name="Data_no_head", header=False, index=False\n )\n refdf.to_excel(writer, sheet_name="Data_with_head", index=False)\n\n refdf.columns = ["A", "B"]\n\n with ExcelFile(pth) as reader:\n xlsdf_no_head = pd.read_excel(\n reader, sheet_name="Data_no_head", header=None, names=["A", "B"]\n )\n xlsdf_with_head = pd.read_excel(\n reader,\n sheet_name="Data_with_head",\n index_col=None,\n names=["A", "B"],\n )\n\n tm.assert_frame_equal(xlsdf_no_head, refdf)\n tm.assert_frame_equal(xlsdf_with_head, refdf)\n\n def test_creating_and_reading_multiple_sheets(self, ext):\n # see gh-9450\n #\n # Test reading multiple sheets, from a runtime\n # created Excel file with multiple sheets.\n def tdf(col_sheet_name):\n d, i = [11, 22, 33], [1, 2, 3]\n return DataFrame(d, i, columns=[col_sheet_name])\n\n sheets = ["AAA", "BBB", "CCC"]\n\n dfs = [tdf(s) for s in sheets]\n dfs = dict(zip(sheets, dfs))\n\n with tm.ensure_clean(ext) as pth:\n with ExcelWriter(pth) as ew:\n for sheetname, df in dfs.items():\n df.to_excel(ew, sheet_name=sheetname)\n\n dfs_returned = pd.read_excel(pth, sheet_name=sheets, index_col=0)\n\n for s in sheets:\n tm.assert_frame_equal(dfs[s], dfs_returned[s])\n\n def test_read_excel_multiindex_empty_level(self, ext):\n # see gh-12453\n with tm.ensure_clean(ext) as path:\n df = DataFrame(\n {\n ("One", "x"): {0: 1},\n ("Two", "X"): {0: 3},\n ("Two", "Y"): {0: 7},\n ("Zero", ""): {0: 0},\n }\n )\n\n expected = DataFrame(\n {\n ("One", "x"): {0: 1},\n ("Two", "X"): {0: 3},\n ("Two", "Y"): {0: 7},\n ("Zero", "Unnamed: 4_level_1"): {0: 0},\n }\n )\n\n df.to_excel(path)\n actual = pd.read_excel(path, header=[0, 1], index_col=0)\n tm.assert_frame_equal(actual, expected)\n\n df = DataFrame(\n {\n ("Beg", ""): {0: 0},\n ("Middle", "x"): {0: 1},\n ("Tail", "X"): {0: 3},\n ("Tail", "Y"): {0: 7},\n }\n )\n\n expected = DataFrame(\n {\n ("Beg", "Unnamed: 1_level_1"): {0: 0},\n ("Middle", "x"): {0: 1},\n ("Tail", "X"): {0: 3},\n ("Tail", "Y"): {0: 7},\n }\n )\n\n df.to_excel(path)\n actual = pd.read_excel(path, header=[0, 1], index_col=0)\n tm.assert_frame_equal(actual, expected)\n\n @pytest.mark.parametrize("c_idx_names", ["a", None])\n @pytest.mark.parametrize("r_idx_names", ["b", None])\n @pytest.mark.parametrize("c_idx_levels", [1, 3])\n @pytest.mark.parametrize("r_idx_levels", [1, 3])\n def test_excel_multindex_roundtrip(\n self, ext, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels, request\n ):\n # see gh-4679\n with tm.ensure_clean(ext) as pth:\n # Empty name case current read in as\n # unnamed levels, not Nones.\n check_names = bool(r_idx_names) or r_idx_levels <= 1\n\n if c_idx_levels == 1:\n columns = Index(list("abcde"))\n else:\n columns = MultiIndex.from_arrays(\n [range(5) for _ in range(c_idx_levels)],\n names=[f"{c_idx_names}-{i}" for i in range(c_idx_levels)],\n )\n if r_idx_levels == 1:\n index = Index(list("ghijk"))\n else:\n index = MultiIndex.from_arrays(\n [range(5) for _ in range(r_idx_levels)],\n names=[f"{r_idx_names}-{i}" for i in range(r_idx_levels)],\n )\n df = DataFrame(\n 1.1 * np.ones((5, 5)),\n columns=columns,\n index=index,\n )\n df.to_excel(pth)\n\n act = pd.read_excel(\n pth,\n index_col=list(range(r_idx_levels)),\n header=list(range(c_idx_levels)),\n )\n tm.assert_frame_equal(df, act, check_names=check_names)\n\n df.iloc[0, :] = np.nan\n df.to_excel(pth)\n\n act = pd.read_excel(\n pth,\n index_col=list(range(r_idx_levels)),\n header=list(range(c_idx_levels)),\n )\n tm.assert_frame_equal(df, act, check_names=check_names)\n\n df.iloc[-1, :] = np.nan\n df.to_excel(pth)\n act = pd.read_excel(\n pth,\n index_col=list(range(r_idx_levels)),\n header=list(range(c_idx_levels)),\n )\n tm.assert_frame_equal(df, act, check_names=check_names)\n\n def test_read_excel_parse_dates(self, ext):\n # see gh-11544, gh-12051\n df = DataFrame(\n {"col": [1, 2, 3], "date_strings": date_range("2012-01-01", periods=3)}\n )\n df2 = df.copy()\n df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y")\n\n with tm.ensure_clean(ext) as pth:\n df2.to_excel(pth)\n\n res = pd.read_excel(pth, index_col=0)\n tm.assert_frame_equal(df2, res)\n\n res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0)\n tm.assert_frame_equal(df, res)\n\n date_parser = lambda x: datetime.strptime(x, "%m/%d/%Y")\n with tm.assert_produces_warning(\n FutureWarning,\n match="use 'date_format' instead",\n raise_on_extra_warnings=False,\n ):\n res = pd.read_excel(\n pth,\n parse_dates=["date_strings"],\n date_parser=date_parser,\n index_col=0,\n )\n tm.assert_frame_equal(df, res)\n res = pd.read_excel(\n pth, parse_dates=["date_strings"], date_format="%m/%d/%Y", index_col=0\n )\n tm.assert_frame_equal(df, res)\n\n def test_multiindex_interval_datetimes(self, ext):\n # GH 30986\n midx = MultiIndex.from_arrays(\n [\n range(4),\n pd.interval_range(\n start=pd.Timestamp("2020-01-01"), periods=4, freq="6ME"\n ),\n ]\n )\n df = DataFrame(range(4), index=midx)\n with tm.ensure_clean(ext) as pth:\n df.to_excel(pth)\n result = pd.read_excel(pth, index_col=[0, 1])\n expected = DataFrame(\n range(4),\n MultiIndex.from_arrays(\n [\n range(4),\n [\n "(2020-01-31 00:00:00, 2020-07-31 00:00:00]",\n "(2020-07-31 00:00:00, 2021-01-31 00:00:00]",\n "(2021-01-31 00:00:00, 2021-07-31 00:00:00]",\n "(2021-07-31 00:00:00, 2022-01-31 00:00:00]",\n ],\n ]\n ),\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "engine,ext",\n [\n pytest.param(\n "openpyxl",\n ".xlsx",\n marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")],\n ),\n pytest.param(\n "openpyxl",\n ".xlsm",\n marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")],\n ),\n pytest.param(\n "xlsxwriter",\n ".xlsx",\n marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")],\n ),\n pytest.param("odf", ".ods", marks=td.skip_if_no("odf")),\n ],\n)\n@pytest.mark.usefixtures("set_engine")\nclass TestExcelWriter:\n def test_excel_sheet_size(self, path):\n # GH 26080\n breaking_row_count = 2**20 + 1\n breaking_col_count = 2**14 + 1\n # purposely using two arrays to prevent memory issues while testing\n row_arr = np.zeros(shape=(breaking_row_count, 1))\n col_arr = np.zeros(shape=(1, breaking_col_count))\n row_df = DataFrame(row_arr)\n col_df = DataFrame(col_arr)\n\n msg = "sheet is too large"\n with pytest.raises(ValueError, match=msg):\n row_df.to_excel(path)\n\n with pytest.raises(ValueError, match=msg):\n col_df.to_excel(path)\n\n def test_excel_sheet_by_name_raise(self, path):\n gt = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))\n gt.to_excel(path)\n\n with ExcelFile(path) as xl:\n df = pd.read_excel(xl, sheet_name=0, index_col=0)\n\n tm.assert_frame_equal(gt, df)\n\n msg = "Worksheet named '0' not found"\n with pytest.raises(ValueError, match=msg):\n pd.read_excel(xl, "0")\n\n def test_excel_writer_context_manager(self, frame, path):\n with ExcelWriter(path) as writer:\n frame.to_excel(writer, sheet_name="Data1")\n frame2 = frame.copy()\n frame2.columns = frame.columns[::-1]\n frame2.to_excel(writer, sheet_name="Data2")\n\n with ExcelFile(path) as reader:\n found_df = pd.read_excel(reader, sheet_name="Data1", index_col=0)\n found_df2 = pd.read_excel(reader, sheet_name="Data2", index_col=0)\n\n tm.assert_frame_equal(found_df, frame)\n tm.assert_frame_equal(found_df2, frame2)\n\n def test_roundtrip(self, frame, path):\n frame = frame.copy()\n frame.iloc[:5, frame.columns.get_loc("A")] = np.nan\n\n frame.to_excel(path, sheet_name="test1")\n frame.to_excel(path, sheet_name="test1", columns=["A", "B"])\n frame.to_excel(path, sheet_name="test1", header=False)\n frame.to_excel(path, sheet_name="test1", index=False)\n\n # test roundtrip\n frame.to_excel(path, sheet_name="test1")\n recons = pd.read_excel(path, sheet_name="test1", index_col=0)\n tm.assert_frame_equal(frame, recons)\n\n frame.to_excel(path, sheet_name="test1", index=False)\n recons = pd.read_excel(path, sheet_name="test1", index_col=None)\n recons.index = frame.index\n tm.assert_frame_equal(frame, recons)\n\n frame.to_excel(path, sheet_name="test1", na_rep="NA")\n recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["NA"])\n tm.assert_frame_equal(frame, recons)\n\n # GH 3611\n frame.to_excel(path, sheet_name="test1", na_rep="88")\n recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["88"])\n tm.assert_frame_equal(frame, recons)\n\n frame.to_excel(path, sheet_name="test1", na_rep="88")\n recons = pd.read_excel(\n path, sheet_name="test1", index_col=0, na_values=[88, 88.0]\n )\n tm.assert_frame_equal(frame, recons)\n\n # GH 6573\n frame.to_excel(path, sheet_name="Sheet1")\n recons = pd.read_excel(path, index_col=0)\n tm.assert_frame_equal(frame, recons)\n\n frame.to_excel(path, sheet_name="0")\n recons = pd.read_excel(path, index_col=0)\n tm.assert_frame_equal(frame, recons)\n\n # GH 8825 Pandas Series should provide to_excel method\n s = frame["A"]\n s.to_excel(path)\n recons = pd.read_excel(path, index_col=0)\n tm.assert_frame_equal(s.to_frame(), recons)\n\n def test_mixed(self, frame, path):\n mixed_frame = frame.copy()\n mixed_frame["foo"] = "bar"\n\n mixed_frame.to_excel(path, sheet_name="test1")\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0)\n tm.assert_frame_equal(mixed_frame, recons)\n\n def test_ts_frame(self, path):\n unit = get_exp_unit(path)\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 4)),\n columns=Index(list("ABCD")),\n index=date_range("2000-01-01", periods=5, freq="B"),\n )\n\n # freq doesn't round-trip\n index = pd.DatetimeIndex(np.asarray(df.index), freq=None)\n df.index = index\n\n expected = df[:]\n expected.index = expected.index.as_unit(unit)\n\n df.to_excel(path, sheet_name="test1")\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0)\n tm.assert_frame_equal(expected, recons)\n\n def test_basics_with_nan(self, frame, path):\n frame = frame.copy()\n frame.iloc[:5, frame.columns.get_loc("A")] = np.nan\n frame.to_excel(path, sheet_name="test1")\n frame.to_excel(path, sheet_name="test1", columns=["A", "B"])\n frame.to_excel(path, sheet_name="test1", header=False)\n frame.to_excel(path, sheet_name="test1", index=False)\n\n @pytest.mark.parametrize("np_type", [np.int8, np.int16, np.int32, np.int64])\n def test_int_types(self, np_type, path):\n # Test np.int values read come back as int\n # (rather than float which is Excel's format).\n df = DataFrame(\n np.random.default_rng(2).integers(-10, 10, size=(10, 2)), dtype=np_type\n )\n df.to_excel(path, sheet_name="test1")\n\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0)\n\n int_frame = df.astype(np.int64)\n tm.assert_frame_equal(int_frame, recons)\n\n recons2 = pd.read_excel(path, sheet_name="test1", index_col=0)\n tm.assert_frame_equal(int_frame, recons2)\n\n @pytest.mark.parametrize("np_type", [np.float16, np.float32, np.float64])\n def test_float_types(self, np_type, path):\n # Test np.float values read come back as float.\n df = DataFrame(np.random.default_rng(2).random(10), dtype=np_type)\n df.to_excel(path, sheet_name="test1")\n\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(\n np_type\n )\n\n tm.assert_frame_equal(df, recons)\n\n def test_bool_types(self, path):\n # Test np.bool_ values read come back as float.\n df = DataFrame([1, 0, True, False], dtype=np.bool_)\n df.to_excel(path, sheet_name="test1")\n\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(\n np.bool_\n )\n\n tm.assert_frame_equal(df, recons)\n\n def test_inf_roundtrip(self, path):\n df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)])\n df.to_excel(path, sheet_name="test1")\n\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0)\n\n tm.assert_frame_equal(df, recons)\n\n def test_sheets(self, frame, path):\n # freq doesn't round-trip\n unit = get_exp_unit(path)\n tsframe = DataFrame(\n np.random.default_rng(2).standard_normal((5, 4)),\n columns=Index(list("ABCD")),\n index=date_range("2000-01-01", periods=5, freq="B"),\n )\n index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None)\n tsframe.index = index\n\n expected = tsframe[:]\n expected.index = expected.index.as_unit(unit)\n\n frame = frame.copy()\n frame.iloc[:5, frame.columns.get_loc("A")] = np.nan\n\n frame.to_excel(path, sheet_name="test1")\n frame.to_excel(path, sheet_name="test1", columns=["A", "B"])\n frame.to_excel(path, sheet_name="test1", header=False)\n frame.to_excel(path, sheet_name="test1", index=False)\n\n # Test writing to separate sheets\n with ExcelWriter(path) as writer:\n frame.to_excel(writer, sheet_name="test1")\n tsframe.to_excel(writer, sheet_name="test2")\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0)\n tm.assert_frame_equal(frame, recons)\n recons = pd.read_excel(reader, sheet_name="test2", index_col=0)\n tm.assert_frame_equal(expected, recons)\n assert 2 == len(reader.sheet_names)\n assert "test1" == reader.sheet_names[0]\n assert "test2" == reader.sheet_names[1]\n\n def test_colaliases(self, frame, path):\n frame = frame.copy()\n frame.iloc[:5, frame.columns.get_loc("A")] = np.nan\n\n frame.to_excel(path, sheet_name="test1")\n frame.to_excel(path, sheet_name="test1", columns=["A", "B"])\n frame.to_excel(path, sheet_name="test1", header=False)\n frame.to_excel(path, sheet_name="test1", index=False)\n\n # column aliases\n col_aliases = Index(["AA", "X", "Y", "Z"])\n frame.to_excel(path, sheet_name="test1", header=col_aliases)\n with ExcelFile(path) as reader:\n rs = pd.read_excel(reader, sheet_name="test1", index_col=0)\n xp = frame.copy()\n xp.columns = col_aliases\n tm.assert_frame_equal(xp, rs)\n\n def test_roundtrip_indexlabels(self, merge_cells, frame, path):\n frame = frame.copy()\n frame.iloc[:5, frame.columns.get_loc("A")] = np.nan\n\n frame.to_excel(path, sheet_name="test1")\n frame.to_excel(path, sheet_name="test1", columns=["A", "B"])\n frame.to_excel(path, sheet_name="test1", header=False)\n frame.to_excel(path, sheet_name="test1", index=False)\n\n # test index_label\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0\n df.to_excel(\n path, sheet_name="test1", index_label=["test"], merge_cells=merge_cells\n )\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(\n np.int64\n )\n df.index.names = ["test"]\n assert df.index.names == recons.index.names\n\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0\n df.to_excel(\n path,\n sheet_name="test1",\n index_label=["test", "dummy", "dummy2"],\n merge_cells=merge_cells,\n )\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(\n np.int64\n )\n df.index.names = ["test"]\n assert df.index.names == recons.index.names\n\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) >= 0\n df.to_excel(\n path, sheet_name="test1", index_label="test", merge_cells=merge_cells\n )\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(\n np.int64\n )\n df.index.names = ["test"]\n tm.assert_frame_equal(df, recons.astype(bool))\n\n frame.to_excel(\n path,\n sheet_name="test1",\n columns=["A", "B", "C", "D"],\n index=False,\n merge_cells=merge_cells,\n )\n # take 'A' and 'B' as indexes (same row as cols 'C', 'D')\n df = frame.copy()\n df = df.set_index(["A", "B"])\n\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])\n tm.assert_frame_equal(df, recons)\n\n def test_excel_roundtrip_indexname(self, merge_cells, path):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))\n df.index.name = "foo"\n\n df.to_excel(path, merge_cells=merge_cells)\n\n with ExcelFile(path) as xf:\n result = pd.read_excel(xf, sheet_name=xf.sheet_names[0], index_col=0)\n\n tm.assert_frame_equal(result, df)\n assert result.index.name == "foo"\n\n def test_excel_roundtrip_datetime(self, merge_cells, path):\n # datetime.date, not sure what to test here exactly\n unit = get_exp_unit(path)\n\n # freq does not round-trip\n tsframe = DataFrame(\n np.random.default_rng(2).standard_normal((5, 4)),\n columns=Index(list("ABCD")),\n index=date_range("2000-01-01", periods=5, freq="B"),\n )\n index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None)\n tsframe.index = index\n\n tsf = tsframe.copy()\n\n tsf.index = [x.date() for x in tsframe.index]\n tsf.to_excel(path, sheet_name="test1", merge_cells=merge_cells)\n\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0)\n\n expected = tsframe[:]\n expected.index = expected.index.as_unit(unit)\n tm.assert_frame_equal(expected, recons)\n\n def test_excel_date_datetime_format(self, ext, path):\n # see gh-4133\n #\n # Excel output format strings\n unit = get_exp_unit(path)\n\n df = DataFrame(\n [\n [date(2014, 1, 31), date(1999, 9, 24)],\n [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],\n ],\n index=["DATE", "DATETIME"],\n columns=["X", "Y"],\n )\n df_expected = DataFrame(\n [\n [datetime(2014, 1, 31), datetime(1999, 9, 24)],\n [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],\n ],\n index=["DATE", "DATETIME"],\n columns=["X", "Y"],\n )\n df_expected = df_expected.astype(f"M8[{unit}]")\n\n with tm.ensure_clean(ext) as filename2:\n with ExcelWriter(path) as writer1:\n df.to_excel(writer1, sheet_name="test1")\n\n with ExcelWriter(\n filename2,\n date_format="DD.MM.YYYY",\n datetime_format="DD.MM.YYYY HH-MM-SS",\n ) as writer2:\n df.to_excel(writer2, sheet_name="test1")\n\n with ExcelFile(path) as reader1:\n rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0)\n\n with ExcelFile(filename2) as reader2:\n rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0)\n\n tm.assert_frame_equal(rs1, rs2)\n\n # Since the reader returns a datetime object for dates,\n # we need to use df_expected to check the result.\n tm.assert_frame_equal(rs2, df_expected)\n\n @pytest.mark.filterwarnings(\n "ignore:invalid value encountered in cast:RuntimeWarning"\n )\n def test_to_excel_interval_no_labels(self, path, using_infer_string):\n # see gh-19242\n #\n # Test writing Interval without labels.\n df = DataFrame(\n np.random.default_rng(2).integers(-10, 10, size=(20, 1)), dtype=np.int64\n )\n expected = df.copy()\n\n df["new"] = pd.cut(df[0], 10)\n expected["new"] = pd.cut(expected[0], 10).astype(\n str if not using_infer_string else "str"\n )\n\n df.to_excel(path, sheet_name="test1")\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0)\n tm.assert_frame_equal(expected, recons)\n\n def test_to_excel_interval_labels(self, path):\n # see gh-19242\n #\n # Test writing Interval with labels.\n df = DataFrame(\n np.random.default_rng(2).integers(-10, 10, size=(20, 1)), dtype=np.int64\n )\n expected = df.copy()\n intervals = pd.cut(\n df[0], 10, labels=["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]\n )\n df["new"] = intervals\n expected["new"] = pd.Series(list(intervals))\n\n df.to_excel(path, sheet_name="test1")\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0)\n tm.assert_frame_equal(expected, recons)\n\n def test_to_excel_timedelta(self, path):\n # see gh-19242, gh-9155\n #\n # Test writing timedelta to xls.\n df = DataFrame(\n np.random.default_rng(2).integers(-10, 10, size=(20, 1)),\n columns=["A"],\n dtype=np.int64,\n )\n expected = df.copy()\n\n df["new"] = df["A"].apply(lambda x: timedelta(seconds=x))\n expected["new"] = expected["A"].apply(\n lambda x: timedelta(seconds=x).total_seconds() / 86400\n )\n\n df.to_excel(path, sheet_name="test1")\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=0)\n tm.assert_frame_equal(expected, recons)\n\n def test_to_excel_periodindex(self, path):\n # xp has a PeriodIndex\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 4)),\n columns=Index(list("ABCD")),\n index=date_range("2000-01-01", periods=5, freq="B"),\n )\n xp = df.resample("ME").mean().to_period("M")\n\n xp.to_excel(path, sheet_name="sht1")\n\n with ExcelFile(path) as reader:\n rs = pd.read_excel(reader, sheet_name="sht1", index_col=0)\n tm.assert_frame_equal(xp, rs.to_period("M"))\n\n def test_to_excel_multiindex(self, merge_cells, frame, path):\n arrays = np.arange(len(frame.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 frame.to_excel(path, sheet_name="test1", header=False)\n frame.to_excel(path, sheet_name="test1", columns=["A", "B"])\n\n # round trip\n frame.to_excel(path, sheet_name="test1", merge_cells=merge_cells)\n with ExcelFile(path) as reader:\n df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])\n tm.assert_frame_equal(frame, df)\n\n # GH13511\n def test_to_excel_multiindex_nan_label(self, merge_cells, path):\n df = DataFrame(\n {\n "A": [None, 2, 3],\n "B": [10, 20, 30],\n "C": np.random.default_rng(2).random(3),\n }\n )\n df = df.set_index(["A", "B"])\n\n df.to_excel(path, merge_cells=merge_cells)\n df1 = pd.read_excel(path, index_col=[0, 1])\n tm.assert_frame_equal(df, df1)\n\n # Test for Issue 11328. If column indices are integers, make\n # sure they are handled correctly for either setting of\n # merge_cells\n def test_to_excel_multiindex_cols(self, merge_cells, frame, path):\n arrays = np.arange(len(frame.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 new_cols_index = MultiIndex.from_tuples([(40, 1), (40, 2), (50, 1), (50, 2)])\n frame.columns = new_cols_index\n header = [0, 1]\n if not merge_cells:\n header = 0\n\n # round trip\n frame.to_excel(path, sheet_name="test1", merge_cells=merge_cells)\n with ExcelFile(path) as reader:\n df = pd.read_excel(\n reader, sheet_name="test1", header=header, index_col=[0, 1]\n )\n if not merge_cells:\n fm = frame.columns._format_multi(sparsify=False, include_names=False)\n frame.columns = [".".join(map(str, q)) for q in zip(*fm)]\n tm.assert_frame_equal(frame, df)\n\n def test_to_excel_multiindex_dates(self, merge_cells, path):\n # try multiindex with dates\n unit = get_exp_unit(path)\n tsframe = DataFrame(\n np.random.default_rng(2).standard_normal((5, 4)),\n columns=Index(list("ABCD")),\n index=date_range("2000-01-01", periods=5, freq="B"),\n )\n tsframe.index = MultiIndex.from_arrays(\n [\n tsframe.index.as_unit(unit),\n np.arange(len(tsframe.index), dtype=np.int64),\n ],\n names=["time", "foo"],\n )\n\n tsframe.to_excel(path, sheet_name="test1", merge_cells=merge_cells)\n with ExcelFile(path) as reader:\n recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])\n\n tm.assert_frame_equal(tsframe, recons)\n assert recons.index.names == ("time", "foo")\n\n def test_to_excel_multiindex_no_write_index(self, path):\n # Test writing and re-reading a MI without the index. GH 5616.\n\n # Initial non-MI frame.\n frame1 = DataFrame({"a": [10, 20], "b": [30, 40], "c": [50, 60]})\n\n # Add a MI.\n frame2 = frame1.copy()\n multi_index = MultiIndex.from_tuples([(70, 80), (90, 100)])\n frame2.index = multi_index\n\n # Write out to Excel without the index.\n frame2.to_excel(path, sheet_name="test1", index=False)\n\n # Read it back in.\n with ExcelFile(path) as reader:\n frame3 = pd.read_excel(reader, sheet_name="test1")\n\n # Test that it is the same as the initial frame.\n tm.assert_frame_equal(frame1, frame3)\n\n def test_to_excel_empty_multiindex(self, path):\n # GH 19543.\n expected = DataFrame([], columns=[0, 1, 2])\n\n df = DataFrame([], index=MultiIndex.from_tuples([], names=[0, 1]), columns=[2])\n df.to_excel(path, sheet_name="test1")\n\n with ExcelFile(path) as reader:\n result = pd.read_excel(reader, sheet_name="test1")\n tm.assert_frame_equal(\n result, expected, check_index_type=False, check_dtype=False\n )\n\n def test_to_excel_float_format(self, path):\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 df.to_excel(path, sheet_name="test1", float_format="%.2f")\n\n with ExcelFile(path) as reader:\n result = pd.read_excel(reader, sheet_name="test1", index_col=0)\n\n expected = 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(result, expected)\n\n def test_to_excel_output_encoding(self, ext):\n # Avoid mixed inferred_type.\n df = DataFrame(\n [["\u0192", "\u0193", "\u0194"], ["\u0195", "\u0196", "\u0197"]],\n index=["A\u0192", "B"],\n columns=["X\u0193", "Y", "Z"],\n )\n\n with tm.ensure_clean("__tmp_to_excel_float_format__." + ext) as filename:\n df.to_excel(filename, sheet_name="TestSheet")\n result = pd.read_excel(filename, sheet_name="TestSheet", index_col=0)\n tm.assert_frame_equal(result, df)\n\n def test_to_excel_unicode_filename(self, ext):\n with tm.ensure_clean("\u0192u." + ext) as filename:\n try:\n with open(filename, "wb"):\n pass\n except UnicodeEncodeError:\n pytest.skip("No unicode file names on this system")\n\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 df.to_excel(filename, sheet_name="test1", float_format="%.2f")\n\n with ExcelFile(filename) as reader:\n result = pd.read_excel(reader, sheet_name="test1", index_col=0)\n\n expected = 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(result, expected)\n\n @pytest.mark.parametrize("use_headers", [True, False])\n @pytest.mark.parametrize("r_idx_nlevels", [1, 2, 3])\n @pytest.mark.parametrize("c_idx_nlevels", [1, 2, 3])\n def test_excel_010_hemstring(\n self, merge_cells, c_idx_nlevels, r_idx_nlevels, use_headers, path\n ):\n def roundtrip(data, header=True, parser_hdr=0, index=True):\n data.to_excel(path, header=header, merge_cells=merge_cells, index=index)\n\n with ExcelFile(path) as xf:\n return pd.read_excel(\n xf, sheet_name=xf.sheet_names[0], header=parser_hdr\n )\n\n # Basic test.\n parser_header = 0 if use_headers else None\n res = roundtrip(DataFrame([0]), use_headers, parser_header)\n\n assert res.shape == (1, 2)\n assert res.iloc[0, 0] is not np.nan\n\n # More complex tests with multi-index.\n nrows = 5\n ncols = 3\n\n # ensure limited functionality in 0.10\n # override of gh-2370 until sorted out in 0.11\n\n if c_idx_nlevels == 1:\n columns = Index([f"a-{i}" for i in range(ncols)], dtype=object)\n else:\n columns = MultiIndex.from_arrays(\n [range(ncols) for _ in range(c_idx_nlevels)],\n names=[f"i-{i}" for i in range(c_idx_nlevels)],\n )\n if r_idx_nlevels == 1:\n index = Index([f"b-{i}" for i in range(nrows)], dtype=object)\n else:\n index = MultiIndex.from_arrays(\n [range(nrows) for _ in range(r_idx_nlevels)],\n names=[f"j-{i}" for i in range(r_idx_nlevels)],\n )\n\n df = DataFrame(\n np.ones((nrows, ncols)),\n columns=columns,\n index=index,\n )\n\n # This if will be removed once multi-column Excel writing\n # is implemented. For now fixing gh-9794.\n if c_idx_nlevels > 1:\n msg = (\n "Writing to Excel with MultiIndex columns and no index "\n "\\('index'=False\\) is not yet implemented."\n )\n with pytest.raises(NotImplementedError, match=msg):\n roundtrip(df, use_headers, index=False)\n else:\n res = roundtrip(df, use_headers)\n\n if use_headers:\n assert res.shape == (nrows, ncols + r_idx_nlevels)\n else:\n # First row taken as columns.\n assert res.shape == (nrows - 1, ncols + r_idx_nlevels)\n\n # No NaNs.\n for r in range(len(res.index)):\n for c in range(len(res.columns)):\n assert res.iloc[r, c] is not np.nan\n\n def test_duplicated_columns(self, path):\n # see gh-5235\n df = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B"])\n df.to_excel(path, sheet_name="test1")\n expected = DataFrame(\n [[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B.1"]\n )\n\n # By default, we mangle.\n result = pd.read_excel(path, sheet_name="test1", index_col=0)\n tm.assert_frame_equal(result, expected)\n\n # see gh-11007, gh-10970\n df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A", "B"])\n df.to_excel(path, sheet_name="test1")\n\n result = pd.read_excel(path, sheet_name="test1", index_col=0)\n expected = DataFrame(\n [[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A.1", "B.1"]\n )\n tm.assert_frame_equal(result, expected)\n\n # see gh-10982\n df.to_excel(path, sheet_name="test1", index=False, header=False)\n result = pd.read_excel(path, sheet_name="test1", header=None)\n\n expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])\n tm.assert_frame_equal(result, expected)\n\n def test_swapped_columns(self, path):\n # Test for issue #5427.\n write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]})\n write_frame.to_excel(path, sheet_name="test1", columns=["B", "A"])\n\n read_frame = pd.read_excel(path, sheet_name="test1", header=0)\n\n tm.assert_series_equal(write_frame["A"], read_frame["A"])\n tm.assert_series_equal(write_frame["B"], read_frame["B"])\n\n def test_invalid_columns(self, path):\n # see gh-10982\n write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]})\n\n with pytest.raises(KeyError, match="Not all names specified"):\n write_frame.to_excel(path, sheet_name="test1", columns=["B", "C"])\n\n with pytest.raises(\n KeyError, match="'passes columns are not ALL present dataframe'"\n ):\n write_frame.to_excel(path, sheet_name="test1", columns=["C", "D"])\n\n @pytest.mark.parametrize(\n "to_excel_index,read_excel_index_col",\n [\n (True, 0), # Include index in write to file\n (False, None), # Dont include index in write to file\n ],\n )\n def test_write_subset_columns(self, path, to_excel_index, read_excel_index_col):\n # GH 31677\n write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2], "C": [3, 3, 3]})\n write_frame.to_excel(\n path, sheet_name="col_subset_bug", columns=["A", "B"], index=to_excel_index\n )\n\n expected = write_frame[["A", "B"]]\n read_frame = pd.read_excel(\n path, sheet_name="col_subset_bug", index_col=read_excel_index_col\n )\n\n tm.assert_frame_equal(expected, read_frame)\n\n def test_comment_arg(self, path):\n # see gh-18735\n #\n # Test the comment argument functionality to pd.read_excel.\n\n # Create file to read in.\n df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]})\n df.to_excel(path, sheet_name="test_c")\n\n # Read file without comment arg.\n result1 = pd.read_excel(path, sheet_name="test_c", index_col=0)\n\n result1.iloc[1, 0] = None\n result1.iloc[1, 1] = None\n result1.iloc[2, 1] = None\n\n result2 = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0)\n tm.assert_frame_equal(result1, result2)\n\n def test_comment_default(self, path):\n # Re issue #18735\n # Test the comment argument default to pd.read_excel\n\n # Create file to read in\n df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]})\n df.to_excel(path, sheet_name="test_c")\n\n # Read file with default and explicit comment=None\n result1 = pd.read_excel(path, sheet_name="test_c")\n result2 = pd.read_excel(path, sheet_name="test_c", comment=None)\n tm.assert_frame_equal(result1, result2)\n\n def test_comment_used(self, path):\n # see gh-18735\n #\n # Test the comment argument is working as expected when used.\n\n # Create file to read in.\n df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]})\n df.to_excel(path, sheet_name="test_c")\n\n # Test read_frame_comment against manually produced expected output.\n expected = DataFrame({"A": ["one", None, "one"], "B": ["two", None, None]})\n result = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0)\n tm.assert_frame_equal(result, expected)\n\n def test_comment_empty_line(self, path):\n # Re issue #18735\n # Test that pd.read_excel ignores commented lines at the end of file\n\n df = DataFrame({"a": ["1", "#2"], "b": ["2", "3"]})\n df.to_excel(path, index=False)\n\n # Test that all-comment lines at EoF are ignored\n expected = DataFrame({"a": [1], "b": [2]})\n result = pd.read_excel(path, comment="#")\n tm.assert_frame_equal(result, expected)\n\n def test_datetimes(self, path):\n # Test writing and reading datetimes. For issue #9139. (xref #9185)\n unit = get_exp_unit(path)\n datetimes = [\n datetime(2013, 1, 13, 1, 2, 3),\n datetime(2013, 1, 13, 2, 45, 56),\n datetime(2013, 1, 13, 4, 29, 49),\n datetime(2013, 1, 13, 6, 13, 42),\n datetime(2013, 1, 13, 7, 57, 35),\n datetime(2013, 1, 13, 9, 41, 28),\n datetime(2013, 1, 13, 11, 25, 21),\n datetime(2013, 1, 13, 13, 9, 14),\n datetime(2013, 1, 13, 14, 53, 7),\n datetime(2013, 1, 13, 16, 37, 0),\n datetime(2013, 1, 13, 18, 20, 52),\n ]\n\n write_frame = DataFrame({"A": datetimes})\n write_frame.to_excel(path, sheet_name="Sheet1")\n read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0)\n\n expected = write_frame.astype(f"M8[{unit}]")\n tm.assert_series_equal(expected["A"], read_frame["A"])\n\n def test_bytes_io(self, engine):\n # see gh-7074\n with BytesIO() as bio:\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))\n\n # Pass engine explicitly, as there is no file path to infer from.\n with ExcelWriter(bio, engine=engine) as writer:\n df.to_excel(writer)\n\n bio.seek(0)\n reread_df = pd.read_excel(bio, index_col=0)\n tm.assert_frame_equal(df, reread_df)\n\n def test_engine_kwargs(self, engine, path):\n # GH#52368\n df = DataFrame([{"A": 1, "B": 2}, {"A": 3, "B": 4}])\n\n msgs = {\n "odf": r"OpenDocumentSpreadsheet() got an unexpected keyword "\n r"argument 'foo'",\n "openpyxl": r"__init__() got an unexpected keyword argument 'foo'",\n "xlsxwriter": r"__init__() got an unexpected keyword argument 'foo'",\n }\n\n if PY310:\n msgs[\n "openpyxl"\n ] = "Workbook.__init__() got an unexpected keyword argument 'foo'"\n msgs[\n "xlsxwriter"\n ] = "Workbook.__init__() got an unexpected keyword argument 'foo'"\n\n # Handle change in error message for openpyxl (write and append mode)\n if engine == "openpyxl" and not os.path.exists(path):\n msgs[\n "openpyxl"\n ] = r"load_workbook() got an unexpected keyword argument 'foo'"\n\n with pytest.raises(TypeError, match=re.escape(msgs[engine])):\n df.to_excel(\n path,\n engine=engine,\n engine_kwargs={"foo": "bar"},\n )\n\n def test_write_lists_dict(self, path):\n # see gh-8188.\n df = DataFrame(\n {\n "mixed": ["a", ["b", "c"], {"d": "e", "f": 2}],\n "numeric": [1, 2, 3.0],\n "str": ["apple", "banana", "cherry"],\n }\n )\n df.to_excel(path, sheet_name="Sheet1")\n read = pd.read_excel(path, sheet_name="Sheet1", header=0, index_col=0)\n\n expected = df.copy()\n expected.mixed = expected.mixed.apply(str)\n expected.numeric = expected.numeric.astype("int64")\n\n tm.assert_frame_equal(read, expected)\n\n def test_render_as_column_name(self, path):\n # see gh-34331\n df = DataFrame({"render": [1, 2], "data": [3, 4]})\n df.to_excel(path, sheet_name="Sheet1")\n read = pd.read_excel(path, "Sheet1", index_col=0)\n expected = df\n tm.assert_frame_equal(read, expected)\n\n def test_true_and_false_value_options(self, path):\n # see gh-13347\n df = DataFrame([["foo", "bar"]], columns=["col1", "col2"], dtype=object)\n with option_context("future.no_silent_downcasting", True):\n expected = df.replace({"foo": True, "bar": False}).astype("bool")\n\n df.to_excel(path)\n read_frame = pd.read_excel(\n path, true_values=["foo"], false_values=["bar"], index_col=0\n )\n tm.assert_frame_equal(read_frame, expected)\n\n def test_freeze_panes(self, path):\n # see gh-15160\n expected = DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"])\n expected.to_excel(path, sheet_name="Sheet1", freeze_panes=(1, 1))\n\n result = pd.read_excel(path, index_col=0)\n tm.assert_frame_equal(result, expected)\n\n def test_path_path_lib(self, engine, ext):\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD")),\n index=Index([f"i-{i}" for i in range(30)]),\n )\n writer = partial(df.to_excel, engine=engine)\n\n reader = partial(pd.read_excel, index_col=0)\n result = tm.round_trip_pathlib(writer, reader, path=f"foo{ext}")\n tm.assert_frame_equal(result, df)\n\n def test_path_local_path(self, engine, ext):\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD")),\n index=Index([f"i-{i}" for i in range(30)]),\n )\n writer = partial(df.to_excel, engine=engine)\n\n reader = partial(pd.read_excel, index_col=0)\n result = tm.round_trip_localpath(writer, reader, path=f"foo{ext}")\n tm.assert_frame_equal(result, df)\n\n def test_merged_cell_custom_objects(self, path):\n # see GH-27006\n mi = MultiIndex.from_tuples(\n [\n (pd.Period("2018"), pd.Period("2018Q1")),\n (pd.Period("2018"), pd.Period("2018Q2")),\n ]\n )\n expected = DataFrame(np.ones((2, 2), dtype="int64"), columns=mi)\n expected.to_excel(path)\n result = pd.read_excel(path, header=[0, 1], index_col=0)\n # need to convert PeriodIndexes to standard Indexes for assert equal\n expected.columns = expected.columns.set_levels(\n [[str(i) for i in mi.levels[0]], [str(i) for i in mi.levels[1]]],\n level=[0, 1],\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("dtype", [None, object])\n def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path):\n # GH 27008, GH 7056\n tz = tz_aware_fixture\n data = pd.Timestamp("2019", tz=tz)\n df = DataFrame([data], dtype=dtype)\n with pytest.raises(ValueError, match="Excel does not support"):\n df.to_excel(path)\n\n data = data.to_pydatetime()\n df = DataFrame([data], dtype=dtype)\n with pytest.raises(ValueError, match="Excel does not support"):\n df.to_excel(path)\n\n def test_excel_duplicate_columns_with_names(self, path):\n # GH#39695\n df = DataFrame({"A": [0, 1], "B": [10, 11]})\n df.to_excel(path, columns=["A", "B", "A"], index=False)\n\n result = pd.read_excel(path)\n expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"])\n tm.assert_frame_equal(result, expected)\n\n def test_if_sheet_exists_raises(self, ext):\n # GH 40230\n msg = "if_sheet_exists is only valid in append mode (mode='a')"\n\n with tm.ensure_clean(ext) as f:\n with pytest.raises(ValueError, match=re.escape(msg)):\n ExcelWriter(f, if_sheet_exists="replace")\n\n def test_excel_writer_empty_frame(self, engine, ext):\n # GH#45793\n with tm.ensure_clean(ext) as path:\n with ExcelWriter(path, engine=engine) as writer:\n DataFrame().to_excel(writer)\n result = pd.read_excel(path)\n expected = DataFrame()\n tm.assert_frame_equal(result, expected)\n\n def test_to_excel_empty_frame(self, engine, ext):\n # GH#45793\n with tm.ensure_clean(ext) as path:\n DataFrame().to_excel(path, engine=engine)\n result = pd.read_excel(path)\n expected = DataFrame()\n tm.assert_frame_equal(result, expected)\n\n\nclass TestExcelWriterEngineTests:\n @pytest.mark.parametrize(\n "klass,ext",\n [\n pytest.param(_XlsxWriter, ".xlsx", marks=td.skip_if_no("xlsxwriter")),\n pytest.param(_OpenpyxlWriter, ".xlsx", marks=td.skip_if_no("openpyxl")),\n ],\n )\n def test_ExcelWriter_dispatch(self, klass, ext):\n with tm.ensure_clean(ext) as path:\n with ExcelWriter(path) as writer:\n if ext == ".xlsx" and bool(\n import_optional_dependency("xlsxwriter", errors="ignore")\n ):\n # xlsxwriter has preference over openpyxl if both installed\n assert isinstance(writer, _XlsxWriter)\n else:\n assert isinstance(writer, klass)\n\n def test_ExcelWriter_dispatch_raises(self):\n with pytest.raises(ValueError, match="No engine"):\n ExcelWriter("nothing")\n\n def test_register_writer(self):\n class DummyClass(ExcelWriter):\n called_save = False\n called_write_cells = False\n called_sheets = False\n _supported_extensions = ("xlsx", "xls")\n _engine = "dummy"\n\n def book(self):\n pass\n\n def _save(self):\n type(self).called_save = True\n\n def _write_cells(self, *args, **kwargs):\n type(self).called_write_cells = True\n\n @property\n def sheets(self):\n type(self).called_sheets = True\n\n @classmethod\n def assert_called_and_reset(cls):\n assert cls.called_save\n assert cls.called_write_cells\n assert not cls.called_sheets\n cls.called_save = False\n cls.called_write_cells = False\n\n register_writer(DummyClass)\n\n with option_context("io.excel.xlsx.writer", "dummy"):\n path = "something.xlsx"\n with tm.ensure_clean(path) as filepath:\n with ExcelWriter(filepath) as writer:\n assert isinstance(writer, DummyClass)\n df = DataFrame(\n ["a"],\n columns=Index(["b"], name="foo"),\n index=Index(["c"], name="bar"),\n )\n df.to_excel(filepath)\n DummyClass.assert_called_and_reset()\n\n with tm.ensure_clean("something.xls") as filepath:\n df.to_excel(filepath, engine="dummy")\n DummyClass.assert_called_and_reset()\n\n\n@td.skip_if_no("xlrd")\n@td.skip_if_no("openpyxl")\nclass TestFSPath:\n def test_excelfile_fspath(self):\n with tm.ensure_clean("foo.xlsx") as path:\n df = DataFrame({"A": [1, 2]})\n df.to_excel(path)\n with ExcelFile(path) as xl:\n result = os.fspath(xl)\n assert result == path\n\n def test_excelwriter_fspath(self):\n with tm.ensure_clean("foo.xlsx") as path:\n with ExcelWriter(path) as writer:\n assert os.fspath(writer) == str(path)\n\n def test_to_excel_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_excel except "\n r"for the argument 'excel_writer' will be keyword-only."\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n buf = BytesIO()\n writer = ExcelWriter(buf)\n df.to_excel(writer, "Sheet_name_1")\n\n\n@pytest.mark.parametrize("klass", _writers.values())\ndef test_subclass_attr(klass):\n # testing that subclasses of ExcelWriter don't have public attributes (issue 49602)\n attrs_base = {name for name in dir(ExcelWriter) if not name.startswith("_")}\n attrs_klass = {name for name in dir(klass) if not name.startswith("_")}\n assert not attrs_base.symmetric_difference(attrs_klass)\n
.venv\Lib\site-packages\pandas\tests\io\excel\test_writers.py
test_writers.py
Python
54,972
0.75
0.09181
0.08903
node-utils
968
2023-11-15T06:39:55.816038
GPL-3.0
true
4851f69c0c477d564a835d57491ac635
import io\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\n\nimport pandas as pd\nimport pandas._testing as tm\n\nfrom pandas.io.excel import ExcelFile\nfrom pandas.io.excel._base import inspect_excel_format\n\nxlrd = pytest.importorskip("xlrd")\n\nif is_platform_windows():\n pytestmark = pytest.mark.single_cpu\n\n\n@pytest.fixture(params=[".xls"])\ndef read_ext_xlrd(request):\n """\n Valid extensions for reading Excel files with xlrd.\n\n Similar to read_ext, but excludes .ods, .xlsb, and for xlrd>2 .xlsx, .xlsm\n """\n return request.param\n\n\ndef test_read_xlrd_book(read_ext_xlrd, datapath):\n engine = "xlrd"\n sheet_name = "Sheet1"\n pth = datapath("io", "data", "excel", "test1.xls")\n with xlrd.open_workbook(pth) as book:\n with ExcelFile(book, engine=engine) as xl:\n result = pd.read_excel(xl, sheet_name=sheet_name, index_col=0)\n\n expected = pd.read_excel(\n book, sheet_name=sheet_name, engine=engine, index_col=0\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_read_xlsx_fails(datapath):\n # GH 29375\n from xlrd.biffh import XLRDError\n\n path = datapath("io", "data", "excel", "test1.xlsx")\n with pytest.raises(XLRDError, match="Excel xlsx file; not supported"):\n pd.read_excel(path, engine="xlrd")\n\n\ndef test_nan_in_xls(datapath):\n # GH 54564\n path = datapath("io", "data", "excel", "test6.xls")\n\n expected = pd.DataFrame({0: np.r_[0, 2].astype("int64"), 1: np.r_[1, np.nan]})\n\n result = pd.read_excel(path, header=None)\n\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "file_header",\n [\n b"\x09\x00\x04\x00\x07\x00\x10\x00",\n b"\x09\x02\x06\x00\x00\x00\x10\x00",\n b"\x09\x04\x06\x00\x00\x00\x10\x00",\n b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1",\n ],\n)\ndef test_read_old_xls_files(file_header):\n # GH 41226\n f = io.BytesIO(file_header)\n assert inspect_excel_format(f) == "xls"\n
.venv\Lib\site-packages\pandas\tests\io\excel\test_xlrd.py
test_xlrd.py
Python
1,977
0.95
0.105263
0.055556
vue-tools
864
2024-06-27T01:41:13.107829
Apache-2.0
true
a169f6de8fbdb316efea13f25d428fdf
import contextlib\n\nimport pytest\n\nfrom pandas.compat import is_platform_windows\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\nfrom pandas.io.excel import ExcelWriter\n\nxlsxwriter = pytest.importorskip("xlsxwriter")\n\nif is_platform_windows():\n pytestmark = pytest.mark.single_cpu\n\n\n@pytest.fixture\ndef ext():\n return ".xlsx"\n\n\ndef test_column_format(ext):\n # Test that column formats are applied to cells. Test for issue #9167.\n # Applicable to xlsxwriter only.\n openpyxl = pytest.importorskip("openpyxl")\n\n with tm.ensure_clean(ext) as path:\n frame = DataFrame({"A": [123456, 123456], "B": [123456, 123456]})\n\n with ExcelWriter(path) as writer:\n frame.to_excel(writer)\n\n # Add a number format to col B and ensure it is applied to cells.\n num_format = "#,##0"\n write_workbook = writer.book\n write_worksheet = write_workbook.worksheets()[0]\n col_format = write_workbook.add_format({"num_format": num_format})\n write_worksheet.set_column("B:B", None, col_format)\n\n with contextlib.closing(openpyxl.load_workbook(path)) as read_workbook:\n try:\n read_worksheet = read_workbook["Sheet1"]\n except TypeError:\n # compat\n read_worksheet = read_workbook.get_sheet_by_name(name="Sheet1")\n\n # Get the number format from the cell.\n try:\n cell = read_worksheet["B2"]\n except TypeError:\n # compat\n cell = read_worksheet.cell("B2")\n\n try:\n read_num_format = cell.number_format\n except AttributeError:\n read_num_format = cell.style.number_format._format_code\n\n assert read_num_format == num_format\n\n\ndef test_write_append_mode_raises(ext):\n msg = "Append mode is not supported with xlsxwriter!"\n\n with tm.ensure_clean(ext) as f:\n with pytest.raises(ValueError, match=msg):\n ExcelWriter(f, engine="xlsxwriter", mode="a")\n\n\n@pytest.mark.parametrize("nan_inf_to_errors", [True, False])\ndef test_engine_kwargs(ext, nan_inf_to_errors):\n # GH 42286\n engine_kwargs = {"options": {"nan_inf_to_errors": nan_inf_to_errors}}\n with tm.ensure_clean(ext) as f:\n with ExcelWriter(f, engine="xlsxwriter", engine_kwargs=engine_kwargs) as writer:\n assert writer.book.nan_inf_to_errors == nan_inf_to_errors\n\n\ndef test_book_and_sheets_consistent(ext):\n # GH#45687 - Ensure sheets is updated if user modifies book\n with tm.ensure_clean(ext) as f:\n with ExcelWriter(f, engine="xlsxwriter") as writer:\n assert writer.sheets == {}\n sheet = writer.book.add_worksheet("test_name")\n assert writer.sheets == {"test_name": sheet}\n
.venv\Lib\site-packages\pandas\tests\io\excel\test_xlsxwriter.py
test_xlsxwriter.py
Python
2,773
0.95
0.127907
0.129032
vue-tools
829
2024-06-21T00:58:40.729509
MIT
true
fb25df0b2b2781ec1727e4e1a782a9ad
\n\n
.venv\Lib\site-packages\pandas\tests\io\excel\__pycache__\test_odf.cpython-313.pyc
test_odf.cpython-313.pyc
Other
3,707
0.85
0
0
vue-tools
96
2023-08-25T10:27:32.254619
GPL-3.0
true
ae3f947898aadfdcabc27eae4035bd1b
\n\n
.venv\Lib\site-packages\pandas\tests\io\excel\__pycache__\test_odswriter.cpython-313.pyc
test_odswriter.cpython-313.pyc
Other
5,248
0.95
0
0
awesome-app
137
2024-05-09T01:16:08.342571
GPL-3.0
true
a2814696c8ce5c9a88cb1800aa969197
\n\n
.venv\Lib\site-packages\pandas\tests\io\excel\__pycache__\test_openpyxl.cpython-313.pyc
test_openpyxl.cpython-313.pyc
Other
21,981
0.95
0.00274
0.00295
react-lib
930
2024-02-17T22:35:32.096826
GPL-3.0
true
39ea0b666c1789195de9e6ab062a19c1
\n\n
.venv\Lib\site-packages\pandas\tests\io\excel\__pycache__\test_readers.cpython-313.pyc
test_readers.cpython-313.pyc
Other
80,591
0.6
0.007856
0
awesome-app
913
2024-02-15T15:09:51.897414
MIT
true
3c38320fb12c2d4e219f37dd8a235272
\n\n
.venv\Lib\site-packages\pandas\tests\io\excel\__pycache__\test_style.cpython-313.pyc
test_style.cpython-313.pyc
Other
15,646
0.95
0.00463
0
python-kit
696
2024-11-08T17:57:24.829104
MIT
true
fc914fca9d789f86bee1c1e2e17bedef
\n\n
.venv\Lib\site-packages\pandas\tests\io\excel\__pycache__\test_writers.cpython-313.pyc
test_writers.cpython-313.pyc
Other
81,550
0.75
0.002915
0.004004
node-utils
441
2023-08-01T07:11:37.147263
MIT
true
42dd1478c09eef1cec63bb0463c0bcb9
\n\n
.venv\Lib\site-packages\pandas\tests\io\excel\__pycache__\test_xlrd.cpython-313.pyc
test_xlrd.cpython-313.pyc
Other
3,486
0.85
0.036364
0
react-lib
569
2023-08-15T23:47:35.089768
BSD-3-Clause
true
fd1d5636ab44d0d4936d081ee4ea7dc5
\n\n
.venv\Lib\site-packages\pandas\tests\io\excel\__pycache__\test_xlsxwriter.cpython-313.pyc
test_xlsxwriter.cpython-313.pyc
Other
4,702
0.95
0
0
python-kit
168
2025-04-02T04:01:35.814620
Apache-2.0
true
3da11c7f0e1d6b0d94e04547025ff9da
\n\n
.venv\Lib\site-packages\pandas\tests\io\excel\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
196
0.7
0
0
react-lib
12
2024-08-19T15:43:15.173846
MIT
true
3684d3f752f0a1057e49c44015c24a62
import locale\n\nimport pytest\n\nfrom pandas._config import detect_console_encoding\n\n\nclass MockEncoding:\n """\n Used to add a side effect when accessing the 'encoding' property. If the\n side effect is a str in nature, the value will be returned. Otherwise, the\n side effect should be an exception that will be raised.\n """\n\n def __init__(self, encoding) -> None:\n super().__init__()\n self.val = encoding\n\n @property\n def encoding(self):\n return self.raise_or_return(self.val)\n\n @staticmethod\n def raise_or_return(val):\n if isinstance(val, str):\n return val\n else:\n raise val\n\n\n@pytest.mark.parametrize("empty,filled", [["stdin", "stdout"], ["stdout", "stdin"]])\ndef test_detect_console_encoding_from_stdout_stdin(monkeypatch, empty, filled):\n # Ensures that when sys.stdout.encoding or sys.stdin.encoding is used when\n # they have values filled.\n # GH 21552\n with monkeypatch.context() as context:\n context.setattr(f"sys.{empty}", MockEncoding(""))\n context.setattr(f"sys.{filled}", MockEncoding(filled))\n assert detect_console_encoding() == filled\n\n\n@pytest.mark.parametrize("encoding", [AttributeError, OSError, "ascii"])\ndef test_detect_console_encoding_fallback_to_locale(monkeypatch, encoding):\n # GH 21552\n with monkeypatch.context() as context:\n context.setattr("locale.getpreferredencoding", lambda: "foo")\n context.setattr("sys.stdout", MockEncoding(encoding))\n assert detect_console_encoding() == "foo"\n\n\n@pytest.mark.parametrize(\n "std,locale",\n [\n ["ascii", "ascii"],\n ["ascii", locale.Error],\n [AttributeError, "ascii"],\n [AttributeError, locale.Error],\n [OSError, "ascii"],\n [OSError, locale.Error],\n ],\n)\ndef test_detect_console_encoding_fallback_to_default(monkeypatch, std, locale):\n # When both the stdout/stdin encoding and locale preferred encoding checks\n # fail (or return 'ascii', we should default to the sys default encoding.\n # GH 21552\n with monkeypatch.context() as context:\n context.setattr(\n "locale.getpreferredencoding", lambda: MockEncoding.raise_or_return(locale)\n )\n context.setattr("sys.stdout", MockEncoding(std))\n context.setattr("sys.getdefaultencoding", lambda: "sysDefaultEncoding")\n assert detect_console_encoding() == "sysDefaultEncoding"\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_console.py
test_console.py
Python
2,435
0.95
0.111111
0.118644
vue-tools
905
2024-03-16T01:28:29.109108
Apache-2.0
true
0fbaf997229e7a1c7f02a521cf86f94d
import pytest\n\nfrom pandas.errors import CSSWarning\n\nimport pandas._testing as tm\n\nfrom pandas.io.formats.css import CSSResolver\n\n\ndef assert_resolves(css, props, inherited=None):\n resolve = CSSResolver()\n actual = resolve(css, inherited=inherited)\n assert props == actual\n\n\ndef assert_same_resolution(css1, css2, inherited=None):\n resolve = CSSResolver()\n resolved1 = resolve(css1, inherited=inherited)\n resolved2 = resolve(css2, inherited=inherited)\n assert resolved1 == resolved2\n\n\n@pytest.mark.parametrize(\n "name,norm,abnorm",\n [\n (\n "whitespace",\n "hello: world; foo: bar",\n " \t hello \t :\n world \n ; \n foo: \tbar\n\n",\n ),\n ("case", "hello: world; foo: bar", "Hello: WORLD; foO: bar"),\n ("empty-decl", "hello: world; foo: bar", "; hello: world;; foo: bar;\n; ;"),\n ("empty-list", "", ";"),\n ],\n)\ndef test_css_parse_normalisation(name, norm, abnorm):\n assert_same_resolution(norm, abnorm)\n\n\n@pytest.mark.parametrize(\n "invalid_css,remainder",\n [\n # No colon\n ("hello-world", ""),\n ("border-style: solid; hello-world", "border-style: solid"),\n (\n "border-style: solid; hello-world; font-weight: bold",\n "border-style: solid; font-weight: bold",\n ),\n # Unclosed string fail\n # Invalid size\n ("font-size: blah", "font-size: 1em"),\n ("font-size: 1a2b", "font-size: 1em"),\n ("font-size: 1e5pt", "font-size: 1em"),\n ("font-size: 1+6pt", "font-size: 1em"),\n ("font-size: 1unknownunit", "font-size: 1em"),\n ("font-size: 10", "font-size: 1em"),\n ("font-size: 10 pt", "font-size: 1em"),\n # Too many args\n ("border-top: 1pt solid red green", "border-top: 1pt solid green"),\n ],\n)\ndef test_css_parse_invalid(invalid_css, remainder):\n with tm.assert_produces_warning(CSSWarning):\n assert_same_resolution(invalid_css, remainder)\n\n\n@pytest.mark.parametrize(\n "shorthand,expansions",\n [\n ("margin", ["margin-top", "margin-right", "margin-bottom", "margin-left"]),\n ("padding", ["padding-top", "padding-right", "padding-bottom", "padding-left"]),\n (\n "border-width",\n [\n "border-top-width",\n "border-right-width",\n "border-bottom-width",\n "border-left-width",\n ],\n ),\n (\n "border-color",\n [\n "border-top-color",\n "border-right-color",\n "border-bottom-color",\n "border-left-color",\n ],\n ),\n (\n "border-style",\n [\n "border-top-style",\n "border-right-style",\n "border-bottom-style",\n "border-left-style",\n ],\n ),\n ],\n)\ndef test_css_side_shorthands(shorthand, expansions):\n top, right, bottom, left = expansions\n\n assert_resolves(\n f"{shorthand}: 1pt", {top: "1pt", right: "1pt", bottom: "1pt", left: "1pt"}\n )\n\n assert_resolves(\n f"{shorthand}: 1pt 4pt", {top: "1pt", right: "4pt", bottom: "1pt", left: "4pt"}\n )\n\n assert_resolves(\n f"{shorthand}: 1pt 4pt 2pt",\n {top: "1pt", right: "4pt", bottom: "2pt", left: "4pt"},\n )\n\n assert_resolves(\n f"{shorthand}: 1pt 4pt 2pt 0pt",\n {top: "1pt", right: "4pt", bottom: "2pt", left: "0pt"},\n )\n\n with tm.assert_produces_warning(CSSWarning):\n assert_resolves(f"{shorthand}: 1pt 1pt 1pt 1pt 1pt", {})\n\n\n@pytest.mark.parametrize(\n "shorthand,sides",\n [\n ("border-top", ["top"]),\n ("border-right", ["right"]),\n ("border-bottom", ["bottom"]),\n ("border-left", ["left"]),\n ("border", ["top", "right", "bottom", "left"]),\n ],\n)\ndef test_css_border_shorthand_sides(shorthand, sides):\n def create_border_dict(sides, color=None, style=None, width=None):\n resolved = {}\n for side in sides:\n if color:\n resolved[f"border-{side}-color"] = color\n if style:\n resolved[f"border-{side}-style"] = style\n if width:\n resolved[f"border-{side}-width"] = width\n return resolved\n\n assert_resolves(\n f"{shorthand}: 1pt red solid", create_border_dict(sides, "red", "solid", "1pt")\n )\n\n\n@pytest.mark.parametrize(\n "prop, expected",\n [\n ("1pt red solid", ("red", "solid", "1pt")),\n ("red 1pt solid", ("red", "solid", "1pt")),\n ("red solid 1pt", ("red", "solid", "1pt")),\n ("solid 1pt red", ("red", "solid", "1pt")),\n ("red solid", ("red", "solid", "1.500000pt")),\n # Note: color=black is not CSS conforming\n # (See https://drafts.csswg.org/css-backgrounds/#border-shorthands)\n ("1pt solid", ("black", "solid", "1pt")),\n ("1pt red", ("red", "none", "1pt")),\n ("red", ("red", "none", "1.500000pt")),\n ("1pt", ("black", "none", "1pt")),\n ("solid", ("black", "solid", "1.500000pt")),\n # Sizes\n ("1em", ("black", "none", "12pt")),\n ],\n)\ndef test_css_border_shorthands(prop, expected):\n color, style, width = expected\n\n assert_resolves(\n f"border-left: {prop}",\n {\n "border-left-color": color,\n "border-left-style": style,\n "border-left-width": width,\n },\n )\n\n\n@pytest.mark.parametrize(\n "style,inherited,equiv",\n [\n ("margin: 1px; margin: 2px", "", "margin: 2px"),\n ("margin: 1px", "margin: 2px", "margin: 1px"),\n ("margin: 1px; margin: inherit", "margin: 2px", "margin: 2px"),\n (\n "margin: 1px; margin-top: 2px",\n "",\n "margin-left: 1px; margin-right: 1px; "\n "margin-bottom: 1px; margin-top: 2px",\n ),\n ("margin-top: 2px", "margin: 1px", "margin: 1px; margin-top: 2px"),\n ("margin: 1px", "margin-top: 2px", "margin: 1px"),\n (\n "margin: 1px; margin-top: inherit",\n "margin: 2px",\n "margin: 1px; margin-top: 2px",\n ),\n ],\n)\ndef test_css_precedence(style, inherited, equiv):\n resolve = CSSResolver()\n inherited_props = resolve(inherited)\n style_props = resolve(style, inherited=inherited_props)\n equiv_props = resolve(equiv)\n assert style_props == equiv_props\n\n\n@pytest.mark.parametrize(\n "style,equiv",\n [\n (\n "margin: 1px; margin-top: inherit",\n "margin-bottom: 1px; margin-right: 1px; margin-left: 1px",\n ),\n ("margin-top: inherit", ""),\n ("margin-top: initial", ""),\n ],\n)\ndef test_css_none_absent(style, equiv):\n assert_same_resolution(style, equiv)\n\n\n@pytest.mark.parametrize(\n "size,resolved",\n [\n ("xx-small", "6pt"),\n ("x-small", f"{7.5:f}pt"),\n ("small", f"{9.6:f}pt"),\n ("medium", "12pt"),\n ("large", f"{13.5:f}pt"),\n ("x-large", "18pt"),\n ("xx-large", "24pt"),\n ("8px", "6pt"),\n ("1.25pc", "15pt"),\n (".25in", "18pt"),\n ("02.54cm", "72pt"),\n ("25.4mm", "72pt"),\n ("101.6q", "72pt"),\n ("101.6q", "72pt"),\n ],\n)\n@pytest.mark.parametrize("relative_to", [None, "16pt"]) # invariant to inherited size\ndef test_css_absolute_font_size(size, relative_to, resolved):\n if relative_to is None:\n inherited = None\n else:\n inherited = {"font-size": relative_to}\n assert_resolves(f"font-size: {size}", {"font-size": resolved}, inherited=inherited)\n\n\n@pytest.mark.parametrize(\n "size,relative_to,resolved",\n [\n ("1em", None, "12pt"),\n ("1.0em", None, "12pt"),\n ("1.25em", None, "15pt"),\n ("1em", "16pt", "16pt"),\n ("1.0em", "16pt", "16pt"),\n ("1.25em", "16pt", "20pt"),\n ("1rem", "16pt", "12pt"),\n ("1.0rem", "16pt", "12pt"),\n ("1.25rem", "16pt", "15pt"),\n ("100%", None, "12pt"),\n ("125%", None, "15pt"),\n ("100%", "16pt", "16pt"),\n ("125%", "16pt", "20pt"),\n ("2ex", None, "12pt"),\n ("2.0ex", None, "12pt"),\n ("2.50ex", None, "15pt"),\n ("inherit", "16pt", "16pt"),\n ("smaller", None, "10pt"),\n ("smaller", "18pt", "15pt"),\n ("larger", None, f"{14.4:f}pt"),\n ("larger", "15pt", "18pt"),\n ],\n)\ndef test_css_relative_font_size(size, relative_to, resolved):\n if relative_to is None:\n inherited = None\n else:\n inherited = {"font-size": relative_to}\n assert_resolves(f"font-size: {size}", {"font-size": resolved}, inherited=inherited)\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_css.py
test_css.py
Python
8,669
0.95
0.062284
0.027237
awesome-app
989
2024-04-21T09:00:51.154492
Apache-2.0
true
d7003ed4d7facc2ece318c580eecfd45
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n reset_option,\n set_eng_float_format,\n)\n\nfrom pandas.io.formats.format import EngFormatter\n\n\n@pytest.fixture(autouse=True)\ndef reset_float_format():\n yield\n reset_option("display.float_format")\n\n\nclass TestEngFormatter:\n def test_eng_float_formatter2(self, float_frame):\n df = float_frame\n df.loc[5] = 0\n\n set_eng_float_format()\n repr(df)\n\n set_eng_float_format(use_eng_prefix=True)\n repr(df)\n\n set_eng_float_format(accuracy=0)\n repr(df)\n\n def test_eng_float_formatter(self):\n df = DataFrame({"A": [1.41, 141.0, 14100, 1410000.0]})\n\n set_eng_float_format()\n result = df.to_string()\n expected = (\n " A\n"\n "0 1.410E+00\n"\n "1 141.000E+00\n"\n "2 14.100E+03\n"\n "3 1.410E+06"\n )\n assert result == expected\n\n set_eng_float_format(use_eng_prefix=True)\n result = df.to_string()\n expected = " A\n0 1.410\n1 141.000\n2 14.100k\n3 1.410M"\n assert result == expected\n\n set_eng_float_format(accuracy=0)\n result = df.to_string()\n expected = " A\n0 1E+00\n1 141E+00\n2 14E+03\n3 1E+06"\n assert result == expected\n\n def compare(self, formatter, input, output):\n formatted_input = formatter(input)\n assert formatted_input == output\n\n def compare_all(self, formatter, in_out):\n """\n Parameters:\n -----------\n formatter: EngFormatter under test\n in_out: list of tuples. Each tuple = (number, expected_formatting)\n\n It is tested if 'formatter(number) == expected_formatting'.\n *number* should be >= 0 because formatter(-number) == fmt is also\n tested. *fmt* is derived from *expected_formatting*\n """\n for input, output in in_out:\n self.compare(formatter, input, output)\n self.compare(formatter, -input, "-" + output[1:])\n\n def test_exponents_with_eng_prefix(self):\n formatter = EngFormatter(accuracy=3, use_eng_prefix=True)\n f = np.sqrt(2)\n in_out = [\n (f * 10**-24, " 1.414y"),\n (f * 10**-23, " 14.142y"),\n (f * 10**-22, " 141.421y"),\n (f * 10**-21, " 1.414z"),\n (f * 10**-20, " 14.142z"),\n (f * 10**-19, " 141.421z"),\n (f * 10**-18, " 1.414a"),\n (f * 10**-17, " 14.142a"),\n (f * 10**-16, " 141.421a"),\n (f * 10**-15, " 1.414f"),\n (f * 10**-14, " 14.142f"),\n (f * 10**-13, " 141.421f"),\n (f * 10**-12, " 1.414p"),\n (f * 10**-11, " 14.142p"),\n (f * 10**-10, " 141.421p"),\n (f * 10**-9, " 1.414n"),\n (f * 10**-8, " 14.142n"),\n (f * 10**-7, " 141.421n"),\n (f * 10**-6, " 1.414u"),\n (f * 10**-5, " 14.142u"),\n (f * 10**-4, " 141.421u"),\n (f * 10**-3, " 1.414m"),\n (f * 10**-2, " 14.142m"),\n (f * 10**-1, " 141.421m"),\n (f * 10**0, " 1.414"),\n (f * 10**1, " 14.142"),\n (f * 10**2, " 141.421"),\n (f * 10**3, " 1.414k"),\n (f * 10**4, " 14.142k"),\n (f * 10**5, " 141.421k"),\n (f * 10**6, " 1.414M"),\n (f * 10**7, " 14.142M"),\n (f * 10**8, " 141.421M"),\n (f * 10**9, " 1.414G"),\n (f * 10**10, " 14.142G"),\n (f * 10**11, " 141.421G"),\n (f * 10**12, " 1.414T"),\n (f * 10**13, " 14.142T"),\n (f * 10**14, " 141.421T"),\n (f * 10**15, " 1.414P"),\n (f * 10**16, " 14.142P"),\n (f * 10**17, " 141.421P"),\n (f * 10**18, " 1.414E"),\n (f * 10**19, " 14.142E"),\n (f * 10**20, " 141.421E"),\n (f * 10**21, " 1.414Z"),\n (f * 10**22, " 14.142Z"),\n (f * 10**23, " 141.421Z"),\n (f * 10**24, " 1.414Y"),\n (f * 10**25, " 14.142Y"),\n (f * 10**26, " 141.421Y"),\n ]\n self.compare_all(formatter, in_out)\n\n def test_exponents_without_eng_prefix(self):\n formatter = EngFormatter(accuracy=4, use_eng_prefix=False)\n f = np.pi\n in_out = [\n (f * 10**-24, " 3.1416E-24"),\n (f * 10**-23, " 31.4159E-24"),\n (f * 10**-22, " 314.1593E-24"),\n (f * 10**-21, " 3.1416E-21"),\n (f * 10**-20, " 31.4159E-21"),\n (f * 10**-19, " 314.1593E-21"),\n (f * 10**-18, " 3.1416E-18"),\n (f * 10**-17, " 31.4159E-18"),\n (f * 10**-16, " 314.1593E-18"),\n (f * 10**-15, " 3.1416E-15"),\n (f * 10**-14, " 31.4159E-15"),\n (f * 10**-13, " 314.1593E-15"),\n (f * 10**-12, " 3.1416E-12"),\n (f * 10**-11, " 31.4159E-12"),\n (f * 10**-10, " 314.1593E-12"),\n (f * 10**-9, " 3.1416E-09"),\n (f * 10**-8, " 31.4159E-09"),\n (f * 10**-7, " 314.1593E-09"),\n (f * 10**-6, " 3.1416E-06"),\n (f * 10**-5, " 31.4159E-06"),\n (f * 10**-4, " 314.1593E-06"),\n (f * 10**-3, " 3.1416E-03"),\n (f * 10**-2, " 31.4159E-03"),\n (f * 10**-1, " 314.1593E-03"),\n (f * 10**0, " 3.1416E+00"),\n (f * 10**1, " 31.4159E+00"),\n (f * 10**2, " 314.1593E+00"),\n (f * 10**3, " 3.1416E+03"),\n (f * 10**4, " 31.4159E+03"),\n (f * 10**5, " 314.1593E+03"),\n (f * 10**6, " 3.1416E+06"),\n (f * 10**7, " 31.4159E+06"),\n (f * 10**8, " 314.1593E+06"),\n (f * 10**9, " 3.1416E+09"),\n (f * 10**10, " 31.4159E+09"),\n (f * 10**11, " 314.1593E+09"),\n (f * 10**12, " 3.1416E+12"),\n (f * 10**13, " 31.4159E+12"),\n (f * 10**14, " 314.1593E+12"),\n (f * 10**15, " 3.1416E+15"),\n (f * 10**16, " 31.4159E+15"),\n (f * 10**17, " 314.1593E+15"),\n (f * 10**18, " 3.1416E+18"),\n (f * 10**19, " 31.4159E+18"),\n (f * 10**20, " 314.1593E+18"),\n (f * 10**21, " 3.1416E+21"),\n (f * 10**22, " 31.4159E+21"),\n (f * 10**23, " 314.1593E+21"),\n (f * 10**24, " 3.1416E+24"),\n (f * 10**25, " 31.4159E+24"),\n (f * 10**26, " 314.1593E+24"),\n ]\n self.compare_all(formatter, in_out)\n\n def test_rounding(self):\n formatter = EngFormatter(accuracy=3, use_eng_prefix=True)\n in_out = [\n (5.55555, " 5.556"),\n (55.5555, " 55.556"),\n (555.555, " 555.555"),\n (5555.55, " 5.556k"),\n (55555.5, " 55.556k"),\n (555555, " 555.555k"),\n ]\n self.compare_all(formatter, in_out)\n\n formatter = EngFormatter(accuracy=1, use_eng_prefix=True)\n in_out = [\n (5.55555, " 5.6"),\n (55.5555, " 55.6"),\n (555.555, " 555.6"),\n (5555.55, " 5.6k"),\n (55555.5, " 55.6k"),\n (555555, " 555.6k"),\n ]\n self.compare_all(formatter, in_out)\n\n formatter = EngFormatter(accuracy=0, use_eng_prefix=True)\n in_out = [\n (5.55555, " 6"),\n (55.5555, " 56"),\n (555.555, " 556"),\n (5555.55, " 6k"),\n (55555.5, " 56k"),\n (555555, " 556k"),\n ]\n self.compare_all(formatter, in_out)\n\n formatter = EngFormatter(accuracy=3, use_eng_prefix=True)\n result = formatter(0)\n assert result == " 0.000"\n\n def test_nan(self):\n # Issue #11981\n\n formatter = EngFormatter(accuracy=1, use_eng_prefix=True)\n result = formatter(np.nan)\n assert result == "NaN"\n\n df = DataFrame(\n {\n "a": [1.5, 10.3, 20.5],\n "b": [50.3, 60.67, 70.12],\n "c": [100.2, 101.33, 120.33],\n }\n )\n pt = df.pivot_table(values="a", index="b", columns="c")\n set_eng_float_format(accuracy=1)\n result = pt.to_string()\n assert "NaN" in result\n\n def test_inf(self):\n # Issue #11981\n\n formatter = EngFormatter(accuracy=1, use_eng_prefix=True)\n result = formatter(np.inf)\n assert result == "inf"\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_eng_formatting.py
test_eng_formatting.py
Python
8,454
0.95
0.051181
0.013216
react-lib
528
2025-04-18T19:28:28.491326
GPL-3.0
true
e3481a561ce6b003e43030c86bc89b6d
"""\nTests for the file pandas.io.formats.format, *not* tests for general formatting\nof pandas objects.\n"""\nfrom datetime import datetime\nfrom io import StringIO\nfrom pathlib import Path\nimport re\nfrom shutil import get_terminal_size\n\nimport 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 MultiIndex,\n NaT,\n Series,\n Timestamp,\n date_range,\n get_option,\n option_context,\n read_csv,\n reset_option,\n)\n\nfrom pandas.io.formats import printing\nimport pandas.io.formats.format as fmt\n\n\n@pytest.fixture(params=["string", "pathlike", "buffer"])\ndef filepath_or_buffer_id(request):\n """\n A fixture yielding test ids for filepath_or_buffer testing.\n """\n return request.param\n\n\n@pytest.fixture\ndef filepath_or_buffer(filepath_or_buffer_id, tmp_path):\n """\n A fixture yielding a string representing a filepath, a path-like object\n and a StringIO buffer. Also checks that buffer is not closed.\n """\n if filepath_or_buffer_id == "buffer":\n buf = StringIO()\n yield buf\n assert not buf.closed\n else:\n assert isinstance(tmp_path, Path)\n if filepath_or_buffer_id == "pathlike":\n yield tmp_path / "foo"\n else:\n yield str(tmp_path / "foo")\n\n\n@pytest.fixture\ndef assert_filepath_or_buffer_equals(\n filepath_or_buffer, filepath_or_buffer_id, encoding\n):\n """\n Assertion helper for checking filepath_or_buffer.\n """\n if encoding is None:\n encoding = "utf-8"\n\n def _assert_filepath_or_buffer_equals(expected):\n if filepath_or_buffer_id == "string":\n with open(filepath_or_buffer, encoding=encoding) as f:\n result = f.read()\n elif filepath_or_buffer_id == "pathlike":\n result = filepath_or_buffer.read_text(encoding=encoding)\n elif filepath_or_buffer_id == "buffer":\n result = filepath_or_buffer.getvalue()\n assert result == expected\n\n return _assert_filepath_or_buffer_equals\n\n\ndef has_info_repr(df):\n r = repr(df)\n c1 = r.split("\n")[0].startswith("<class")\n c2 = r.split("\n")[0].startswith(r"&lt;class") # _repr_html_\n return c1 or c2\n\n\ndef has_non_verbose_info_repr(df):\n has_info = has_info_repr(df)\n r = repr(df)\n\n # 1. <class>\n # 2. Index\n # 3. Columns\n # 4. dtype\n # 5. memory usage\n # 6. trailing newline\n nv = len(r.split("\n")) == 6\n return has_info and nv\n\n\ndef has_horizontally_truncated_repr(df):\n try: # Check header row\n fst_line = np.array(repr(df).splitlines()[0].split())\n cand_col = np.where(fst_line == "...")[0][0]\n except IndexError:\n return False\n # Make sure each row has this ... in the same place\n r = repr(df)\n for ix, _ in enumerate(r.splitlines()):\n if not r.split()[cand_col] == "...":\n return False\n return True\n\n\ndef has_vertically_truncated_repr(df):\n r = repr(df)\n only_dot_row = False\n for row in r.splitlines():\n if re.match(r"^[\.\ ]+$", row):\n only_dot_row = True\n return only_dot_row\n\n\ndef has_truncated_repr(df):\n return has_horizontally_truncated_repr(df) or has_vertically_truncated_repr(df)\n\n\ndef has_doubly_truncated_repr(df):\n return has_horizontally_truncated_repr(df) and has_vertically_truncated_repr(df)\n\n\ndef has_expanded_repr(df):\n r = repr(df)\n for line in r.split("\n"):\n if line.endswith("\\"):\n return True\n return False\n\n\nclass TestDataFrameFormatting:\n def test_repr_truncation(self):\n max_len = 20\n with option_context("display.max_colwidth", max_len):\n df = DataFrame(\n {\n "A": np.random.default_rng(2).standard_normal(10),\n "B": [\n "a"\n * np.random.default_rng(2).integers(max_len - 1, max_len + 1)\n for _ in range(10)\n ],\n }\n )\n r = repr(df)\n r = r[r.find("\n") + 1 :]\n\n adj = printing.get_adjustment()\n\n for line, value in zip(r.split("\n"), df["B"]):\n if adj.len(value) + 1 > max_len:\n assert "..." in line\n else:\n assert "..." not in line\n\n with option_context("display.max_colwidth", 999999):\n assert "..." not in repr(df)\n\n with option_context("display.max_colwidth", max_len + 2):\n assert "..." not in repr(df)\n\n def test_repr_truncation_preserves_na(self):\n # https://github.com/pandas-dev/pandas/issues/55630\n df = DataFrame({"a": [pd.NA for _ in range(10)]})\n with option_context("display.max_rows", 2, "display.show_dimensions", False):\n assert repr(df) == " a\n0 <NA>\n.. ...\n9 <NA>"\n\n def test_max_colwidth_negative_int_raises(self):\n # Deprecation enforced from:\n # https://github.com/pandas-dev/pandas/issues/31532\n with pytest.raises(\n ValueError, match="Value must be a nonnegative integer or None"\n ):\n with option_context("display.max_colwidth", -1):\n pass\n\n def test_repr_chop_threshold(self):\n df = DataFrame([[0.1, 0.5], [0.5, -0.1]])\n reset_option("display.chop_threshold") # default None\n assert repr(df) == " 0 1\n0 0.1 0.5\n1 0.5 -0.1"\n\n with option_context("display.chop_threshold", 0.2):\n assert repr(df) == " 0 1\n0 0.0 0.5\n1 0.5 0.0"\n\n with option_context("display.chop_threshold", 0.6):\n assert repr(df) == " 0 1\n0 0.0 0.0\n1 0.0 0.0"\n\n with option_context("display.chop_threshold", None):\n assert repr(df) == " 0 1\n0 0.1 0.5\n1 0.5 -0.1"\n\n def test_repr_chop_threshold_column_below(self):\n # GH 6839: validation case\n\n df = DataFrame([[10, 20, 30, 40], [8e-10, -1e-11, 2e-9, -2e-11]]).T\n\n with option_context("display.chop_threshold", 0):\n assert repr(df) == (\n " 0 1\n"\n "0 10.0 8.000000e-10\n"\n "1 20.0 -1.000000e-11\n"\n "2 30.0 2.000000e-09\n"\n "3 40.0 -2.000000e-11"\n )\n\n with option_context("display.chop_threshold", 1e-8):\n assert repr(df) == (\n " 0 1\n"\n "0 10.0 0.000000e+00\n"\n "1 20.0 0.000000e+00\n"\n "2 30.0 0.000000e+00\n"\n "3 40.0 0.000000e+00"\n )\n\n with option_context("display.chop_threshold", 5e-11):\n assert repr(df) == (\n " 0 1\n"\n "0 10.0 8.000000e-10\n"\n "1 20.0 0.000000e+00\n"\n "2 30.0 2.000000e-09\n"\n "3 40.0 0.000000e+00"\n )\n\n def test_repr_no_backslash(self):\n with option_context("mode.sim_interactive", True):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))\n assert "\\" not in repr(df)\n\n def test_expand_frame_repr(self):\n df_small = DataFrame("hello", index=[0], columns=[0])\n df_wide = DataFrame("hello", index=[0], columns=range(10))\n df_tall = DataFrame("hello", index=range(30), columns=range(5))\n\n with option_context("mode.sim_interactive", True):\n with option_context(\n "display.max_columns",\n 10,\n "display.width",\n 20,\n "display.max_rows",\n 20,\n "display.show_dimensions",\n True,\n ):\n with option_context("display.expand_frame_repr", True):\n assert not has_truncated_repr(df_small)\n assert not has_expanded_repr(df_small)\n assert not has_truncated_repr(df_wide)\n assert has_expanded_repr(df_wide)\n assert has_vertically_truncated_repr(df_tall)\n assert has_expanded_repr(df_tall)\n\n with option_context("display.expand_frame_repr", False):\n assert not has_truncated_repr(df_small)\n assert not has_expanded_repr(df_small)\n assert not has_horizontally_truncated_repr(df_wide)\n assert not has_expanded_repr(df_wide)\n assert has_vertically_truncated_repr(df_tall)\n assert not has_expanded_repr(df_tall)\n\n def test_repr_non_interactive(self):\n # in non interactive mode, there can be no dependency on the\n # result of terminal auto size detection\n df = DataFrame("hello", index=range(1000), columns=range(5))\n\n with option_context(\n "mode.sim_interactive", False, "display.width", 0, "display.max_rows", 5000\n ):\n assert not has_truncated_repr(df)\n assert not has_expanded_repr(df)\n\n def test_repr_truncates_terminal_size(self, monkeypatch):\n # see gh-21180\n\n terminal_size = (118, 96)\n monkeypatch.setattr(\n "pandas.io.formats.format.get_terminal_size", lambda: terminal_size\n )\n\n index = range(5)\n columns = MultiIndex.from_tuples(\n [\n ("This is a long title with > 37 chars.", "cat"),\n ("This is a loooooonger title with > 43 chars.", "dog"),\n ]\n )\n df = DataFrame(1, index=index, columns=columns)\n\n result = repr(df)\n\n h1, h2 = result.split("\n")[:2]\n assert "long" in h1\n assert "loooooonger" in h1\n assert "cat" in h2\n assert "dog" in h2\n\n # regular columns\n df2 = DataFrame({"A" * 41: [1, 2], "B" * 41: [1, 2]})\n result = repr(df2)\n\n assert df2.columns[0] in result.split("\n")[0]\n\n def test_repr_truncates_terminal_size_full(self, monkeypatch):\n # GH 22984 ensure entire window is filled\n terminal_size = (80, 24)\n df = DataFrame(np.random.default_rng(2).random((1, 7)))\n\n monkeypatch.setattr(\n "pandas.io.formats.format.get_terminal_size", lambda: terminal_size\n )\n assert "..." not in str(df)\n\n def test_repr_truncation_column_size(self):\n # dataframe with last column very wide -> check it is not used to\n # determine size of truncation (...) column\n df = DataFrame(\n {\n "a": [108480, 30830],\n "b": [12345, 12345],\n "c": [12345, 12345],\n "d": [12345, 12345],\n "e": ["a" * 50] * 2,\n }\n )\n assert "..." in str(df)\n assert " ... " not in str(df)\n\n def test_repr_max_columns_max_rows(self):\n term_width, term_height = get_terminal_size()\n if term_width < 10 or term_height < 10:\n pytest.skip(f"terminal size too small, {term_width} x {term_height}")\n\n def mkframe(n):\n index = [f"{i:05d}" for i in range(n)]\n return DataFrame(0, index, index)\n\n df6 = mkframe(6)\n df10 = mkframe(10)\n with option_context("mode.sim_interactive", True):\n with option_context("display.width", term_width * 2):\n with option_context("display.max_rows", 5, "display.max_columns", 5):\n assert not has_expanded_repr(mkframe(4))\n assert not has_expanded_repr(mkframe(5))\n assert not has_expanded_repr(df6)\n assert has_doubly_truncated_repr(df6)\n\n with option_context("display.max_rows", 20, "display.max_columns", 10):\n # Out off max_columns boundary, but no extending\n # since not exceeding width\n assert not has_expanded_repr(df6)\n assert not has_truncated_repr(df6)\n\n with option_context("display.max_rows", 9, "display.max_columns", 10):\n # out vertical bounds can not result in expanded repr\n assert not has_expanded_repr(df10)\n assert has_vertically_truncated_repr(df10)\n\n # width=None in terminal, auto detection\n with option_context(\n "display.max_columns",\n 100,\n "display.max_rows",\n term_width * 20,\n "display.width",\n None,\n ):\n df = mkframe((term_width // 7) - 2)\n assert not has_expanded_repr(df)\n df = mkframe((term_width // 7) + 2)\n printing.pprint_thing(df._repr_fits_horizontal_())\n assert has_expanded_repr(df)\n\n def test_repr_min_rows(self):\n df = DataFrame({"a": range(20)})\n\n # default setting no truncation even if above min_rows\n assert ".." not in repr(df)\n assert ".." not in df._repr_html_()\n\n df = DataFrame({"a": range(61)})\n\n # default of max_rows 60 triggers truncation if above\n assert ".." in repr(df)\n assert ".." in df._repr_html_()\n\n with option_context("display.max_rows", 10, "display.min_rows", 4):\n # truncated after first two rows\n assert ".." in repr(df)\n assert "2 " not in repr(df)\n assert "..." in df._repr_html_()\n assert "<td>2</td>" not in df._repr_html_()\n\n with option_context("display.max_rows", 12, "display.min_rows", None):\n # when set to None, follow value of max_rows\n assert "5 5" in repr(df)\n assert "<td>5</td>" in df._repr_html_()\n\n with option_context("display.max_rows", 10, "display.min_rows", 12):\n # when set value higher as max_rows, use the minimum\n assert "5 5" not in repr(df)\n assert "<td>5</td>" not in df._repr_html_()\n\n with option_context("display.max_rows", None, "display.min_rows", 12):\n # max_rows of None -> never truncate\n assert ".." not in repr(df)\n assert ".." not in df._repr_html_()\n\n def test_str_max_colwidth(self):\n # GH 7856\n df = DataFrame(\n [\n {\n "a": "foo",\n "b": "bar",\n "c": "uncomfortably long line with lots of stuff",\n "d": 1,\n },\n {"a": "foo", "b": "bar", "c": "stuff", "d": 1},\n ]\n )\n df.set_index(["a", "b", "c"])\n assert str(df) == (\n " a b c d\n"\n "0 foo bar uncomfortably long line with lots of stuff 1\n"\n "1 foo bar stuff 1"\n )\n with option_context("max_colwidth", 20):\n assert str(df) == (\n " a b c d\n"\n "0 foo bar uncomfortably lo... 1\n"\n "1 foo bar stuff 1"\n )\n\n def test_auto_detect(self):\n term_width, term_height = get_terminal_size()\n fac = 1.05 # Arbitrary large factor to exceed term width\n cols = range(int(term_width * fac))\n index = range(10)\n df = DataFrame(index=index, columns=cols)\n with option_context("mode.sim_interactive", True):\n with option_context("display.max_rows", None):\n with option_context("display.max_columns", None):\n # Wrap around with None\n assert has_expanded_repr(df)\n with option_context("display.max_rows", 0):\n with option_context("display.max_columns", 0):\n # Truncate with auto detection.\n assert has_horizontally_truncated_repr(df)\n\n index = range(int(term_height * fac))\n df = DataFrame(index=index, columns=cols)\n with option_context("display.max_rows", 0):\n with option_context("display.max_columns", None):\n # Wrap around with None\n assert has_expanded_repr(df)\n # Truncate vertically\n assert has_vertically_truncated_repr(df)\n\n with option_context("display.max_rows", None):\n with option_context("display.max_columns", 0):\n assert has_horizontally_truncated_repr(df)\n\n def test_to_string_repr_unicode2(self):\n idx = Index(["abc", "\u03c3a", "aegdvg"])\n ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx)\n rs = repr(ser).split("\n")\n line_len = len(rs[0])\n for line in rs[1:]:\n try:\n line = line.decode(get_option("display.encoding"))\n except AttributeError:\n pass\n if not line.startswith("dtype:"):\n assert len(line) == line_len\n\n def test_east_asian_unicode_false(self):\n # not aligned properly because of east asian width\n\n # mid col\n df = DataFrame(\n {"a": ["あ", "いいい", "う", "ええええええ"], "b": [1, 222, 33333, 4]},\n index=["a", "bb", "c", "ddd"],\n )\n expected = (\n " a b\na あ 1\n"\n "bb いいい 222\nc う 33333\n"\n "ddd ええええええ 4"\n )\n assert repr(df) == expected\n\n # last col\n df = DataFrame(\n {"a": [1, 222, 33333, 4], "b": ["あ", "いいい", "う", "ええええええ"]},\n index=["a", "bb", "c", "ddd"],\n )\n expected = (\n " a b\na 1 あ\n"\n "bb 222 いいい\nc 33333 う\n"\n "ddd 4 ええええええ"\n )\n assert repr(df) == expected\n\n # all col\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n },\n index=["a", "bb", "c", "ddd"],\n )\n expected = (\n " a b\na あああああ あ\n"\n "bb い いいい\nc う う\n"\n "ddd えええ ええええええ"\n )\n assert repr(df) == expected\n\n # column name\n df = DataFrame(\n {\n "b": ["あ", "いいい", "う", "ええええええ"],\n "あああああ": [1, 222, 33333, 4],\n },\n index=["a", "bb", "c", "ddd"],\n )\n expected = (\n " b あああああ\na あ 1\n"\n "bb いいい 222\nc う 33333\n"\n "ddd ええええええ 4"\n )\n assert repr(df) == expected\n\n # index\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n },\n index=["あああ", "いいいいいい", "うう", "え"],\n )\n expected = (\n " a b\nあああ あああああ あ\n"\n "いいいいいい い いいい\nうう う う\n"\n "え えええ ええええええ"\n )\n assert repr(df) == expected\n\n # index name\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n },\n index=Index(["あ", "い", "うう", "え"], name="おおおお"),\n )\n expected = (\n " a b\n"\n "おおおお \n"\n "あ あああああ あ\n"\n "い い いいい\n"\n "うう う う\n"\n "え えええ ええええええ"\n )\n assert repr(df) == expected\n\n # all\n df = DataFrame(\n {\n "あああ": ["あああ", "い", "う", "えええええ"],\n "いいいいい": ["あ", "いいい", "う", "ええ"],\n },\n index=Index(["あ", "いいい", "うう", "え"], name="お"),\n )\n expected = (\n " あああ いいいいい\n"\n "お \n"\n "あ あああ あ\n"\n "いいい い いいい\n"\n "うう う う\n"\n "え えええええ ええ"\n )\n assert repr(df) == expected\n\n # MultiIndex\n idx = MultiIndex.from_tuples(\n [("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]\n )\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n },\n index=idx,\n )\n expected = (\n " a b\n"\n "あ いい あああああ あ\n"\n "う え い いいい\n"\n "おおお かかかか う う\n"\n "き くく えええ ええええええ"\n )\n assert repr(df) == expected\n\n # truncate\n with option_context("display.max_rows", 3, "display.max_columns", 3):\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n "c": ["お", "か", "ききき", "くくくくくく"],\n "ああああ": ["さ", "し", "す", "せ"],\n },\n columns=["a", "b", "c", "ああああ"],\n )\n\n expected = (\n " a ... ああああ\n0 あああああ ... さ\n"\n ".. ... ... ...\n3 えええ ... せ\n"\n "\n[4 rows x 4 columns]"\n )\n assert repr(df) == expected\n\n df.index = ["あああ", "いいいい", "う", "aaa"]\n expected = (\n " a ... ああああ\nあああ あああああ ... さ\n"\n ".. ... ... ...\naaa えええ ... せ\n"\n "\n[4 rows x 4 columns]"\n )\n assert repr(df) == expected\n\n def test_east_asian_unicode_true(self):\n # Enable Unicode option -----------------------------------------\n with option_context("display.unicode.east_asian_width", True):\n # mid col\n df = DataFrame(\n {"a": ["あ", "いいい", "う", "ええええええ"], "b": [1, 222, 33333, 4]},\n index=["a", "bb", "c", "ddd"],\n )\n expected = (\n " a b\na あ 1\n"\n "bb いいい 222\nc う 33333\n"\n "ddd ええええええ 4"\n )\n assert repr(df) == expected\n\n # last col\n df = DataFrame(\n {"a": [1, 222, 33333, 4], "b": ["あ", "いいい", "う", "ええええええ"]},\n index=["a", "bb", "c", "ddd"],\n )\n expected = (\n " a b\na 1 あ\n"\n "bb 222 いいい\nc 33333 う\n"\n "ddd 4 ええええええ"\n )\n assert repr(df) == expected\n\n # all col\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n },\n index=["a", "bb", "c", "ddd"],\n )\n expected = (\n " a b\n"\n "a あああああ あ\n"\n "bb い いいい\n"\n "c う う\n"\n "ddd えええ ええええええ"\n )\n assert repr(df) == expected\n\n # column name\n df = DataFrame(\n {\n "b": ["あ", "いいい", "う", "ええええええ"],\n "あああああ": [1, 222, 33333, 4],\n },\n index=["a", "bb", "c", "ddd"],\n )\n expected = (\n " b あああああ\n"\n "a あ 1\n"\n "bb いいい 222\n"\n "c う 33333\n"\n "ddd ええええええ 4"\n )\n assert repr(df) == expected\n\n # index\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n },\n index=["あああ", "いいいいいい", "うう", "え"],\n )\n expected = (\n " a b\n"\n "あああ あああああ あ\n"\n "いいいいいい い いいい\n"\n "うう う う\n"\n "え えええ ええええええ"\n )\n assert repr(df) == expected\n\n # index name\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n },\n index=Index(["あ", "い", "うう", "え"], name="おおおお"),\n )\n expected = (\n " a b\n"\n "おおおお \n"\n "あ あああああ あ\n"\n "い い いいい\n"\n "うう う う\n"\n "え えええ ええええええ"\n )\n assert repr(df) == expected\n\n # all\n df = DataFrame(\n {\n "あああ": ["あああ", "い", "う", "えええええ"],\n "いいいいい": ["あ", "いいい", "う", "ええ"],\n },\n index=Index(["あ", "いいい", "うう", "え"], name="お"),\n )\n expected = (\n " あああ いいいいい\n"\n "お \n"\n "あ あああ あ\n"\n "いいい い いいい\n"\n "うう う う\n"\n "え えええええ ええ"\n )\n assert repr(df) == expected\n\n # MultiIndex\n idx = MultiIndex.from_tuples(\n [("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]\n )\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n },\n index=idx,\n )\n expected = (\n " a b\n"\n "あ いい あああああ あ\n"\n "う え い いいい\n"\n "おおお かかかか う う\n"\n "き くく えええ ええええええ"\n )\n assert repr(df) == expected\n\n # truncate\n with option_context("display.max_rows", 3, "display.max_columns", 3):\n df = DataFrame(\n {\n "a": ["あああああ", "い", "う", "えええ"],\n "b": ["あ", "いいい", "う", "ええええええ"],\n "c": ["お", "か", "ききき", "くくくくくく"],\n "ああああ": ["さ", "し", "す", "せ"],\n },\n columns=["a", "b", "c", "ああああ"],\n )\n\n expected = (\n " a ... ああああ\n"\n "0 あああああ ... さ\n"\n ".. ... ... ...\n"\n "3 えええ ... せ\n"\n "\n[4 rows x 4 columns]"\n )\n assert repr(df) == expected\n\n df.index = ["あああ", "いいいい", "う", "aaa"]\n expected = (\n " a ... ああああ\n"\n "あああ あああああ ... さ\n"\n "... ... ... ...\n"\n "aaa えええ ... せ\n"\n "\n[4 rows x 4 columns]"\n )\n assert repr(df) == expected\n\n # ambiguous unicode\n df = DataFrame(\n {\n "b": ["あ", "いいい", "¡¡", "ええええええ"],\n "あああああ": [1, 222, 33333, 4],\n },\n index=["a", "bb", "c", "¡¡¡"],\n )\n expected = (\n " b あああああ\n"\n "a あ 1\n"\n "bb いいい 222\n"\n "c ¡¡ 33333\n"\n "¡¡¡ ええええええ 4"\n )\n assert repr(df) == expected\n\n def test_to_string_buffer_all_unicode(self):\n buf = StringIO()\n\n empty = DataFrame({"c/\u03c3": Series(dtype=object)})\n nonempty = DataFrame({"c/\u03c3": Series([1, 2, 3])})\n\n print(empty, file=buf)\n print(nonempty, file=buf)\n\n # this should work\n buf.getvalue()\n\n @pytest.mark.parametrize(\n "index_scalar",\n [\n "a" * 10,\n 1,\n Timestamp(2020, 1, 1),\n pd.Period("2020-01-01"),\n ],\n )\n @pytest.mark.parametrize("h", [10, 20])\n @pytest.mark.parametrize("w", [10, 20])\n def test_to_string_truncate_indices(self, index_scalar, h, w):\n with option_context("display.expand_frame_repr", False):\n df = DataFrame(\n index=[index_scalar] * h, columns=[str(i) * 10 for i in range(w)]\n )\n with option_context("display.max_rows", 15):\n if h == 20:\n assert has_vertically_truncated_repr(df)\n else:\n assert not has_vertically_truncated_repr(df)\n with option_context("display.max_columns", 15):\n if w == 20:\n assert has_horizontally_truncated_repr(df)\n else:\n assert not has_horizontally_truncated_repr(df)\n with option_context("display.max_rows", 15, "display.max_columns", 15):\n if h == 20 and w == 20:\n assert has_doubly_truncated_repr(df)\n else:\n assert not has_doubly_truncated_repr(df)\n\n def test_to_string_truncate_multilevel(self):\n arrays = [\n ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n df = DataFrame(index=arrays, columns=arrays)\n with option_context("display.max_rows", 7, "display.max_columns", 7):\n assert has_doubly_truncated_repr(df)\n\n @pytest.mark.parametrize("dtype", ["object", "datetime64[us]"])\n def test_truncate_with_different_dtypes(self, dtype):\n # 11594, 12045\n # when truncated the dtypes of the splits can differ\n\n # 11594\n ser = Series(\n [datetime(2012, 1, 1)] * 10\n + [datetime(1012, 1, 2)]\n + [datetime(2012, 1, 3)] * 10,\n dtype=dtype,\n )\n\n with option_context("display.max_rows", 8):\n result = str(ser)\n assert dtype in result\n\n def test_truncate_with_different_dtypes2(self):\n # 12045\n df = DataFrame({"text": ["some words"] + [None] * 9}, dtype=object)\n\n with option_context("display.max_rows", 8, "display.max_columns", 3):\n result = str(df)\n assert "None" in result\n assert "NaN" not in result\n\n def test_truncate_with_different_dtypes_multiindex(self):\n # GH#13000\n df = DataFrame({"Vals": range(100)})\n frame = pd.concat([df], keys=["Sweep"], names=["Sweep", "Index"])\n result = repr(frame)\n\n result2 = repr(frame.iloc[:5])\n assert result.startswith(result2)\n\n def test_datetimelike_frame(self):\n # GH 12211\n df = DataFrame({"date": [Timestamp("20130101").tz_localize("UTC")] + [NaT] * 5})\n\n with option_context("display.max_rows", 5):\n result = str(df)\n assert "2013-01-01 00:00:00+00:00" in result\n assert "NaT" in result\n assert "..." in result\n assert "[6 rows x 1 columns]" in result\n\n dts = [Timestamp("2011-01-01", tz="US/Eastern")] * 5 + [NaT] * 5\n df = DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})\n with option_context("display.max_rows", 5):\n expected = (\n " dt x\n"\n "0 2011-01-01 00:00:00-05:00 1\n"\n "1 2011-01-01 00:00:00-05:00 2\n"\n ".. ... ..\n"\n "8 NaT 9\n"\n "9 NaT 10\n\n"\n "[10 rows x 2 columns]"\n )\n assert repr(df) == expected\n\n dts = [NaT] * 5 + [Timestamp("2011-01-01", tz="US/Eastern")] * 5\n df = DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})\n with option_context("display.max_rows", 5):\n expected = (\n " dt x\n"\n "0 NaT 1\n"\n "1 NaT 2\n"\n ".. ... ..\n"\n "8 2011-01-01 00:00:00-05:00 9\n"\n "9 2011-01-01 00:00:00-05:00 10\n\n"\n "[10 rows x 2 columns]"\n )\n assert repr(df) == expected\n\n dts = [Timestamp("2011-01-01", tz="Asia/Tokyo")] * 5 + [\n Timestamp("2011-01-01", tz="US/Eastern")\n ] * 5\n df = DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})\n with option_context("display.max_rows", 5):\n expected = (\n " dt x\n"\n "0 2011-01-01 00:00:00+09:00 1\n"\n "1 2011-01-01 00:00:00+09:00 2\n"\n ".. ... ..\n"\n "8 2011-01-01 00:00:00-05:00 9\n"\n "9 2011-01-01 00:00:00-05:00 10\n\n"\n "[10 rows x 2 columns]"\n )\n assert repr(df) == expected\n\n @pytest.mark.parametrize(\n "start_date",\n [\n "2017-01-01 23:59:59.999999999",\n "2017-01-01 23:59:59.99999999",\n "2017-01-01 23:59:59.9999999",\n "2017-01-01 23:59:59.999999",\n "2017-01-01 23:59:59.99999",\n "2017-01-01 23:59:59.9999",\n ],\n )\n def test_datetimeindex_highprecision(self, start_date):\n # GH19030\n # Check that high-precision time values for the end of day are\n # included in repr for DatetimeIndex\n df = DataFrame({"A": date_range(start=start_date, freq="D", periods=5)})\n result = str(df)\n assert start_date in result\n\n dti = date_range(start=start_date, freq="D", periods=5)\n df = DataFrame({"A": range(5)}, index=dti)\n result = str(df.index)\n assert start_date in result\n\n def test_string_repr_encoding(self, datapath):\n filepath = datapath("io", "parser", "data", "unicode_series.csv")\n df = read_csv(filepath, header=None, encoding="latin1")\n repr(df)\n repr(df[1])\n\n def test_repr_corner(self):\n # representing infs poses no problems\n df = DataFrame({"foo": [-np.inf, np.inf]})\n repr(df)\n\n def test_frame_info_encoding(self):\n index = ["'Til There Was You (1997)", "ldum klaka (Cold Fever) (1994)"]\n with option_context("display.max_rows", 1):\n df = DataFrame(columns=["a", "b", "c"], index=index)\n repr(df)\n repr(df.T)\n\n def test_wide_repr(self):\n with option_context(\n "mode.sim_interactive",\n True,\n "display.show_dimensions",\n True,\n "display.max_columns",\n 20,\n ):\n max_cols = get_option("display.max_columns")\n df = DataFrame([["a" * 25] * (max_cols - 1)] * 10)\n with option_context("display.expand_frame_repr", False):\n rep_str = repr(df)\n\n assert f"10 rows x {max_cols - 1} columns" in rep_str\n with option_context("display.expand_frame_repr", True):\n wide_repr = repr(df)\n assert rep_str != wide_repr\n\n with option_context("display.width", 120):\n wider_repr = repr(df)\n assert len(wider_repr) < len(wide_repr)\n\n def test_wide_repr_wide_columns(self):\n with option_context("mode.sim_interactive", True, "display.max_columns", 20):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)),\n columns=["a" * 90, "b" * 90, "c" * 90],\n )\n rep_str = repr(df)\n\n assert len(rep_str.splitlines()) == 20\n\n def test_wide_repr_named(self):\n with option_context("mode.sim_interactive", True, "display.max_columns", 20):\n max_cols = get_option("display.max_columns")\n df = DataFrame([["a" * 25] * (max_cols - 1)] * 10)\n df.index.name = "DataFrame Index"\n with option_context("display.expand_frame_repr", False):\n rep_str = repr(df)\n with option_context("display.expand_frame_repr", True):\n wide_repr = repr(df)\n assert rep_str != wide_repr\n\n with option_context("display.width", 150):\n wider_repr = repr(df)\n assert len(wider_repr) < len(wide_repr)\n\n for line in wide_repr.splitlines()[1::13]:\n assert "DataFrame Index" in line\n\n def test_wide_repr_multiindex(self):\n with option_context("mode.sim_interactive", True, "display.max_columns", 20):\n midx = MultiIndex.from_arrays([["a" * 5] * 10] * 2)\n max_cols = get_option("display.max_columns")\n df = DataFrame([["a" * 25] * (max_cols - 1)] * 10, index=midx)\n df.index.names = ["Level 0", "Level 1"]\n with option_context("display.expand_frame_repr", False):\n rep_str = repr(df)\n with option_context("display.expand_frame_repr", True):\n wide_repr = repr(df)\n assert rep_str != wide_repr\n\n with option_context("display.width", 150):\n wider_repr = repr(df)\n assert len(wider_repr) < len(wide_repr)\n\n for line in wide_repr.splitlines()[1::13]:\n assert "Level 0 Level 1" in line\n\n def test_wide_repr_multiindex_cols(self):\n with option_context("mode.sim_interactive", True, "display.max_columns", 20):\n max_cols = get_option("display.max_columns")\n midx = MultiIndex.from_arrays([["a" * 5] * 10] * 2)\n mcols = MultiIndex.from_arrays([["b" * 3] * (max_cols - 1)] * 2)\n df = DataFrame(\n [["c" * 25] * (max_cols - 1)] * 10, index=midx, columns=mcols\n )\n df.index.names = ["Level 0", "Level 1"]\n with option_context("display.expand_frame_repr", False):\n rep_str = repr(df)\n with option_context("display.expand_frame_repr", True):\n wide_repr = repr(df)\n assert rep_str != wide_repr\n\n with option_context("display.width", 150, "display.max_columns", 20):\n wider_repr = repr(df)\n assert len(wider_repr) < len(wide_repr)\n\n def test_wide_repr_unicode(self):\n with option_context("mode.sim_interactive", True, "display.max_columns", 20):\n max_cols = 20\n df = DataFrame([["a" * 25] * 10] * (max_cols - 1))\n with option_context("display.expand_frame_repr", False):\n rep_str = repr(df)\n with option_context("display.expand_frame_repr", True):\n wide_repr = repr(df)\n assert rep_str != wide_repr\n\n with option_context("display.width", 150):\n wider_repr = repr(df)\n assert len(wider_repr) < len(wide_repr)\n\n def test_wide_repr_wide_long_columns(self):\n with option_context("mode.sim_interactive", True):\n df = DataFrame({"a": ["a" * 30, "b" * 30], "b": ["c" * 70, "d" * 80]})\n\n result = repr(df)\n assert "ccccc" in result\n assert "ddddd" in result\n\n def test_long_series(self):\n n = 1000\n s = Series(\n np.random.default_rng(2).integers(-50, 50, n),\n index=[f"s{x:04d}" for x in range(n)],\n dtype="int64",\n )\n\n str_rep = str(s)\n nmatches = len(re.findall("dtype", str_rep))\n assert nmatches == 1\n\n def test_to_string_ascii_error(self):\n data = [\n (\n "0 ",\n " .gitignore ",\n " 5 ",\n " \xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2",\n )\n ]\n df = DataFrame(data)\n\n # it works!\n repr(df)\n\n def test_show_dimensions(self):\n df = DataFrame(123, index=range(10, 15), columns=range(30))\n\n with option_context(\n "display.max_rows",\n 10,\n "display.max_columns",\n 40,\n "display.width",\n 500,\n "display.expand_frame_repr",\n "info",\n "display.show_dimensions",\n True,\n ):\n assert "5 rows" in str(df)\n assert "5 rows" in df._repr_html_()\n with option_context(\n "display.max_rows",\n 10,\n "display.max_columns",\n 40,\n "display.width",\n 500,\n "display.expand_frame_repr",\n "info",\n "display.show_dimensions",\n False,\n ):\n assert "5 rows" not in str(df)\n assert "5 rows" not in df._repr_html_()\n with option_context(\n "display.max_rows",\n 2,\n "display.max_columns",\n 2,\n "display.width",\n 500,\n "display.expand_frame_repr",\n "info",\n "display.show_dimensions",\n "truncate",\n ):\n assert "5 rows" in str(df)\n assert "5 rows" in df._repr_html_()\n with option_context(\n "display.max_rows",\n 10,\n "display.max_columns",\n 40,\n "display.width",\n 500,\n "display.expand_frame_repr",\n "info",\n "display.show_dimensions",\n "truncate",\n ):\n assert "5 rows" not in str(df)\n assert "5 rows" not in df._repr_html_()\n\n def test_info_repr(self):\n # GH#21746 For tests inside a terminal (i.e. not CI) we need to detect\n # the terminal size to ensure that we try to print something "too big"\n term_width, term_height = get_terminal_size()\n\n max_rows = 60\n max_cols = 20 + (max(term_width, 80) - 80) // 4\n # Long\n h, w = max_rows + 1, max_cols - 1\n df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})\n assert has_vertically_truncated_repr(df)\n with option_context("display.large_repr", "info"):\n assert has_info_repr(df)\n\n # Wide\n h, w = max_rows - 1, max_cols + 1\n df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})\n assert has_horizontally_truncated_repr(df)\n with option_context(\n "display.large_repr", "info", "display.max_columns", max_cols\n ):\n assert has_info_repr(df)\n\n def test_info_repr_max_cols(self):\n # GH #6939\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))\n with option_context(\n "display.large_repr",\n "info",\n "display.max_columns",\n 1,\n "display.max_info_columns",\n 4,\n ):\n assert has_non_verbose_info_repr(df)\n\n with option_context(\n "display.large_repr",\n "info",\n "display.max_columns",\n 1,\n "display.max_info_columns",\n 5,\n ):\n assert not has_non_verbose_info_repr(df)\n\n # FIXME: don't leave commented-out\n # test verbose overrides\n # set_option('display.max_info_columns', 4) # exceeded\n\n def test_pprint_pathological_object(self):\n """\n If the test fails, it at least won't hang.\n """\n\n class A:\n def __getitem__(self, key):\n return 3 # obviously simplified\n\n df = DataFrame([A()])\n repr(df) # just don't die\n\n def test_float_trim_zeros(self):\n vals = [\n 2.08430917305e10,\n 3.52205017305e10,\n 2.30674817305e10,\n 2.03954217305e10,\n 5.59897817305e10,\n ]\n skip = True\n for line in repr(DataFrame({"A": vals})).split("\n")[:-2]:\n if line.startswith("dtype:"):\n continue\n if _three_digit_exp():\n assert ("+010" in line) or skip\n else:\n assert ("+10" in line) or skip\n skip = False\n\n @pytest.mark.parametrize(\n "data, expected",\n [\n (["3.50"], "0 3.50\ndtype: object"),\n ([1.20, "1.00"], "0 1.2\n1 1.00\ndtype: object"),\n ([np.nan], "0 NaN\ndtype: float64"),\n ([None], "0 None\ndtype: object"),\n (["3.50", np.nan], "0 3.50\n1 NaN\ndtype: object"),\n ([3.50, np.nan], "0 3.5\n1 NaN\ndtype: float64"),\n ([3.50, np.nan, "3.50"], "0 3.5\n1 NaN\n2 3.50\ndtype: object"),\n ([3.50, None, "3.50"], "0 3.5\n1 None\n2 3.50\ndtype: object"),\n ],\n )\n def test_repr_str_float_truncation(self, data, expected, using_infer_string):\n # GH#38708\n series = Series(data, dtype=object if "3.50" in data else None)\n result = repr(series)\n assert result == expected\n\n @pytest.mark.parametrize(\n "float_format,expected",\n [\n ("{:,.0f}".format, "0 1,000\n1 test\ndtype: object"),\n ("{:.4f}".format, "0 1000.0000\n1 test\ndtype: object"),\n ],\n )\n def test_repr_float_format_in_object_col(self, float_format, expected):\n # GH#40024\n df = Series([1000.0, "test"])\n with option_context("display.float_format", float_format):\n result = repr(df)\n\n assert result == expected\n\n def test_period(self):\n # GH 12615\n df = DataFrame(\n {\n "A": pd.period_range("2013-01", periods=4, freq="M"),\n "B": [\n pd.Period("2011-01", freq="M"),\n pd.Period("2011-02-01", freq="D"),\n pd.Period("2011-03-01 09:00", freq="h"),\n pd.Period("2011-04", freq="M"),\n ],\n "C": list("abcd"),\n }\n )\n exp = (\n " A B C\n"\n "0 2013-01 2011-01 a\n"\n "1 2013-02 2011-02-01 b\n"\n "2 2013-03 2011-03-01 09:00 c\n"\n "3 2013-04 2011-04 d"\n )\n assert str(df) == exp\n\n @pytest.mark.parametrize(\n "length, max_rows, min_rows, expected",\n [\n (10, 10, 10, 10),\n (10, 10, None, 10),\n (10, 8, None, 8),\n (20, 30, 10, 30), # max_rows > len(frame), hence max_rows\n (50, 30, 10, 10), # max_rows < len(frame), hence min_rows\n (100, 60, 10, 10), # same\n (60, 60, 10, 60), # edge case\n (61, 60, 10, 10), # edge case\n ],\n )\n def test_max_rows_fitted(self, length, min_rows, max_rows, expected):\n """Check that display logic is correct.\n\n GH #37359\n\n See description here:\n https://pandas.pydata.org/docs/dev/user_guide/options.html#frequently-used-options\n """\n formatter = fmt.DataFrameFormatter(\n DataFrame(np.random.default_rng(2).random((length, 3))),\n max_rows=max_rows,\n min_rows=min_rows,\n )\n result = formatter.max_rows_fitted\n assert result == expected\n\n\ndef gen_series_formatting():\n s1 = Series(["a"] * 100)\n s2 = Series(["ab"] * 100)\n s3 = Series(["a", "ab", "abc", "abcd", "abcde", "abcdef"])\n s4 = s3[::-1]\n test_sers = {"onel": s1, "twol": s2, "asc": s3, "desc": s4}\n return test_sers\n\n\nclass TestSeriesFormatting:\n def test_freq_name_separation(self):\n s = Series(\n np.random.default_rng(2).standard_normal(10),\n index=date_range("1/1/2000", periods=10),\n name=0,\n )\n\n result = repr(s)\n assert "Freq: D, Name: 0" in result\n\n def test_unicode_name_in_footer(self):\n s = Series([1, 2], name="\u05e2\u05d1\u05e8\u05d9\u05ea")\n sf = fmt.SeriesFormatter(s, name="\u05e2\u05d1\u05e8\u05d9\u05ea")\n sf._get_footer() # should not raise exception\n\n @pytest.mark.xfail(using_string_dtype(), reason="Fixup when arrow is default")\n def test_east_asian_unicode_series(self):\n # not aligned properly because of east asian width\n\n # unicode index\n s = Series(["a", "bb", "CCC", "D"], index=["あ", "いい", "ううう", "ええええ"])\n expected = "".join(\n [\n "あ a\n",\n "いい bb\n",\n "ううう CCC\n",\n "ええええ D\ndtype: object",\n ]\n )\n assert repr(s) == expected\n\n # unicode values\n s = Series(["あ", "いい", "ううう", "ええええ"], index=["a", "bb", "c", "ddd"])\n expected = "".join(\n [\n "a あ\n",\n "bb いい\n",\n "c ううう\n",\n "ddd ええええ\n",\n "dtype: object",\n ]\n )\n\n assert repr(s) == expected\n\n # both\n s = Series(\n ["あ", "いい", "ううう", "ええええ"],\n index=["ああ", "いいいい", "う", "えええ"],\n )\n expected = "".join(\n [\n "ああ あ\n",\n "いいいい いい\n",\n "う ううう\n",\n "えええ ええええ\n",\n "dtype: object",\n ]\n )\n\n assert repr(s) == expected\n\n # unicode footer\n s = Series(\n ["あ", "いい", "ううう", "ええええ"],\n index=["ああ", "いいいい", "う", "えええ"],\n name="おおおおおおお",\n )\n expected = (\n "ああ あ\nいいいい いい\nう ううう\n"\n "えええ ええええ\nName: おおおおおおお, dtype: object"\n )\n assert repr(s) == expected\n\n # MultiIndex\n idx = MultiIndex.from_tuples(\n [("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]\n )\n s = Series([1, 22, 3333, 44444], index=idx)\n expected = (\n "あ いい 1\n"\n "う え 22\n"\n "おおお かかかか 3333\n"\n "き くく 44444\ndtype: int64"\n )\n assert repr(s) == expected\n\n # object dtype, shorter than unicode repr\n s = Series([1, 22, 3333, 44444], index=[1, "AB", np.nan, "あああ"])\n expected = (\n "1 1\nAB 22\nNaN 3333\nあああ 44444\ndtype: int64"\n )\n assert repr(s) == expected\n\n # object dtype, longer than unicode repr\n s = Series(\n [1, 22, 3333, 44444], index=[1, "AB", Timestamp("2011-01-01"), "あああ"]\n )\n expected = (\n "1 1\n"\n "AB 22\n"\n "2011-01-01 00:00:00 3333\n"\n "あああ 44444\ndtype: int64"\n )\n assert repr(s) == expected\n\n # truncate\n with option_context("display.max_rows", 3):\n s = Series(["あ", "いい", "ううう", "ええええ"], name="おおおおおおお")\n\n expected = (\n "0 あ\n ... \n"\n "3 ええええ\n"\n "Name: おおおおおおお, Length: 4, dtype: object"\n )\n assert repr(s) == expected\n\n s.index = ["ああ", "いいいい", "う", "えええ"]\n expected = (\n "ああ あ\n ... \n"\n "えええ ええええ\n"\n "Name: おおおおおおお, Length: 4, dtype: object"\n )\n assert repr(s) == expected\n\n # Enable Unicode option -----------------------------------------\n with option_context("display.unicode.east_asian_width", True):\n # unicode index\n s = Series(\n ["a", "bb", "CCC", "D"],\n index=["あ", "いい", "ううう", "ええええ"],\n )\n expected = (\n "あ a\nいい bb\nううう CCC\n"\n "ええええ D\ndtype: object"\n )\n assert repr(s) == expected\n\n # unicode values\n s = Series(\n ["あ", "いい", "ううう", "ええええ"],\n index=["a", "bb", "c", "ddd"],\n )\n expected = (\n "a あ\nbb いい\nc ううう\n"\n "ddd ええええ\ndtype: object"\n )\n assert repr(s) == expected\n # both\n s = Series(\n ["あ", "いい", "ううう", "ええええ"],\n index=["ああ", "いいいい", "う", "えええ"],\n )\n expected = (\n "ああ あ\n"\n "いいいい いい\n"\n "う ううう\n"\n "えええ ええええ\ndtype: object"\n )\n assert repr(s) == expected\n\n # unicode footer\n s = Series(\n ["あ", "いい", "ううう", "ええええ"],\n index=["ああ", "いいいい", "う", "えええ"],\n name="おおおおおおお",\n )\n expected = (\n "ああ あ\n"\n "いいいい いい\n"\n "う ううう\n"\n "えええ ええええ\n"\n "Name: おおおおおおお, dtype: object"\n )\n assert repr(s) == expected\n\n # MultiIndex\n idx = MultiIndex.from_tuples(\n [("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]\n )\n s = Series([1, 22, 3333, 44444], index=idx)\n expected = (\n "あ いい 1\n"\n "う え 22\n"\n "おおお かかかか 3333\n"\n "き くく 44444\n"\n "dtype: int64"\n )\n assert repr(s) == expected\n\n # object dtype, shorter than unicode repr\n s = Series([1, 22, 3333, 44444], index=[1, "AB", np.nan, "あああ"])\n expected = (\n "1 1\nAB 22\nNaN 3333\n"\n "あああ 44444\ndtype: int64"\n )\n assert repr(s) == expected\n\n # object dtype, longer than unicode repr\n s = Series(\n [1, 22, 3333, 44444],\n index=[1, "AB", Timestamp("2011-01-01"), "あああ"],\n )\n expected = (\n "1 1\n"\n "AB 22\n"\n "2011-01-01 00:00:00 3333\n"\n "あああ 44444\ndtype: int64"\n )\n assert repr(s) == expected\n\n # truncate\n with option_context("display.max_rows", 3):\n s = Series(["あ", "いい", "ううう", "ええええ"], name="おおおおおおお")\n expected = (\n "0 あ\n ... \n"\n "3 ええええ\n"\n "Name: おおおおおおお, Length: 4, dtype: object"\n )\n assert repr(s) == expected\n\n s.index = ["ああ", "いいいい", "う", "えええ"]\n expected = (\n "ああ あ\n"\n " ... \n"\n "えええ ええええ\n"\n "Name: おおおおおおお, Length: 4, dtype: object"\n )\n assert repr(s) == expected\n\n # ambiguous unicode\n s = Series(\n ["¡¡", "い¡¡", "ううう", "ええええ"],\n index=["ああ", "¡¡¡¡いい", "¡¡", "えええ"],\n )\n expected = (\n "ああ ¡¡\n"\n "¡¡¡¡いい い¡¡\n"\n "¡¡ ううう\n"\n "えええ ええええ\ndtype: object"\n )\n assert repr(s) == expected\n\n def test_float_trim_zeros(self):\n vals = [\n 2.08430917305e10,\n 3.52205017305e10,\n 2.30674817305e10,\n 2.03954217305e10,\n 5.59897817305e10,\n ]\n for line in repr(Series(vals)).split("\n"):\n if line.startswith("dtype:"):\n continue\n if _three_digit_exp():\n assert "+010" in line\n else:\n assert "+10" in line\n\n @pytest.mark.parametrize(\n "start_date",\n [\n "2017-01-01 23:59:59.999999999",\n "2017-01-01 23:59:59.99999999",\n "2017-01-01 23:59:59.9999999",\n "2017-01-01 23:59:59.999999",\n "2017-01-01 23:59:59.99999",\n "2017-01-01 23:59:59.9999",\n ],\n )\n def test_datetimeindex_highprecision(self, start_date):\n # GH19030\n # Check that high-precision time values for the end of day are\n # included in repr for DatetimeIndex\n s1 = Series(date_range(start=start_date, freq="D", periods=5))\n result = str(s1)\n assert start_date in result\n\n dti = date_range(start=start_date, freq="D", periods=5)\n s2 = Series(3, index=dti)\n result = str(s2.index)\n assert start_date in result\n\n def test_mixed_datetime64(self):\n df = DataFrame({"A": [1, 2], "B": ["2012-01-01", "2012-01-02"]})\n df["B"] = pd.to_datetime(df.B)\n\n result = repr(df.loc[0])\n assert "2012-01-01" in result\n\n def test_period(self):\n # GH 12615\n index = pd.period_range("2013-01", periods=6, freq="M")\n s = Series(np.arange(6, dtype="int64"), index=index)\n exp = (\n "2013-01 0\n"\n "2013-02 1\n"\n "2013-03 2\n"\n "2013-04 3\n"\n "2013-05 4\n"\n "2013-06 5\n"\n "Freq: M, dtype: int64"\n )\n assert str(s) == exp\n\n s = Series(index)\n exp = (\n "0 2013-01\n"\n "1 2013-02\n"\n "2 2013-03\n"\n "3 2013-04\n"\n "4 2013-05\n"\n "5 2013-06\n"\n "dtype: period[M]"\n )\n assert str(s) == exp\n\n # periods with mixed freq\n s = Series(\n [\n pd.Period("2011-01", freq="M"),\n pd.Period("2011-02-01", freq="D"),\n pd.Period("2011-03-01 09:00", freq="h"),\n ]\n )\n exp = (\n "0 2011-01\n1 2011-02-01\n"\n "2 2011-03-01 09:00\ndtype: object"\n )\n assert str(s) == exp\n\n def test_max_multi_index_display(self):\n # GH 7101\n\n # doc example (indexing.rst)\n\n # multi-index\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 index = MultiIndex.from_tuples(tuples, names=["first", "second"])\n s = Series(np.random.default_rng(2).standard_normal(8), index=index)\n\n with option_context("display.max_rows", 10):\n assert len(str(s).split("\n")) == 10\n with option_context("display.max_rows", 3):\n assert len(str(s).split("\n")) == 5\n with option_context("display.max_rows", 2):\n assert len(str(s).split("\n")) == 5\n with option_context("display.max_rows", 1):\n assert len(str(s).split("\n")) == 4\n with option_context("display.max_rows", 0):\n assert len(str(s).split("\n")) == 10\n\n # index\n s = Series(np.random.default_rng(2).standard_normal(8), None)\n\n with option_context("display.max_rows", 10):\n assert len(str(s).split("\n")) == 9\n with option_context("display.max_rows", 3):\n assert len(str(s).split("\n")) == 4\n with option_context("display.max_rows", 2):\n assert len(str(s).split("\n")) == 4\n with option_context("display.max_rows", 1):\n assert len(str(s).split("\n")) == 3\n with option_context("display.max_rows", 0):\n assert len(str(s).split("\n")) == 9\n\n # Make sure #8532 is fixed\n def test_consistent_format(self):\n s = Series([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9999, 1, 1] * 10)\n with option_context("display.max_rows", 10, "display.show_dimensions", False):\n res = repr(s)\n exp = (\n "0 1.0000\n1 1.0000\n2 1.0000\n3 "\n "1.0000\n4 1.0000\n ... \n125 "\n "1.0000\n126 1.0000\n127 0.9999\n128 "\n "1.0000\n129 1.0000\ndtype: float64"\n )\n assert res == exp\n\n def chck_ncols(self, s):\n lines = [\n line for line in repr(s).split("\n") if not re.match(r"[^\.]*\.+", line)\n ][:-1]\n ncolsizes = len({len(line.strip()) for line in lines})\n assert ncolsizes == 1\n\n @pytest.mark.xfail(using_string_dtype(), reason="change when arrow is default")\n def test_format_explicit(self):\n test_sers = gen_series_formatting()\n with option_context("display.max_rows", 4, "display.show_dimensions", False):\n res = repr(test_sers["onel"])\n exp = "0 a\n1 a\n ..\n98 a\n99 a\ndtype: object"\n assert exp == res\n res = repr(test_sers["twol"])\n exp = "0 ab\n1 ab\n ..\n98 ab\n99 ab\ndtype: object"\n assert exp == res\n res = repr(test_sers["asc"])\n exp = (\n "0 a\n1 ab\n ... \n4 abcde\n5 "\n "abcdef\ndtype: object"\n )\n assert exp == res\n res = repr(test_sers["desc"])\n exp = (\n "5 abcdef\n4 abcde\n ... \n1 ab\n0 "\n "a\ndtype: object"\n )\n assert exp == res\n\n def test_ncols(self):\n test_sers = gen_series_formatting()\n for s in test_sers.values():\n self.chck_ncols(s)\n\n def test_max_rows_eq_one(self):\n s = Series(range(10), dtype="int64")\n with option_context("display.max_rows", 1):\n strrepr = repr(s).split("\n")\n exp1 = ["0", "0"]\n res1 = strrepr[0].split()\n assert exp1 == res1\n exp2 = [".."]\n res2 = strrepr[1].split()\n assert exp2 == res2\n\n def test_truncate_ndots(self):\n def getndots(s):\n return len(re.match(r"[^\.]*(\.*)", s).groups()[0])\n\n s = Series([0, 2, 3, 6])\n with option_context("display.max_rows", 2):\n strrepr = repr(s).replace("\n", "")\n assert getndots(strrepr) == 2\n\n s = Series([0, 100, 200, 400])\n with option_context("display.max_rows", 2):\n strrepr = repr(s).replace("\n", "")\n assert getndots(strrepr) == 3\n\n def test_show_dimensions(self):\n # gh-7117\n s = Series(range(5))\n\n assert "Length" not in repr(s)\n\n with option_context("display.max_rows", 4):\n assert "Length" in repr(s)\n\n with option_context("display.show_dimensions", True):\n assert "Length" in repr(s)\n\n with option_context("display.max_rows", 4, "display.show_dimensions", False):\n assert "Length" not in repr(s)\n\n def test_repr_min_rows(self):\n s = Series(range(20))\n\n # default setting no truncation even if above min_rows\n assert ".." not in repr(s)\n\n s = Series(range(61))\n\n # default of max_rows 60 triggers truncation if above\n assert ".." in repr(s)\n\n with option_context("display.max_rows", 10, "display.min_rows", 4):\n # truncated after first two rows\n assert ".." in repr(s)\n assert "2 " not in repr(s)\n\n with option_context("display.max_rows", 12, "display.min_rows", None):\n # when set to None, follow value of max_rows\n assert "5 5" in repr(s)\n\n with option_context("display.max_rows", 10, "display.min_rows", 12):\n # when set value higher as max_rows, use the minimum\n assert "5 5" not in repr(s)\n\n with option_context("display.max_rows", None, "display.min_rows", 12):\n # max_rows of None -> never truncate\n assert ".." not in repr(s)\n\n\nclass TestGenericArrayFormatter:\n def test_1d_array(self):\n # _GenericArrayFormatter is used on types for which there isn't a dedicated\n # formatter. np.bool_ is one of those types.\n obj = fmt._GenericArrayFormatter(np.array([True, False]))\n res = obj.get_result()\n assert len(res) == 2\n # Results should be right-justified.\n assert res[0] == " True"\n assert res[1] == " False"\n\n def test_2d_array(self):\n obj = fmt._GenericArrayFormatter(np.array([[True, False], [False, True]]))\n res = obj.get_result()\n assert len(res) == 2\n assert res[0] == " [True, False]"\n assert res[1] == " [False, True]"\n\n def test_3d_array(self):\n obj = fmt._GenericArrayFormatter(\n np.array([[[True, True], [False, False]], [[False, True], [True, False]]])\n )\n res = obj.get_result()\n assert len(res) == 2\n assert res[0] == " [[True, True], [False, False]]"\n assert res[1] == " [[False, True], [True, False]]"\n\n def test_2d_extension_type(self):\n # GH 33770\n\n # Define a stub extension type with just enough code to run Series.__repr__()\n class DtypeStub(pd.api.extensions.ExtensionDtype):\n @property\n def type(self):\n return np.ndarray\n\n @property\n def name(self):\n return "DtypeStub"\n\n class ExtTypeStub(pd.api.extensions.ExtensionArray):\n def __len__(self) -> int:\n return 2\n\n def __getitem__(self, ix):\n return [ix == 1, ix == 0]\n\n @property\n def dtype(self):\n return DtypeStub()\n\n series = Series(ExtTypeStub(), copy=False)\n res = repr(series) # This line crashed before #33770 was fixed.\n expected = "\n".join(\n ["0 [False True]", "1 [True False]", "dtype: DtypeStub"]\n )\n assert res == expected\n\n\ndef _three_digit_exp():\n return f"{1.7e8:.4g}" == "1.7e+008"\n\n\nclass TestFloatArrayFormatter:\n def test_misc(self):\n obj = fmt.FloatArrayFormatter(np.array([], dtype=np.float64))\n result = obj.get_result()\n assert len(result) == 0\n\n def test_format(self):\n obj = fmt.FloatArrayFormatter(np.array([12, 0], dtype=np.float64))\n result = obj.get_result()\n assert result[0] == " 12.0"\n assert result[1] == " 0.0"\n\n def test_output_display_precision_trailing_zeroes(self):\n # Issue #20359: trimming zeros while there is no decimal point\n\n # Happens when display precision is set to zero\n with option_context("display.precision", 0):\n s = Series([840.0, 4200.0])\n expected_output = "0 840\n1 4200\ndtype: float64"\n assert str(s) == expected_output\n\n @pytest.mark.parametrize(\n "value,expected",\n [\n ([9.4444], " 0\n0 9"),\n ([0.49], " 0\n0 5e-01"),\n ([10.9999], " 0\n0 11"),\n ([9.5444, 9.6], " 0\n0 10\n1 10"),\n ([0.46, 0.78, -9.9999], " 0\n0 5e-01\n1 8e-01\n2 -1e+01"),\n ],\n )\n def test_set_option_precision(self, value, expected):\n # Issue #30122\n # Precision was incorrectly shown\n\n with option_context("display.precision", 0):\n df_value = DataFrame(value)\n assert str(df_value) == expected\n\n def test_output_significant_digits(self):\n # Issue #9764\n\n # In case default display precision changes:\n with option_context("display.precision", 6):\n # DataFrame example from issue #9764\n d = DataFrame(\n {\n "col1": [\n 9.999e-8,\n 1e-7,\n 1.0001e-7,\n 2e-7,\n 4.999e-7,\n 5e-7,\n 5.0001e-7,\n 6e-7,\n 9.999e-7,\n 1e-6,\n 1.0001e-6,\n 2e-6,\n 4.999e-6,\n 5e-6,\n 5.0001e-6,\n 6e-6,\n ]\n }\n )\n\n expected_output = {\n (0, 6): " col1\n"\n "0 9.999000e-08\n"\n "1 1.000000e-07\n"\n "2 1.000100e-07\n"\n "3 2.000000e-07\n"\n "4 4.999000e-07\n"\n "5 5.000000e-07",\n (1, 6): " col1\n"\n "1 1.000000e-07\n"\n "2 1.000100e-07\n"\n "3 2.000000e-07\n"\n "4 4.999000e-07\n"\n "5 5.000000e-07",\n (1, 8): " col1\n"\n "1 1.000000e-07\n"\n "2 1.000100e-07\n"\n "3 2.000000e-07\n"\n "4 4.999000e-07\n"\n "5 5.000000e-07\n"\n "6 5.000100e-07\n"\n "7 6.000000e-07",\n (8, 16): " col1\n"\n "8 9.999000e-07\n"\n "9 1.000000e-06\n"\n "10 1.000100e-06\n"\n "11 2.000000e-06\n"\n "12 4.999000e-06\n"\n "13 5.000000e-06\n"\n "14 5.000100e-06\n"\n "15 6.000000e-06",\n (9, 16): " col1\n"\n "9 0.000001\n"\n "10 0.000001\n"\n "11 0.000002\n"\n "12 0.000005\n"\n "13 0.000005\n"\n "14 0.000005\n"\n "15 0.000006",\n }\n\n for (start, stop), v in expected_output.items():\n assert str(d[start:stop]) == v\n\n def test_too_long(self):\n # GH 10451\n with option_context("display.precision", 4):\n # need both a number > 1e6 and something that normally formats to\n # having length > display.precision + 6\n df = DataFrame({"x": [12345.6789]})\n assert str(df) == " x\n0 12345.6789"\n df = DataFrame({"x": [2e6]})\n assert str(df) == " x\n0 2000000.0"\n df = DataFrame({"x": [12345.6789, 2e6]})\n assert str(df) == " x\n0 1.2346e+04\n1 2.0000e+06"\n\n\nclass TestTimedelta64Formatter:\n def test_days(self):\n x = pd.to_timedelta(list(range(5)) + [NaT], unit="D")._values\n result = fmt._Timedelta64Formatter(x).get_result()\n assert result[0].strip() == "0 days"\n assert result[1].strip() == "1 days"\n\n result = fmt._Timedelta64Formatter(x[1:2]).get_result()\n assert result[0].strip() == "1 days"\n\n result = fmt._Timedelta64Formatter(x).get_result()\n assert result[0].strip() == "0 days"\n assert result[1].strip() == "1 days"\n\n result = fmt._Timedelta64Formatter(x[1:2]).get_result()\n assert result[0].strip() == "1 days"\n\n def test_days_neg(self):\n x = pd.to_timedelta(list(range(5)) + [NaT], unit="D")._values\n result = fmt._Timedelta64Formatter(-x).get_result()\n assert result[0].strip() == "0 days"\n assert result[1].strip() == "-1 days"\n\n def test_subdays(self):\n y = pd.to_timedelta(list(range(5)) + [NaT], unit="s")._values\n result = fmt._Timedelta64Formatter(y).get_result()\n assert result[0].strip() == "0 days 00:00:00"\n assert result[1].strip() == "0 days 00:00:01"\n\n def test_subdays_neg(self):\n y = pd.to_timedelta(list(range(5)) + [NaT], unit="s")._values\n result = fmt._Timedelta64Formatter(-y).get_result()\n assert result[0].strip() == "0 days 00:00:00"\n assert result[1].strip() == "-1 days +23:59:59"\n\n def test_zero(self):\n x = pd.to_timedelta(list(range(1)) + [NaT], unit="D")._values\n result = fmt._Timedelta64Formatter(x).get_result()\n assert result[0].strip() == "0 days"\n\n x = pd.to_timedelta(list(range(1)), unit="D")._values\n result = fmt._Timedelta64Formatter(x).get_result()\n assert result[0].strip() == "0 days"\n\n\nclass TestDatetime64Formatter:\n def test_mixed(self):\n x = Series([datetime(2013, 1, 1), datetime(2013, 1, 1, 12), NaT])._values\n result = fmt._Datetime64Formatter(x).get_result()\n assert result[0].strip() == "2013-01-01 00:00:00"\n assert result[1].strip() == "2013-01-01 12:00:00"\n\n def test_dates(self):\n x = Series([datetime(2013, 1, 1), datetime(2013, 1, 2), NaT])._values\n result = fmt._Datetime64Formatter(x).get_result()\n assert result[0].strip() == "2013-01-01"\n assert result[1].strip() == "2013-01-02"\n\n def test_date_nanos(self):\n x = Series([Timestamp(200)])._values\n result = fmt._Datetime64Formatter(x).get_result()\n assert result[0].strip() == "1970-01-01 00:00:00.000000200"\n\n def test_dates_display(self):\n # 10170\n # make sure that we are consistently display date formatting\n x = Series(date_range("20130101 09:00:00", periods=5, freq="D"))\n x.iloc[1] = np.nan\n result = fmt._Datetime64Formatter(x._values).get_result()\n assert result[0].strip() == "2013-01-01 09:00:00"\n assert result[1].strip() == "NaT"\n assert result[4].strip() == "2013-01-05 09:00:00"\n\n x = Series(date_range("20130101 09:00:00", periods=5, freq="s"))\n x.iloc[1] = np.nan\n result = fmt._Datetime64Formatter(x._values).get_result()\n assert result[0].strip() == "2013-01-01 09:00:00"\n assert result[1].strip() == "NaT"\n assert result[4].strip() == "2013-01-01 09:00:04"\n\n x = Series(date_range("20130101 09:00:00", periods=5, freq="ms"))\n x.iloc[1] = np.nan\n result = fmt._Datetime64Formatter(x._values).get_result()\n assert result[0].strip() == "2013-01-01 09:00:00.000"\n assert result[1].strip() == "NaT"\n assert result[4].strip() == "2013-01-01 09:00:00.004"\n\n x = Series(date_range("20130101 09:00:00", periods=5, freq="us"))\n x.iloc[1] = np.nan\n result = fmt._Datetime64Formatter(x._values).get_result()\n assert result[0].strip() == "2013-01-01 09:00:00.000000"\n assert result[1].strip() == "NaT"\n assert result[4].strip() == "2013-01-01 09:00:00.000004"\n\n x = Series(date_range("20130101 09:00:00", periods=5, freq="ns"))\n x.iloc[1] = np.nan\n result = fmt._Datetime64Formatter(x._values).get_result()\n assert result[0].strip() == "2013-01-01 09:00:00.000000000"\n assert result[1].strip() == "NaT"\n assert result[4].strip() == "2013-01-01 09:00:00.000000004"\n\n def test_datetime64formatter_yearmonth(self):\n x = Series([datetime(2016, 1, 1), datetime(2016, 2, 2)])._values\n\n def format_func(x):\n return x.strftime("%Y-%m")\n\n formatter = fmt._Datetime64Formatter(x, formatter=format_func)\n result = formatter.get_result()\n assert result == ["2016-01", "2016-02"]\n\n def test_datetime64formatter_hoursecond(self):\n x = Series(\n pd.to_datetime(["10:10:10.100", "12:12:12.120"], format="%H:%M:%S.%f")\n )._values\n\n def format_func(x):\n return x.strftime("%H:%M")\n\n formatter = fmt._Datetime64Formatter(x, formatter=format_func)\n result = formatter.get_result()\n assert result == ["10:10", "12:12"]\n\n def test_datetime64formatter_tz_ms(self):\n x = (\n Series(\n np.array(["2999-01-01", "2999-01-02", "NaT"], dtype="datetime64[ms]")\n )\n .dt.tz_localize("US/Pacific")\n ._values\n )\n result = fmt._Datetime64TZFormatter(x).get_result()\n assert result[0].strip() == "2999-01-01 00:00:00-08:00"\n assert result[1].strip() == "2999-01-02 00:00:00-08:00"\n\n\nclass TestFormatPercentiles:\n @pytest.mark.parametrize(\n "percentiles, expected",\n [\n (\n [0.01999, 0.02001, 0.5, 0.666666, 0.9999],\n ["1.999%", "2.001%", "50%", "66.667%", "99.99%"],\n ),\n (\n [0, 0.5, 0.02001, 0.5, 0.666666, 0.9999],\n ["0%", "50%", "2.0%", "50%", "66.67%", "99.99%"],\n ),\n ([0.281, 0.29, 0.57, 0.58], ["28.1%", "29%", "57%", "58%"]),\n ([0.28, 0.29, 0.57, 0.58], ["28%", "29%", "57%", "58%"]),\n (\n [0.9, 0.99, 0.999, 0.9999, 0.99999],\n ["90%", "99%", "99.9%", "99.99%", "99.999%"],\n ),\n ],\n )\n def test_format_percentiles(self, percentiles, expected):\n result = fmt.format_percentiles(percentiles)\n assert result == expected\n\n @pytest.mark.parametrize(\n "percentiles",\n [\n ([0.1, np.nan, 0.5]),\n ([-0.001, 0.1, 0.5]),\n ([2, 0.1, 0.5]),\n ([0.1, 0.5, "a"]),\n ],\n )\n def test_error_format_percentiles(self, percentiles):\n msg = r"percentiles should all be in the interval \[0,1\]"\n with pytest.raises(ValueError, match=msg):\n fmt.format_percentiles(percentiles)\n\n def test_format_percentiles_integer_idx(self):\n # Issue #26660\n result = fmt.format_percentiles(np.linspace(0, 1, 10 + 1))\n expected = [\n "0%",\n "10%",\n "20%",\n "30%",\n "40%",\n "50%",\n "60%",\n "70%",\n "80%",\n "90%",\n "100%",\n ]\n assert result == expected\n\n\n@pytest.mark.parametrize("method", ["to_string", "to_html", "to_latex"])\n@pytest.mark.parametrize(\n "encoding, data",\n [(None, "abc"), ("utf-8", "abc"), ("gbk", "造成输出中文显示乱码"), ("foo", "abc")],\n)\ndef test_filepath_or_buffer_arg(\n method,\n filepath_or_buffer,\n assert_filepath_or_buffer_equals,\n encoding,\n data,\n filepath_or_buffer_id,\n):\n df = DataFrame([data])\n if method in ["to_latex"]: # uses styler implementation\n pytest.importorskip("jinja2")\n\n if filepath_or_buffer_id not in ["string", "pathlike"] and encoding is not None:\n with pytest.raises(\n ValueError, match="buf is not a file name and encoding is specified."\n ):\n getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)\n elif encoding == "foo":\n with pytest.raises(LookupError, match="unknown encoding"):\n getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)\n else:\n expected = getattr(df, method)()\n getattr(df, method)(buf=filepath_or_buffer, encoding=encoding)\n assert_filepath_or_buffer_equals(expected)\n\n\n@pytest.mark.parametrize("method", ["to_string", "to_html", "to_latex"])\ndef test_filepath_or_buffer_bad_arg_raises(float_frame, method):\n if method in ["to_latex"]: # uses styler implementation\n pytest.importorskip("jinja2")\n msg = "buf is not a file name and it has no write method"\n with pytest.raises(TypeError, match=msg):\n getattr(float_frame, method)(buf=object())\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_format.py
test_format.py
Python
83,129
0.75
0.080821
0.066
awesome-app
989
2024-05-31T23:35:44.628218
GPL-3.0
true
6b4535e0ce4361eecd39e6efa0241b12
import numpy as np\n\nimport pandas._config.config as cf\n\nfrom pandas import (\n DataFrame,\n MultiIndex,\n)\n\n\nclass TestTableSchemaRepr:\n def test_publishes(self, ip):\n ipython = ip.instance(config=ip.config)\n df = DataFrame({"A": [1, 2]})\n objects = [df["A"], df] # dataframe / series\n expected_keys = [\n {"text/plain", "application/vnd.dataresource+json"},\n {"text/plain", "text/html", "application/vnd.dataresource+json"},\n ]\n\n opt = cf.option_context("display.html.table_schema", True)\n last_obj = None\n for obj, expected in zip(objects, expected_keys):\n last_obj = obj\n with opt:\n formatted = ipython.display_formatter.format(obj)\n assert set(formatted[0].keys()) == expected\n\n with_latex = cf.option_context("styler.render.repr", "latex")\n\n with opt, with_latex:\n formatted = ipython.display_formatter.format(last_obj)\n\n expected = {\n "text/plain",\n "text/html",\n "text/latex",\n "application/vnd.dataresource+json",\n }\n assert set(formatted[0].keys()) == expected\n\n def test_publishes_not_implemented(self, ip):\n # column MultiIndex\n # GH#15996\n midx = MultiIndex.from_product([["A", "B"], ["a", "b", "c"]])\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, len(midx))), columns=midx\n )\n\n opt = cf.option_context("display.html.table_schema", True)\n\n with opt:\n formatted = ip.instance(config=ip.config).display_formatter.format(df)\n\n expected = {"text/plain", "text/html"}\n assert set(formatted[0].keys()) == expected\n\n def test_config_on(self):\n df = DataFrame({"A": [1, 2]})\n with cf.option_context("display.html.table_schema", True):\n result = df._repr_data_resource_()\n\n assert result is not None\n\n def test_config_default_off(self):\n df = DataFrame({"A": [1, 2]})\n with cf.option_context("display.html.table_schema", False):\n result = df._repr_data_resource_()\n\n assert result is None\n\n def test_enable_data_resource_formatter(self, ip):\n # GH#10491\n formatters = ip.instance(config=ip.config).display_formatter.formatters\n mimetype = "application/vnd.dataresource+json"\n\n with cf.option_context("display.html.table_schema", True):\n assert "application/vnd.dataresource+json" in formatters\n assert formatters[mimetype].enabled\n\n # still there, just disabled\n assert "application/vnd.dataresource+json" in formatters\n assert not formatters[mimetype].enabled\n\n # able to re-set\n with cf.option_context("display.html.table_schema", True):\n assert "application/vnd.dataresource+json" in formatters\n assert formatters[mimetype].enabled\n # smoke test that it works\n ip.instance(config=ip.config).display_formatter.format(cf)\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_ipython_compat.py
test_ipython_compat.py
Python
3,055
0.95
0.077778
0.085714
awesome-app
877
2024-09-09T21:53:10.863397
Apache-2.0
true
9f4d29e7ab0dd3a3f3816af6fd5d3620
# Note! This file is aimed specifically at pandas.io.formats.printing utility\n# functions, not the general printing of pandas objects.\nimport string\n\nimport pandas._config.config as cf\n\nfrom pandas.io.formats import printing\n\n\ndef test_adjoin():\n data = [["a", "b", "c"], ["dd", "ee", "ff"], ["ggg", "hhh", "iii"]]\n expected = "a dd ggg\nb ee hhh\nc ff iii"\n\n adjoined = printing.adjoin(2, *data)\n\n assert adjoined == expected\n\n\nclass TestPPrintThing:\n def test_repr_binary_type(self):\n letters = string.ascii_letters\n try:\n raw = bytes(letters, encoding=cf.get_option("display.encoding"))\n except TypeError:\n raw = bytes(letters)\n b = str(raw.decode("utf-8"))\n res = printing.pprint_thing(b, quote_strings=True)\n assert res == repr(b)\n res = printing.pprint_thing(b, quote_strings=False)\n assert res == b\n\n def test_repr_obeys_max_seq_limit(self):\n with cf.option_context("display.max_seq_items", 2000):\n assert len(printing.pprint_thing(list(range(1000)))) > 1000\n\n with cf.option_context("display.max_seq_items", 5):\n assert len(printing.pprint_thing(list(range(1000)))) < 100\n\n with cf.option_context("display.max_seq_items", 1):\n assert len(printing.pprint_thing(list(range(1000)))) < 9\n\n def test_repr_set(self):\n assert printing.pprint_thing({1}) == "{1}"\n\n\nclass TestFormatBase:\n def test_adjoin(self):\n data = [["a", "b", "c"], ["dd", "ee", "ff"], ["ggg", "hhh", "iii"]]\n expected = "a dd ggg\nb ee hhh\nc ff iii"\n\n adjoined = printing.adjoin(2, *data)\n\n assert adjoined == expected\n\n def test_adjoin_unicode(self):\n data = [["あ", "b", "c"], ["dd", "ええ", "ff"], ["ggg", "hhh", "いいい"]]\n expected = "あ dd ggg\nb ええ hhh\nc ff いいい"\n adjoined = printing.adjoin(2, *data)\n assert adjoined == expected\n\n adj = printing._EastAsianTextAdjustment()\n\n expected = """あ dd ggg\nb ええ hhh\nc ff いいい"""\n\n adjoined = adj.adjoin(2, *data)\n assert adjoined == expected\n cols = adjoined.split("\n")\n assert adj.len(cols[0]) == 13\n assert adj.len(cols[1]) == 13\n assert adj.len(cols[2]) == 16\n\n expected = """あ dd ggg\nb ええ hhh\nc ff いいい"""\n\n adjoined = adj.adjoin(7, *data)\n assert adjoined == expected\n cols = adjoined.split("\n")\n assert adj.len(cols[0]) == 23\n assert adj.len(cols[1]) == 23\n assert adj.len(cols[2]) == 26\n\n def test_justify(self):\n adj = printing._EastAsianTextAdjustment()\n\n def just(x, *args, **kwargs):\n # wrapper to test single str\n return adj.justify([x], *args, **kwargs)[0]\n\n assert just("abc", 5, mode="left") == "abc "\n assert just("abc", 5, mode="center") == " abc "\n assert just("abc", 5, mode="right") == " abc"\n assert just("abc", 5, mode="left") == "abc "\n assert just("abc", 5, mode="center") == " abc "\n assert just("abc", 5, mode="right") == " abc"\n\n assert just("パンダ", 5, mode="left") == "パンダ"\n assert just("パンダ", 5, mode="center") == "パンダ"\n assert just("パンダ", 5, mode="right") == "パンダ"\n\n assert just("パンダ", 10, mode="left") == "パンダ "\n assert just("パンダ", 10, mode="center") == " パンダ "\n assert just("パンダ", 10, mode="right") == " パンダ"\n\n def test_east_asian_len(self):\n adj = printing._EastAsianTextAdjustment()\n\n assert adj.len("abc") == 3\n assert adj.len("abc") == 3\n\n assert adj.len("パンダ") == 6\n assert adj.len("パンダ") == 5\n assert adj.len("パンダpanda") == 11\n assert adj.len("パンダpanda") == 10\n\n def test_ambiguous_width(self):\n adj = printing._EastAsianTextAdjustment()\n assert adj.len("¡¡ab") == 4\n\n with cf.option_context("display.unicode.ambiguous_as_wide", True):\n adj = printing._EastAsianTextAdjustment()\n assert adj.len("¡¡ab") == 6\n\n data = [["あ", "b", "c"], ["dd", "ええ", "ff"], ["ggg", "¡¡ab", "いいい"]]\n expected = "あ dd ggg \nb ええ ¡¡ab\nc ff いいい"\n adjoined = adj.adjoin(2, *data)\n assert adjoined == expected\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_printing.py
test_printing.py
Python
4,499
0.95
0.100775
0.03125
awesome-app
38
2024-01-25T19:26:48.802308
Apache-2.0
true
4fc63191a8605834049fe2f8b3a5c582
import io\nimport os\nimport sys\nfrom zipfile import ZipFile\n\nfrom _csv import Error\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n compat,\n)\nimport pandas._testing as tm\n\n\nclass TestToCSV:\n def test_to_csv_with_single_column(self):\n # see gh-18676, https://bugs.python.org/issue32255\n #\n # Python's CSV library adds an extraneous '""'\n # before the newline when the NaN-value is in\n # the first row. Otherwise, only the newline\n # character is added. This behavior is inconsistent\n # and was patched in https://bugs.python.org/pull_request4672.\n df1 = DataFrame([None, 1])\n expected1 = """\\n""\n1.0\n"""\n with tm.ensure_clean("test.csv") as path:\n df1.to_csv(path, header=None, index=None)\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected1\n\n df2 = DataFrame([1, None])\n expected2 = """\\n1.0\n""\n"""\n with tm.ensure_clean("test.csv") as path:\n df2.to_csv(path, header=None, index=None)\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected2\n\n def test_to_csv_default_encoding(self):\n # GH17097\n df = DataFrame({"col": ["AAAAA", "ÄÄÄÄÄ", "ßßßßß", "聞聞聞聞聞"]})\n\n with tm.ensure_clean("test.csv") as path:\n # the default to_csv encoding is uft-8.\n df.to_csv(path)\n tm.assert_frame_equal(pd.read_csv(path, index_col=0), df)\n\n def test_to_csv_quotechar(self):\n df = DataFrame({"col": [1, 2]})\n expected = """\\n"","col"\n"0","1"\n"1","2"\n"""\n\n with tm.ensure_clean("test.csv") as path:\n df.to_csv(path, quoting=1) # 1=QUOTE_ALL\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected\n\n expected = """\\n$$,$col$\n$0$,$1$\n$1$,$2$\n"""\n\n with tm.ensure_clean("test.csv") as path:\n df.to_csv(path, quoting=1, quotechar="$")\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected\n\n with tm.ensure_clean("test.csv") as path:\n with pytest.raises(TypeError, match="quotechar"):\n df.to_csv(path, quoting=1, quotechar=None)\n\n def test_to_csv_doublequote(self):\n df = DataFrame({"col": ['a"a', '"bb"']})\n expected = '''\\n"","col"\n"0","a""a"\n"1","""bb"""\n'''\n\n with tm.ensure_clean("test.csv") as path:\n df.to_csv(path, quoting=1, doublequote=True) # QUOTE_ALL\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected\n\n with tm.ensure_clean("test.csv") as path:\n with pytest.raises(Error, match="escapechar"):\n df.to_csv(path, doublequote=False) # no escapechar set\n\n def test_to_csv_escapechar(self):\n df = DataFrame({"col": ['a"a', '"bb"']})\n expected = """\\n"","col"\n"0","a\\"a"\n"1","\\"bb\\""\n"""\n\n with tm.ensure_clean("test.csv") as path: # QUOTE_ALL\n df.to_csv(path, quoting=1, doublequote=False, escapechar="\\")\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected\n\n df = DataFrame({"col": ["a,a", ",bb,"]})\n expected = """\\n,col\n0,a\\,a\n1,\\,bb\\,\n"""\n\n with tm.ensure_clean("test.csv") as path:\n df.to_csv(path, quoting=3, escapechar="\\") # QUOTE_NONE\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected\n\n def test_csv_to_string(self):\n df = DataFrame({"col": [1, 2]})\n expected_rows = [",col", "0,1", "1,2"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df.to_csv() == expected\n\n def test_to_csv_decimal(self):\n # see gh-781\n df = DataFrame({"col1": [1], "col2": ["a"], "col3": [10.1]})\n\n expected_rows = [",col1,col2,col3", "0,1,a,10.1"]\n expected_default = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df.to_csv() == expected_default\n\n expected_rows = [";col1;col2;col3", "0;1;a;10,1"]\n expected_european_excel = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df.to_csv(decimal=",", sep=";") == expected_european_excel\n\n expected_rows = [",col1,col2,col3", "0,1,a,10.10"]\n expected_float_format_default = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df.to_csv(float_format="%.2f") == expected_float_format_default\n\n expected_rows = [";col1;col2;col3", "0;1;a;10,10"]\n expected_float_format = tm.convert_rows_list_to_csv_str(expected_rows)\n assert (\n df.to_csv(decimal=",", sep=";", float_format="%.2f")\n == expected_float_format\n )\n\n # see gh-11553: testing if decimal is taken into account for '0.0'\n df = DataFrame({"a": [0, 1.1], "b": [2.2, 3.3], "c": 1})\n\n expected_rows = ["a,b,c", "0^0,2^2,1", "1^1,3^3,1"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df.to_csv(index=False, decimal="^") == expected\n\n # same but for an index\n assert df.set_index("a").to_csv(decimal="^") == expected\n\n # same for a multi-index\n assert df.set_index(["a", "b"]).to_csv(decimal="^") == expected\n\n def test_to_csv_float_format(self):\n # testing if float_format is taken into account for the index\n # GH 11553\n df = DataFrame({"a": [0, 1], "b": [2.2, 3.3], "c": 1})\n\n expected_rows = ["a,b,c", "0,2.20,1", "1,3.30,1"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df.set_index("a").to_csv(float_format="%.2f") == expected\n\n # same for a multi-index\n assert df.set_index(["a", "b"]).to_csv(float_format="%.2f") == expected\n\n def test_to_csv_na_rep(self):\n # see gh-11553\n #\n # Testing if NaN values are correctly represented in the index.\n df = DataFrame({"a": [0, np.nan], "b": [0, 1], "c": [2, 3]})\n expected_rows = ["a,b,c", "0.0,0,2", "_,1,3"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n\n assert df.set_index("a").to_csv(na_rep="_") == expected\n assert df.set_index(["a", "b"]).to_csv(na_rep="_") == expected\n\n # now with an index containing only NaNs\n df = DataFrame({"a": np.nan, "b": [0, 1], "c": [2, 3]})\n expected_rows = ["a,b,c", "_,0,2", "_,1,3"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n\n assert df.set_index("a").to_csv(na_rep="_") == expected\n assert df.set_index(["a", "b"]).to_csv(na_rep="_") == expected\n\n # check if na_rep parameter does not break anything when no NaN\n df = DataFrame({"a": 0, "b": [0, 1], "c": [2, 3]})\n expected_rows = ["a,b,c", "0,0,2", "0,1,3"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n\n assert df.set_index("a").to_csv(na_rep="_") == expected\n assert df.set_index(["a", "b"]).to_csv(na_rep="_") == expected\n\n csv = pd.Series(["a", pd.NA, "c"]).to_csv(na_rep="ZZZZZ")\n expected = tm.convert_rows_list_to_csv_str([",0", "0,a", "1,ZZZZZ", "2,c"])\n assert expected == csv\n\n def test_to_csv_na_rep_nullable_string(self, nullable_string_dtype):\n # GH 29975\n # Make sure full na_rep shows up when a dtype is provided\n expected = tm.convert_rows_list_to_csv_str([",0", "0,a", "1,ZZZZZ", "2,c"])\n csv = pd.Series(["a", pd.NA, "c"], dtype=nullable_string_dtype).to_csv(\n na_rep="ZZZZZ"\n )\n assert expected == csv\n\n def test_to_csv_date_format(self):\n # GH 10209\n df_sec = DataFrame({"A": pd.date_range("20130101", periods=5, freq="s")})\n df_day = DataFrame({"A": pd.date_range("20130101", periods=5, freq="d")})\n\n expected_rows = [\n ",A",\n "0,2013-01-01 00:00:00",\n "1,2013-01-01 00:00:01",\n "2,2013-01-01 00:00:02",\n "3,2013-01-01 00:00:03",\n "4,2013-01-01 00:00:04",\n ]\n expected_default_sec = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df_sec.to_csv() == expected_default_sec\n\n expected_rows = [\n ",A",\n "0,2013-01-01 00:00:00",\n "1,2013-01-02 00:00:00",\n "2,2013-01-03 00:00:00",\n "3,2013-01-04 00:00:00",\n "4,2013-01-05 00:00:00",\n ]\n expected_ymdhms_day = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df_day.to_csv(date_format="%Y-%m-%d %H:%M:%S") == expected_ymdhms_day\n\n expected_rows = [\n ",A",\n "0,2013-01-01",\n "1,2013-01-01",\n "2,2013-01-01",\n "3,2013-01-01",\n "4,2013-01-01",\n ]\n expected_ymd_sec = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df_sec.to_csv(date_format="%Y-%m-%d") == expected_ymd_sec\n\n expected_rows = [\n ",A",\n "0,2013-01-01",\n "1,2013-01-02",\n "2,2013-01-03",\n "3,2013-01-04",\n "4,2013-01-05",\n ]\n expected_default_day = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df_day.to_csv() == expected_default_day\n assert df_day.to_csv(date_format="%Y-%m-%d") == expected_default_day\n\n # see gh-7791\n #\n # Testing if date_format parameter is taken into account\n # for multi-indexed DataFrames.\n df_sec["B"] = 0\n df_sec["C"] = 1\n\n expected_rows = ["A,B,C", "2013-01-01,0,1.0"]\n expected_ymd_sec = tm.convert_rows_list_to_csv_str(expected_rows)\n\n df_sec_grouped = df_sec.groupby([pd.Grouper(key="A", freq="1h"), "B"])\n assert df_sec_grouped.mean().to_csv(date_format="%Y-%m-%d") == expected_ymd_sec\n\n def test_to_csv_different_datetime_formats(self):\n # GH#21734\n df = DataFrame(\n {\n "date": pd.to_datetime("1970-01-01"),\n "datetime": pd.date_range("1970-01-01", periods=2, freq="h"),\n }\n )\n expected_rows = [\n "date,datetime",\n "1970-01-01,1970-01-01 00:00:00",\n "1970-01-01,1970-01-01 01:00:00",\n ]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert df.to_csv(index=False) == expected\n\n def test_to_csv_date_format_in_categorical(self):\n # GH#40754\n ser = pd.Series(pd.to_datetime(["2021-03-27", pd.NaT], format="%Y-%m-%d"))\n ser = ser.astype("category")\n expected = tm.convert_rows_list_to_csv_str(["0", "2021-03-27", '""'])\n assert ser.to_csv(index=False) == expected\n\n ser = pd.Series(\n pd.date_range(\n start="2021-03-27", freq="D", periods=1, tz="Europe/Berlin"\n ).append(pd.DatetimeIndex([pd.NaT]))\n )\n ser = ser.astype("category")\n assert ser.to_csv(index=False, date_format="%Y-%m-%d") == expected\n\n def test_to_csv_float_ea_float_format(self):\n # GH#45991\n df = DataFrame({"a": [1.1, 2.02, pd.NA, 6.000006], "b": "c"})\n df["a"] = df["a"].astype("Float64")\n result = df.to_csv(index=False, float_format="%.5f")\n expected = tm.convert_rows_list_to_csv_str(\n ["a,b", "1.10000,c", "2.02000,c", ",c", "6.00001,c"]\n )\n assert result == expected\n\n def test_to_csv_float_ea_no_float_format(self):\n # GH#45991\n df = DataFrame({"a": [1.1, 2.02, pd.NA, 6.000006], "b": "c"})\n df["a"] = df["a"].astype("Float64")\n result = df.to_csv(index=False)\n expected = tm.convert_rows_list_to_csv_str(\n ["a,b", "1.1,c", "2.02,c", ",c", "6.000006,c"]\n )\n assert result == expected\n\n def test_to_csv_multi_index(self):\n # see gh-6618\n df = DataFrame([1], columns=pd.MultiIndex.from_arrays([[1], [2]]))\n\n exp_rows = [",1", ",2", "0,1"]\n exp = tm.convert_rows_list_to_csv_str(exp_rows)\n assert df.to_csv() == exp\n\n exp_rows = ["1", "2", "1"]\n exp = tm.convert_rows_list_to_csv_str(exp_rows)\n assert df.to_csv(index=False) == exp\n\n df = DataFrame(\n [1],\n columns=pd.MultiIndex.from_arrays([[1], [2]]),\n index=pd.MultiIndex.from_arrays([[1], [2]]),\n )\n\n exp_rows = [",,1", ",,2", "1,2,1"]\n exp = tm.convert_rows_list_to_csv_str(exp_rows)\n assert df.to_csv() == exp\n\n exp_rows = ["1", "2", "1"]\n exp = tm.convert_rows_list_to_csv_str(exp_rows)\n assert df.to_csv(index=False) == exp\n\n df = DataFrame([1], columns=pd.MultiIndex.from_arrays([["foo"], ["bar"]]))\n\n exp_rows = [",foo", ",bar", "0,1"]\n exp = tm.convert_rows_list_to_csv_str(exp_rows)\n assert df.to_csv() == exp\n\n exp_rows = ["foo", "bar", "1"]\n exp = tm.convert_rows_list_to_csv_str(exp_rows)\n assert df.to_csv(index=False) == exp\n\n @pytest.mark.parametrize(\n "ind,expected",\n [\n (\n pd.MultiIndex(levels=[[1.0]], codes=[[0]], names=["x"]),\n "x,data\n1.0,1\n",\n ),\n (\n pd.MultiIndex(\n levels=[[1.0], [2.0]], codes=[[0], [0]], names=["x", "y"]\n ),\n "x,y,data\n1.0,2.0,1\n",\n ),\n ],\n )\n def test_to_csv_single_level_multi_index(self, ind, expected, frame_or_series):\n # see gh-19589\n obj = frame_or_series(pd.Series([1], ind, name="data"))\n\n result = obj.to_csv(lineterminator="\n", header=True)\n assert result == expected\n\n def test_to_csv_string_array_ascii(self):\n # GH 10813\n str_array = [{"names": ["foo", "bar"]}, {"names": ["baz", "qux"]}]\n df = DataFrame(str_array)\n expected_ascii = """\\n,names\n0,"['foo', 'bar']"\n1,"['baz', 'qux']"\n"""\n with tm.ensure_clean("str_test.csv") as path:\n df.to_csv(path, encoding="ascii")\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected_ascii\n\n def test_to_csv_string_array_utf8(self):\n # GH 10813\n str_array = [{"names": ["foo", "bar"]}, {"names": ["baz", "qux"]}]\n df = DataFrame(str_array)\n expected_utf8 = """\\n,names\n0,"['foo', 'bar']"\n1,"['baz', 'qux']"\n"""\n with tm.ensure_clean("unicode_test.csv") as path:\n df.to_csv(path, encoding="utf-8")\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected_utf8\n\n def test_to_csv_string_with_lf(self):\n # GH 20353\n data = {"int": [1, 2, 3], "str_lf": ["abc", "d\nef", "g\nh\n\ni"]}\n df = DataFrame(data)\n with tm.ensure_clean("lf_test.csv") as path:\n # case 1: The default line terminator(=os.linesep)(PR 21406)\n os_linesep = os.linesep.encode("utf-8")\n expected_noarg = (\n b"int,str_lf"\n + os_linesep\n + b"1,abc"\n + os_linesep\n + b'2,"d\nef"'\n + os_linesep\n + b'3,"g\nh\n\ni"'\n + os_linesep\n )\n df.to_csv(path, index=False)\n with open(path, "rb") as f:\n assert f.read() == expected_noarg\n with tm.ensure_clean("lf_test.csv") as path:\n # case 2: LF as line terminator\n expected_lf = b'int,str_lf\n1,abc\n2,"d\nef"\n3,"g\nh\n\ni"\n'\n df.to_csv(path, lineterminator="\n", index=False)\n with open(path, "rb") as f:\n assert f.read() == expected_lf\n with tm.ensure_clean("lf_test.csv") as path:\n # case 3: CRLF as line terminator\n # 'lineterminator' should not change inner element\n expected_crlf = b'int,str_lf\r\n1,abc\r\n2,"d\nef"\r\n3,"g\nh\n\ni"\r\n'\n df.to_csv(path, lineterminator="\r\n", index=False)\n with open(path, "rb") as f:\n assert f.read() == expected_crlf\n\n def test_to_csv_string_with_crlf(self):\n # GH 20353\n data = {"int": [1, 2, 3], "str_crlf": ["abc", "d\r\nef", "g\r\nh\r\n\r\ni"]}\n df = DataFrame(data)\n with tm.ensure_clean("crlf_test.csv") as path:\n # case 1: The default line terminator(=os.linesep)(PR 21406)\n os_linesep = os.linesep.encode("utf-8")\n expected_noarg = (\n b"int,str_crlf"\n + os_linesep\n + b"1,abc"\n + os_linesep\n + b'2,"d\r\nef"'\n + os_linesep\n + b'3,"g\r\nh\r\n\r\ni"'\n + os_linesep\n )\n df.to_csv(path, index=False)\n with open(path, "rb") as f:\n assert f.read() == expected_noarg\n with tm.ensure_clean("crlf_test.csv") as path:\n # case 2: LF as line terminator\n expected_lf = b'int,str_crlf\n1,abc\n2,"d\r\nef"\n3,"g\r\nh\r\n\r\ni"\n'\n df.to_csv(path, lineterminator="\n", index=False)\n with open(path, "rb") as f:\n assert f.read() == expected_lf\n with tm.ensure_clean("crlf_test.csv") as path:\n # case 3: CRLF as line terminator\n # 'lineterminator' should not change inner element\n expected_crlf = (\n b"int,str_crlf\r\n"\n b"1,abc\r\n"\n b'2,"d\r\nef"\r\n'\n b'3,"g\r\nh\r\n\r\ni"\r\n'\n )\n df.to_csv(path, lineterminator="\r\n", index=False)\n with open(path, "rb") as f:\n assert f.read() == expected_crlf\n\n def test_to_csv_stdout_file(self, capsys):\n # GH 21561\n df = DataFrame([["foo", "bar"], ["baz", "qux"]], columns=["name_1", "name_2"])\n expected_rows = [",name_1,name_2", "0,foo,bar", "1,baz,qux"]\n expected_ascii = tm.convert_rows_list_to_csv_str(expected_rows)\n\n df.to_csv(sys.stdout, encoding="ascii")\n captured = capsys.readouterr()\n\n assert captured.out == expected_ascii\n assert not sys.stdout.closed\n\n @pytest.mark.xfail(\n compat.is_platform_windows(),\n reason=(\n "Especially in Windows, file stream should not be passed"\n "to csv writer without newline='' option."\n "(https://docs.python.org/3/library/csv.html#csv.writer)"\n ),\n )\n def test_to_csv_write_to_open_file(self):\n # GH 21696\n df = DataFrame({"a": ["x", "y", "z"]})\n expected = """\\nmanual header\nx\ny\nz\n"""\n with tm.ensure_clean("test.txt") as path:\n with open(path, "w", encoding="utf-8") as f:\n f.write("manual header\n")\n df.to_csv(f, header=None, index=None)\n with open(path, encoding="utf-8") as f:\n assert f.read() == expected\n\n def test_to_csv_write_to_open_file_with_newline_py3(self):\n # see gh-21696\n # see gh-20353\n df = DataFrame({"a": ["x", "y", "z"]})\n expected_rows = ["x", "y", "z"]\n expected = "manual header\n" + tm.convert_rows_list_to_csv_str(expected_rows)\n with tm.ensure_clean("test.txt") as path:\n with open(path, "w", newline="", encoding="utf-8") as f:\n f.write("manual header\n")\n df.to_csv(f, header=None, index=None)\n\n with open(path, "rb") as f:\n assert f.read() == bytes(expected, "utf-8")\n\n @pytest.mark.parametrize("to_infer", [True, False])\n @pytest.mark.parametrize("read_infer", [True, False])\n def test_to_csv_compression(\n self, compression_only, read_infer, to_infer, compression_to_extension\n ):\n # see gh-15008\n compression = compression_only\n\n # We'll complete file extension subsequently.\n filename = "test."\n filename += compression_to_extension[compression]\n\n df = DataFrame({"A": [1]})\n\n to_compression = "infer" if to_infer else compression\n read_compression = "infer" if read_infer else compression\n\n with tm.ensure_clean(filename) as path:\n df.to_csv(path, compression=to_compression)\n result = pd.read_csv(path, index_col=0, compression=read_compression)\n tm.assert_frame_equal(result, df)\n\n def test_to_csv_compression_dict(self, compression_only):\n # GH 26023\n method = compression_only\n df = DataFrame({"ABC": [1]})\n filename = "to_csv_compress_as_dict."\n extension = {\n "gzip": "gz",\n "zstd": "zst",\n }.get(method, method)\n filename += extension\n with tm.ensure_clean(filename) as path:\n df.to_csv(path, compression={"method": method})\n read_df = pd.read_csv(path, index_col=0)\n tm.assert_frame_equal(read_df, df)\n\n def test_to_csv_compression_dict_no_method_raises(self):\n # GH 26023\n df = DataFrame({"ABC": [1]})\n compression = {"some_option": True}\n msg = "must have key 'method'"\n\n with tm.ensure_clean("out.zip") as path:\n with pytest.raises(ValueError, match=msg):\n df.to_csv(path, compression=compression)\n\n @pytest.mark.parametrize("compression", ["zip", "infer"])\n @pytest.mark.parametrize("archive_name", ["test_to_csv.csv", "test_to_csv.zip"])\n def test_to_csv_zip_arguments(self, compression, archive_name):\n # GH 26023\n df = DataFrame({"ABC": [1]})\n with tm.ensure_clean("to_csv_archive_name.zip") as path:\n df.to_csv(\n path, compression={"method": compression, "archive_name": archive_name}\n )\n with ZipFile(path) as zp:\n assert len(zp.filelist) == 1\n archived_file = zp.filelist[0].filename\n assert archived_file == archive_name\n\n @pytest.mark.parametrize(\n "filename,expected_arcname",\n [\n ("archive.csv", "archive.csv"),\n ("archive.tsv", "archive.tsv"),\n ("archive.csv.zip", "archive.csv"),\n ("archive.tsv.zip", "archive.tsv"),\n ("archive.zip", "archive"),\n ],\n )\n def test_to_csv_zip_infer_name(self, tmp_path, filename, expected_arcname):\n # GH 39465\n df = DataFrame({"ABC": [1]})\n path = tmp_path / filename\n df.to_csv(path, compression="zip")\n with ZipFile(path) as zp:\n assert len(zp.filelist) == 1\n archived_file = zp.filelist[0].filename\n assert archived_file == expected_arcname\n\n @pytest.mark.parametrize("df_new_type", ["Int64"])\n def test_to_csv_na_rep_long_string(self, df_new_type):\n # see gh-25099\n df = DataFrame({"c": [float("nan")] * 3})\n df = df.astype(df_new_type)\n expected_rows = ["c", "mynull", "mynull", "mynull"]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n\n result = df.to_csv(index=False, na_rep="mynull", encoding="ascii")\n\n assert expected == result\n\n def test_to_csv_timedelta_precision(self):\n # GH 6783\n s = pd.Series([1, 1]).astype("timedelta64[ns]")\n buf = io.StringIO()\n s.to_csv(buf)\n result = buf.getvalue()\n expected_rows = [\n ",0",\n "0,0 days 00:00:00.000000001",\n "1,0 days 00:00:00.000000001",\n ]\n expected = tm.convert_rows_list_to_csv_str(expected_rows)\n assert result == expected\n\n def test_na_rep_truncated(self):\n # https://github.com/pandas-dev/pandas/issues/31447\n result = pd.Series(range(8, 12)).to_csv(na_rep="-")\n expected = tm.convert_rows_list_to_csv_str([",0", "0,8", "1,9", "2,10", "3,11"])\n assert result == expected\n\n result = pd.Series([True, False]).to_csv(na_rep="nan")\n expected = tm.convert_rows_list_to_csv_str([",0", "0,True", "1,False"])\n assert result == expected\n\n result = pd.Series([1.1, 2.2]).to_csv(na_rep=".")\n expected = tm.convert_rows_list_to_csv_str([",0", "0,1.1", "1,2.2"])\n assert result == expected\n\n @pytest.mark.parametrize("errors", ["surrogatepass", "ignore", "replace"])\n def test_to_csv_errors(self, errors):\n # GH 22610\n data = ["\ud800foo"]\n ser = pd.Series(data, index=Index(data, dtype=object), dtype=object)\n with tm.ensure_clean("test.csv") as path:\n ser.to_csv(path, errors=errors)\n # No use in reading back the data as it is not the same anymore\n # due to the error handling\n\n @pytest.mark.parametrize("mode", ["wb", "w"])\n def test_to_csv_binary_handle(self, mode):\n """\n Binary file objects should work (if 'mode' contains a 'b') or even without\n it in most cases.\n\n GH 35058 and GH 19827\n """\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD")),\n index=Index([f"i-{i}" for i in range(30)]),\n )\n with tm.ensure_clean() as path:\n with open(path, mode="w+b") as handle:\n df.to_csv(handle, mode=mode)\n tm.assert_frame_equal(df, pd.read_csv(path, index_col=0))\n\n @pytest.mark.parametrize("mode", ["wb", "w"])\n def test_to_csv_encoding_binary_handle(self, mode):\n """\n Binary file objects should honor a specified encoding.\n\n GH 23854 and GH 13068 with binary handles\n """\n # example from GH 23854\n content = "a, b, 🐟".encode("utf-8-sig")\n buffer = io.BytesIO(content)\n df = pd.read_csv(buffer, encoding="utf-8-sig")\n\n buffer = io.BytesIO()\n df.to_csv(buffer, mode=mode, encoding="utf-8-sig", index=False)\n buffer.seek(0) # tests whether file handle wasn't closed\n assert buffer.getvalue().startswith(content)\n\n # example from GH 13068\n with tm.ensure_clean() as path:\n with open(path, "w+b") as handle:\n DataFrame().to_csv(handle, mode=mode, encoding="utf-8-sig")\n\n handle.seek(0)\n assert handle.read().startswith(b'\xef\xbb\xbf""')\n\n\ndef test_to_csv_iterative_compression_name(compression):\n # GH 38714\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD")),\n index=Index([f"i-{i}" for i in range(30)]),\n )\n with tm.ensure_clean() as path:\n df.to_csv(path, compression=compression, chunksize=1)\n tm.assert_frame_equal(\n pd.read_csv(path, compression=compression, index_col=0), df\n )\n\n\ndef test_to_csv_iterative_compression_buffer(compression):\n # GH 38714\n df = DataFrame(\n 1.1 * np.arange(120).reshape((30, 4)),\n columns=Index(list("ABCD")),\n index=Index([f"i-{i}" for i in range(30)]),\n )\n with io.BytesIO() as buffer:\n df.to_csv(buffer, compression=compression, chunksize=1)\n buffer.seek(0)\n tm.assert_frame_equal(\n pd.read_csv(buffer, compression=compression, index_col=0), df\n )\n assert not buffer.closed\n\n\ndef test_to_csv_pos_args_deprecation():\n # GH-54229\n df = DataFrame({"a": [1, 2, 3]})\n msg = (\n r"Starting with pandas version 3.0 all arguments of to_csv except for the "\n r"argument 'path_or_buf' will be keyword-only."\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n buffer = io.BytesIO()\n df.to_csv(buffer, ";")\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_to_csv.py
test_to_csv.py
Python
27,541
0.95
0.075198
0.102603
python-kit
115
2023-10-23T02:15:41.993028
BSD-3-Clause
true
efe84daea2a004935264e17388fb9da2
"""Tests formatting as writer-agnostic ExcelCells\n\nExcelFormatter is tested implicitly in pandas/tests/io/excel\n"""\nimport string\n\nimport pytest\n\nfrom pandas.errors import CSSWarning\n\nimport pandas._testing as tm\n\nfrom pandas.io.formats.excel import (\n CssExcelCell,\n CSSToExcelConverter,\n)\n\n\n@pytest.mark.parametrize(\n "css,expected",\n [\n # FONT\n # - name\n ("font-family: foo,bar", {"font": {"name": "foo"}}),\n ('font-family: "foo bar",baz', {"font": {"name": "foo bar"}}),\n ("font-family: foo,\nbar", {"font": {"name": "foo"}}),\n ("font-family: foo, bar, baz", {"font": {"name": "foo"}}),\n ("font-family: bar, foo", {"font": {"name": "bar"}}),\n ("font-family: 'foo bar', baz", {"font": {"name": "foo bar"}}),\n ("font-family: 'foo \\'bar', baz", {"font": {"name": "foo 'bar"}}),\n ('font-family: "foo \\"bar", baz', {"font": {"name": 'foo "bar'}}),\n ('font-family: "foo ,bar", baz', {"font": {"name": "foo ,bar"}}),\n # - family\n ("font-family: serif", {"font": {"name": "serif", "family": 1}}),\n ("font-family: Serif", {"font": {"name": "serif", "family": 1}}),\n ("font-family: roman, serif", {"font": {"name": "roman", "family": 1}}),\n ("font-family: roman, sans-serif", {"font": {"name": "roman", "family": 2}}),\n ("font-family: roman, sans serif", {"font": {"name": "roman"}}),\n ("font-family: roman, sansserif", {"font": {"name": "roman"}}),\n ("font-family: roman, cursive", {"font": {"name": "roman", "family": 4}}),\n ("font-family: roman, fantasy", {"font": {"name": "roman", "family": 5}}),\n # - size\n ("font-size: 1em", {"font": {"size": 12}}),\n ("font-size: xx-small", {"font": {"size": 6}}),\n ("font-size: x-small", {"font": {"size": 7.5}}),\n ("font-size: small", {"font": {"size": 9.6}}),\n ("font-size: medium", {"font": {"size": 12}}),\n ("font-size: large", {"font": {"size": 13.5}}),\n ("font-size: x-large", {"font": {"size": 18}}),\n ("font-size: xx-large", {"font": {"size": 24}}),\n ("font-size: 50%", {"font": {"size": 6}}),\n # - bold\n ("font-weight: 100", {"font": {"bold": False}}),\n ("font-weight: 200", {"font": {"bold": False}}),\n ("font-weight: 300", {"font": {"bold": False}}),\n ("font-weight: 400", {"font": {"bold": False}}),\n ("font-weight: normal", {"font": {"bold": False}}),\n ("font-weight: lighter", {"font": {"bold": False}}),\n ("font-weight: bold", {"font": {"bold": True}}),\n ("font-weight: bolder", {"font": {"bold": True}}),\n ("font-weight: 700", {"font": {"bold": True}}),\n ("font-weight: 800", {"font": {"bold": True}}),\n ("font-weight: 900", {"font": {"bold": True}}),\n # - italic\n ("font-style: italic", {"font": {"italic": True}}),\n ("font-style: oblique", {"font": {"italic": True}}),\n # - underline\n ("text-decoration: underline", {"font": {"underline": "single"}}),\n ("text-decoration: overline", {}),\n ("text-decoration: none", {}),\n # - strike\n ("text-decoration: line-through", {"font": {"strike": True}}),\n (\n "text-decoration: underline line-through",\n {"font": {"strike": True, "underline": "single"}},\n ),\n (\n "text-decoration: underline; text-decoration: line-through",\n {"font": {"strike": True}},\n ),\n # - color\n ("color: red", {"font": {"color": "FF0000"}}),\n ("color: #ff0000", {"font": {"color": "FF0000"}}),\n ("color: #f0a", {"font": {"color": "FF00AA"}}),\n # - shadow\n ("text-shadow: none", {"font": {"shadow": False}}),\n ("text-shadow: 0px -0em 0px #CCC", {"font": {"shadow": False}}),\n ("text-shadow: 0px -0em 0px #999", {"font": {"shadow": False}}),\n ("text-shadow: 0px -0em 0px", {"font": {"shadow": False}}),\n ("text-shadow: 2px -0em 0px #CCC", {"font": {"shadow": True}}),\n ("text-shadow: 0px -2em 0px #CCC", {"font": {"shadow": True}}),\n ("text-shadow: 0px -0em 2px #CCC", {"font": {"shadow": True}}),\n ("text-shadow: 0px -0em 2px", {"font": {"shadow": True}}),\n ("text-shadow: 0px -2em", {"font": {"shadow": True}}),\n # FILL\n # - color, fillType\n (\n "background-color: red",\n {"fill": {"fgColor": "FF0000", "patternType": "solid"}},\n ),\n (\n "background-color: #ff0000",\n {"fill": {"fgColor": "FF0000", "patternType": "solid"}},\n ),\n (\n "background-color: #f0a",\n {"fill": {"fgColor": "FF00AA", "patternType": "solid"}},\n ),\n # BORDER\n # - style\n (\n "border-style: solid",\n {\n "border": {\n "top": {"style": "medium"},\n "bottom": {"style": "medium"},\n "left": {"style": "medium"},\n "right": {"style": "medium"},\n }\n },\n ),\n (\n "border-style: solid; border-width: thin",\n {\n "border": {\n "top": {"style": "thin"},\n "bottom": {"style": "thin"},\n "left": {"style": "thin"},\n "right": {"style": "thin"},\n }\n },\n ),\n (\n "border-top-style: solid; border-top-width: thin",\n {"border": {"top": {"style": "thin"}}},\n ),\n (\n "border-top-style: solid; border-top-width: 1pt",\n {"border": {"top": {"style": "thin"}}},\n ),\n ("border-top-style: solid", {"border": {"top": {"style": "medium"}}}),\n (\n "border-top-style: solid; border-top-width: medium",\n {"border": {"top": {"style": "medium"}}},\n ),\n (\n "border-top-style: solid; border-top-width: 2pt",\n {"border": {"top": {"style": "medium"}}},\n ),\n (\n "border-top-style: solid; border-top-width: thick",\n {"border": {"top": {"style": "thick"}}},\n ),\n (\n "border-top-style: solid; border-top-width: 4pt",\n {"border": {"top": {"style": "thick"}}},\n ),\n (\n "border-top-style: dotted",\n {"border": {"top": {"style": "mediumDashDotDot"}}},\n ),\n (\n "border-top-style: dotted; border-top-width: thin",\n {"border": {"top": {"style": "dotted"}}},\n ),\n ("border-top-style: dashed", {"border": {"top": {"style": "mediumDashed"}}}),\n (\n "border-top-style: dashed; border-top-width: thin",\n {"border": {"top": {"style": "dashed"}}},\n ),\n ("border-top-style: double", {"border": {"top": {"style": "double"}}}),\n # - color\n (\n "border-style: solid; border-color: #0000ff",\n {\n "border": {\n "top": {"style": "medium", "color": "0000FF"},\n "right": {"style": "medium", "color": "0000FF"},\n "bottom": {"style": "medium", "color": "0000FF"},\n "left": {"style": "medium", "color": "0000FF"},\n }\n },\n ),\n (\n "border-top-style: double; border-top-color: blue",\n {"border": {"top": {"style": "double", "color": "0000FF"}}},\n ),\n (\n "border-top-style: solid; border-top-color: #06c",\n {"border": {"top": {"style": "medium", "color": "0066CC"}}},\n ),\n (\n "border-top-color: blue",\n {"border": {"top": {"color": "0000FF", "style": "none"}}},\n ),\n # ALIGNMENT\n # - horizontal\n ("text-align: center", {"alignment": {"horizontal": "center"}}),\n ("text-align: left", {"alignment": {"horizontal": "left"}}),\n ("text-align: right", {"alignment": {"horizontal": "right"}}),\n ("text-align: justify", {"alignment": {"horizontal": "justify"}}),\n # - vertical\n ("vertical-align: top", {"alignment": {"vertical": "top"}}),\n ("vertical-align: text-top", {"alignment": {"vertical": "top"}}),\n ("vertical-align: middle", {"alignment": {"vertical": "center"}}),\n ("vertical-align: bottom", {"alignment": {"vertical": "bottom"}}),\n ("vertical-align: text-bottom", {"alignment": {"vertical": "bottom"}}),\n # - wrap_text\n ("white-space: nowrap", {"alignment": {"wrap_text": False}}),\n ("white-space: pre", {"alignment": {"wrap_text": False}}),\n ("white-space: pre-line", {"alignment": {"wrap_text": False}}),\n ("white-space: normal", {"alignment": {"wrap_text": True}}),\n # NUMBER FORMAT\n ("number-format: 0%", {"number_format": {"format_code": "0%"}}),\n (\n "number-format: 0§[Red](0)§-§@;",\n {"number_format": {"format_code": "0;[red](0);-;@"}}, # GH 46152\n ),\n ],\n)\ndef test_css_to_excel(css, expected):\n convert = CSSToExcelConverter()\n assert expected == convert(css)\n\n\ndef test_css_to_excel_multiple():\n convert = CSSToExcelConverter()\n actual = convert(\n """\n font-weight: bold;\n text-decoration: underline;\n color: red;\n border-width: thin;\n text-align: center;\n vertical-align: top;\n unused: something;\n """\n )\n assert {\n "font": {"bold": True, "underline": "single", "color": "FF0000"},\n "border": {\n "top": {"style": "thin"},\n "right": {"style": "thin"},\n "bottom": {"style": "thin"},\n "left": {"style": "thin"},\n },\n "alignment": {"horizontal": "center", "vertical": "top"},\n } == actual\n\n\n@pytest.mark.parametrize(\n "css,inherited,expected",\n [\n ("font-weight: bold", "", {"font": {"bold": True}}),\n ("", "font-weight: bold", {"font": {"bold": True}}),\n (\n "font-weight: bold",\n "font-style: italic",\n {"font": {"bold": True, "italic": True}},\n ),\n ("font-style: normal", "font-style: italic", {"font": {"italic": False}}),\n ("font-style: inherit", "", {}),\n (\n "font-style: normal; font-style: inherit",\n "font-style: italic",\n {"font": {"italic": True}},\n ),\n ],\n)\ndef test_css_to_excel_inherited(css, inherited, expected):\n convert = CSSToExcelConverter(inherited)\n assert expected == convert(css)\n\n\n@pytest.mark.parametrize(\n "input_color,output_color",\n (\n list(CSSToExcelConverter.NAMED_COLORS.items())\n + [("#" + rgb, rgb) for rgb in CSSToExcelConverter.NAMED_COLORS.values()]\n + [("#F0F", "FF00FF"), ("#ABC", "AABBCC")]\n ),\n)\ndef test_css_to_excel_good_colors(input_color, output_color):\n # see gh-18392\n css = (\n f"border-top-color: {input_color}; "\n f"border-right-color: {input_color}; "\n f"border-bottom-color: {input_color}; "\n f"border-left-color: {input_color}; "\n f"background-color: {input_color}; "\n f"color: {input_color}"\n )\n\n expected = {}\n\n expected["fill"] = {"patternType": "solid", "fgColor": output_color}\n\n expected["font"] = {"color": output_color}\n\n expected["border"] = {\n k: {"color": output_color, "style": "none"}\n for k in ("top", "right", "bottom", "left")\n }\n\n with tm.assert_produces_warning(None):\n convert = CSSToExcelConverter()\n assert expected == convert(css)\n\n\n@pytest.mark.parametrize("input_color", [None, "not-a-color"])\ndef test_css_to_excel_bad_colors(input_color):\n # see gh-18392\n css = (\n f"border-top-color: {input_color}; "\n f"border-right-color: {input_color}; "\n f"border-bottom-color: {input_color}; "\n f"border-left-color: {input_color}; "\n f"background-color: {input_color}; "\n f"color: {input_color}"\n )\n\n expected = {}\n\n if input_color is not None:\n expected["fill"] = {"patternType": "solid"}\n\n with tm.assert_produces_warning(CSSWarning):\n convert = CSSToExcelConverter()\n assert expected == convert(css)\n\n\ndef tests_css_named_colors_valid():\n upper_hexs = set(map(str.upper, string.hexdigits))\n for color in CSSToExcelConverter.NAMED_COLORS.values():\n assert len(color) == 6 and all(c in upper_hexs for c in color)\n\n\ndef test_css_named_colors_from_mpl_present():\n mpl_colors = pytest.importorskip("matplotlib.colors")\n\n pd_colors = CSSToExcelConverter.NAMED_COLORS\n for name, color in mpl_colors.CSS4_COLORS.items():\n assert name in pd_colors and pd_colors[name] == color[1:]\n\n\n@pytest.mark.parametrize(\n "styles,expected",\n [\n ([("color", "green"), ("color", "red")], "color: red;"),\n ([("font-weight", "bold"), ("font-weight", "normal")], "font-weight: normal;"),\n ([("text-align", "center"), ("TEXT-ALIGN", "right")], "text-align: right;"),\n ],\n)\ndef test_css_excel_cell_precedence(styles, expected):\n """It applies favors latter declarations over former declarations"""\n # See GH 47371\n converter = CSSToExcelConverter()\n converter._call_cached.cache_clear()\n css_styles = {(0, 0): styles}\n cell = CssExcelCell(\n row=0,\n col=0,\n val="",\n style=None,\n css_styles=css_styles,\n css_row=0,\n css_col=0,\n css_converter=converter,\n )\n converter._call_cached.cache_clear()\n\n assert cell.style == converter(expected)\n\n\n@pytest.mark.parametrize(\n "styles,cache_hits,cache_misses",\n [\n ([[("color", "green"), ("color", "red"), ("color", "green")]], 0, 1),\n (\n [\n [("font-weight", "bold")],\n [("font-weight", "normal"), ("font-weight", "bold")],\n ],\n 1,\n 1,\n ),\n ([[("text-align", "center")], [("TEXT-ALIGN", "center")]], 1, 1),\n (\n [\n [("font-weight", "bold"), ("text-align", "center")],\n [("font-weight", "bold"), ("text-align", "left")],\n ],\n 0,\n 2,\n ),\n (\n [\n [("font-weight", "bold"), ("text-align", "center")],\n [("font-weight", "bold"), ("text-align", "left")],\n [("font-weight", "bold"), ("text-align", "center")],\n ],\n 1,\n 2,\n ),\n ],\n)\ndef test_css_excel_cell_cache(styles, cache_hits, cache_misses):\n """It caches unique cell styles"""\n # See GH 47371\n converter = CSSToExcelConverter()\n converter._call_cached.cache_clear()\n\n css_styles = {(0, i): _style for i, _style in enumerate(styles)}\n for css_row, css_col in css_styles:\n CssExcelCell(\n row=0,\n col=0,\n val="",\n style=None,\n css_styles=css_styles,\n css_row=css_row,\n css_col=css_col,\n css_converter=converter,\n )\n cache_info = converter._call_cached.cache_info()\n converter._call_cached.cache_clear()\n\n assert cache_info.hits == cache_hits\n assert cache_info.misses == cache_misses\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_to_excel.py
test_to_excel.py
Python
15,320
0.95
0.039627
0.060914
node-utils
798
2024-06-13T10:51:43.934263
GPL-3.0
true
0b247481799c9b5478bd6e07551d64ca
from datetime import datetime\nfrom io import StringIO\nimport itertools\nimport re\nimport textwrap\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n get_option,\n option_context,\n)\nimport pandas._testing as tm\n\nimport pandas.io.formats.format as fmt\n\nlorem_ipsum = (\n "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "\n "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim "\n "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex "\n "ea commodo consequat. Duis aute irure dolor in reprehenderit in "\n "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur "\n "sint occaecat cupidatat non proident, sunt in culpa qui officia "\n "deserunt mollit anim id est laborum."\n)\n\n\ndef expected_html(datapath, name):\n """\n Read HTML file from formats data directory.\n\n Parameters\n ----------\n datapath : pytest fixture\n The datapath fixture injected into a test by pytest.\n name : str\n The name of the HTML file without the suffix.\n\n Returns\n -------\n str : contents of HTML file.\n """\n filename = ".".join([name, "html"])\n filepath = datapath("io", "formats", "data", "html", filename)\n with open(filepath, encoding="utf-8") as f:\n html = f.read()\n return html.rstrip()\n\n\n@pytest.fixture(params=["mixed", "empty"])\ndef biggie_df_fixture(request):\n """Fixture for a big mixed Dataframe and an empty Dataframe"""\n if request.param == "mixed":\n df = DataFrame(\n {\n "A": np.random.default_rng(2).standard_normal(200),\n "B": Index([f"{i}?!" for i in range(200)]),\n },\n index=np.arange(200),\n )\n df.loc[:20, "A"] = np.nan\n df.loc[:20, "B"] = np.nan\n return df\n elif request.param == "empty":\n df = DataFrame(index=np.arange(200))\n return df\n\n\n@pytest.fixture(params=fmt.VALID_JUSTIFY_PARAMETERS)\ndef justify(request):\n return request.param\n\n\n@pytest.mark.parametrize("col_space", [30, 50])\ndef test_to_html_with_col_space(col_space):\n df = DataFrame(np.random.default_rng(2).random(size=(1, 3)))\n # check that col_space affects HTML generation\n # and be very brittle about it.\n result = df.to_html(col_space=col_space)\n hdrs = [x for x in result.split(r"\n") if re.search(r"<th[>\s]", x)]\n assert len(hdrs) > 0\n for h in hdrs:\n assert "min-width" in h\n assert str(col_space) in h\n\n\ndef test_to_html_with_column_specific_col_space_raises():\n df = DataFrame(\n np.random.default_rng(2).random(size=(3, 3)), columns=["a", "b", "c"]\n )\n\n msg = (\n "Col_space length\\(\\d+\\) should match "\n "DataFrame number of columns\\(\\d+\\)"\n )\n with pytest.raises(ValueError, match=msg):\n df.to_html(col_space=[30, 40])\n\n with pytest.raises(ValueError, match=msg):\n df.to_html(col_space=[30, 40, 50, 60])\n\n msg = "unknown column"\n with pytest.raises(ValueError, match=msg):\n df.to_html(col_space={"a": "foo", "b": 23, "d": 34})\n\n\ndef test_to_html_with_column_specific_col_space():\n df = DataFrame(\n np.random.default_rng(2).random(size=(3, 3)), columns=["a", "b", "c"]\n )\n\n result = df.to_html(col_space={"a": "2em", "b": 23})\n hdrs = [x for x in result.split("\n") if re.search(r"<th[>\s]", x)]\n assert 'min-width: 2em;">a</th>' in hdrs[1]\n assert 'min-width: 23px;">b</th>' in hdrs[2]\n assert "<th>c</th>" in hdrs[3]\n\n result = df.to_html(col_space=["1em", 2, 3])\n hdrs = [x for x in result.split("\n") if re.search(r"<th[>\s]", x)]\n assert 'min-width: 1em;">a</th>' in hdrs[1]\n assert 'min-width: 2px;">b</th>' in hdrs[2]\n assert 'min-width: 3px;">c</th>' in hdrs[3]\n\n\ndef test_to_html_with_empty_string_label():\n # GH 3547, to_html regards empty string labels as repeated labels\n data = {"c1": ["a", "b"], "c2": ["a", ""], "data": [1, 2]}\n df = DataFrame(data).set_index(["c1", "c2"])\n result = df.to_html()\n assert "rowspan" not in result\n\n\n@pytest.mark.parametrize(\n "df,expected",\n [\n (DataFrame({"\u03c3": np.arange(10.0)}), "unicode_1"),\n (DataFrame({"A": ["\u03c3"]}), "unicode_2"),\n ],\n)\ndef test_to_html_unicode(df, expected, datapath):\n expected = expected_html(datapath, expected)\n result = df.to_html()\n assert result == expected\n\n\ndef test_to_html_encoding(float_frame, tmp_path):\n # GH 28663\n path = tmp_path / "test.html"\n float_frame.to_html(path, encoding="gbk")\n with open(str(path), encoding="gbk") as f:\n assert float_frame.to_html() == f.read()\n\n\ndef test_to_html_decimal(datapath):\n # GH 12031\n df = DataFrame({"A": [6.0, 3.1, 2.2]})\n result = df.to_html(decimal=",")\n expected = expected_html(datapath, "gh12031_expected_output")\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "kwargs,string,expected",\n [\n ({}, "<type 'str'>", "escaped"),\n ({"escape": False}, "<b>bold</b>", "escape_disabled"),\n ],\n)\ndef test_to_html_escaped(kwargs, string, expected, datapath):\n a = "str<ing1 &amp;"\n b = "stri>ng2 &amp;"\n\n test_dict = {"co<l1": {a: string, b: string}, "co>l2": {a: string, b: string}}\n result = DataFrame(test_dict).to_html(**kwargs)\n expected = expected_html(datapath, expected)\n assert result == expected\n\n\n@pytest.mark.parametrize("index_is_named", [True, False])\ndef test_to_html_multiindex_index_false(index_is_named, datapath):\n # GH 8452\n df = DataFrame(\n {"a": range(2), "b": range(3, 5), "c": range(5, 7), "d": range(3, 5)}\n )\n df.columns = MultiIndex.from_product([["a", "b"], ["c", "d"]])\n if index_is_named:\n df.index = Index(df.index.values, name="idx")\n result = df.to_html(index=False)\n expected = expected_html(datapath, "gh8452_expected_output")\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "multi_sparse,expected",\n [\n (False, "multiindex_sparsify_false_multi_sparse_1"),\n (False, "multiindex_sparsify_false_multi_sparse_2"),\n (True, "multiindex_sparsify_1"),\n (True, "multiindex_sparsify_2"),\n ],\n)\ndef test_to_html_multiindex_sparsify(multi_sparse, expected, datapath):\n index = MultiIndex.from_arrays([[0, 0, 1, 1], [0, 1, 0, 1]], names=["foo", None])\n df = DataFrame([[0, 1], [2, 3], [4, 5], [6, 7]], index=index)\n if expected.endswith("2"):\n df.columns = index[::2]\n with option_context("display.multi_sparse", multi_sparse):\n result = df.to_html()\n expected = expected_html(datapath, expected)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "max_rows,expected",\n [\n (60, "gh14882_expected_output_1"),\n # Test that ... appears in a middle level\n (56, "gh14882_expected_output_2"),\n ],\n)\ndef test_to_html_multiindex_odd_even_truncate(max_rows, expected, datapath):\n # GH 14882 - Issue on truncation with odd length DataFrame\n index = MultiIndex.from_product(\n [[100, 200, 300], [10, 20, 30], [1, 2, 3, 4, 5, 6, 7]], names=["a", "b", "c"]\n )\n df = DataFrame({"n": range(len(index))}, index=index)\n result = df.to_html(max_rows=max_rows)\n expected = expected_html(datapath, expected)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "df,formatters,expected",\n [\n (\n DataFrame(\n [[0, 1], [2, 3], [4, 5], [6, 7]],\n columns=Index(["foo", None], dtype=object),\n index=np.arange(4),\n ),\n {"__index__": lambda x: "abcd"[x]},\n "index_formatter",\n ),\n (\n DataFrame({"months": [datetime(2016, 1, 1), datetime(2016, 2, 2)]}),\n {"months": lambda x: x.strftime("%Y-%m")},\n "datetime64_monthformatter",\n ),\n (\n DataFrame(\n {\n "hod": pd.to_datetime(\n ["10:10:10.100", "12:12:12.120"], format="%H:%M:%S.%f"\n )\n }\n ),\n {"hod": lambda x: x.strftime("%H:%M")},\n "datetime64_hourformatter",\n ),\n (\n DataFrame(\n {\n "i": pd.Series([1, 2], dtype="int64"),\n "f": pd.Series([1, 2], dtype="float64"),\n "I": pd.Series([1, 2], dtype="Int64"),\n "s": pd.Series([1, 2], dtype="string"),\n "b": pd.Series([True, False], dtype="boolean"),\n "c": pd.Series(["a", "b"], dtype=pd.CategoricalDtype(["a", "b"])),\n "o": pd.Series([1, "2"], dtype=object),\n }\n ),\n [lambda x: "formatted"] * 7,\n "various_dtypes_formatted",\n ),\n ],\n)\ndef test_to_html_formatters(df, formatters, expected, datapath):\n expected = expected_html(datapath, expected)\n result = df.to_html(formatters=formatters)\n assert result == expected\n\n\ndef test_to_html_regression_GH6098():\n df = DataFrame(\n {\n "clé1": ["a", "a", "b", "b", "a"],\n "clé2": ["1er", "2ème", "1er", "2ème", "1er"],\n "données1": np.random.default_rng(2).standard_normal(5),\n "données2": np.random.default_rng(2).standard_normal(5),\n }\n )\n\n # it works\n df.pivot_table(index=["clé1"], columns=["clé2"])._repr_html_()\n\n\ndef test_to_html_truncate(datapath):\n index = pd.date_range(start="20010101", freq="D", periods=20)\n df = DataFrame(index=index, columns=range(20))\n result = df.to_html(max_rows=8, max_cols=4)\n expected = expected_html(datapath, "truncate")\n assert result == expected\n\n\n@pytest.mark.parametrize("size", [1, 5])\ndef test_html_invalid_formatters_arg_raises(size):\n # issue-28469\n df = DataFrame(columns=["a", "b", "c"])\n msg = "Formatters length({}) should match DataFrame number of columns(3)"\n with pytest.raises(ValueError, match=re.escape(msg.format(size))):\n df.to_html(formatters=["{}".format] * size)\n\n\ndef test_to_html_truncate_formatter(datapath):\n # issue-25955\n data = [\n {"A": 1, "B": 2, "C": 3, "D": 4},\n {"A": 5, "B": 6, "C": 7, "D": 8},\n {"A": 9, "B": 10, "C": 11, "D": 12},\n {"A": 13, "B": 14, "C": 15, "D": 16},\n ]\n\n df = DataFrame(data)\n fmt = lambda x: str(x) + "_mod"\n formatters = [fmt, fmt, None, None]\n result = df.to_html(formatters=formatters, max_cols=3)\n expected = expected_html(datapath, "truncate_formatter")\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "sparsify,expected",\n [(True, "truncate_multi_index"), (False, "truncate_multi_index_sparse_off")],\n)\ndef test_to_html_truncate_multi_index(sparsify, expected, datapath):\n arrays = [\n ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],\n ["one", "two", "one", "two", "one", "two", "one", "two"],\n ]\n df = DataFrame(index=arrays, columns=arrays)\n result = df.to_html(max_rows=7, max_cols=7, sparsify=sparsify)\n expected = expected_html(datapath, expected)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "option,result,expected",\n [\n (None, lambda df: df.to_html(), "1"),\n (None, lambda df: df.to_html(border=2), "2"),\n (2, lambda df: df.to_html(), "2"),\n (2, lambda df: df._repr_html_(), "2"),\n ],\n)\ndef test_to_html_border(option, result, expected):\n df = DataFrame({"A": [1, 2]})\n if option is None:\n result = result(df)\n else:\n with option_context("display.html.border", option):\n result = result(df)\n expected = f'border="{expected}"'\n assert expected in result\n\n\n@pytest.mark.parametrize("biggie_df_fixture", ["mixed"], indirect=True)\ndef test_to_html(biggie_df_fixture):\n # TODO: split this test\n df = biggie_df_fixture\n s = df.to_html()\n\n buf = StringIO()\n retval = df.to_html(buf=buf)\n assert retval is None\n assert buf.getvalue() == s\n\n assert isinstance(s, str)\n\n df.to_html(columns=["B", "A"], col_space=17)\n df.to_html(columns=["B", "A"], formatters={"A": lambda x: f"{x:.1f}"})\n\n df.to_html(columns=["B", "A"], float_format=str)\n df.to_html(columns=["B", "A"], col_space=12, float_format=str)\n\n\n@pytest.mark.parametrize("biggie_df_fixture", ["empty"], indirect=True)\ndef test_to_html_empty_dataframe(biggie_df_fixture):\n df = biggie_df_fixture\n df.to_html()\n\n\ndef test_to_html_filename(biggie_df_fixture, tmpdir):\n df = biggie_df_fixture\n expected = df.to_html()\n path = tmpdir.join("test.html")\n df.to_html(path)\n result = path.read()\n assert result == expected\n\n\ndef test_to_html_with_no_bold():\n df = DataFrame({"x": np.random.default_rng(2).standard_normal(5)})\n html = df.to_html(bold_rows=False)\n result = html[html.find("</thead>")]\n assert "<strong" not in result\n\n\ndef test_to_html_columns_arg(float_frame):\n result = float_frame.to_html(columns=["A"])\n assert "<th>B</th>" not in result\n\n\n@pytest.mark.parametrize(\n "columns,justify,expected",\n [\n (\n MultiIndex.from_arrays(\n [np.arange(2).repeat(2), np.mod(range(4), 2)],\n names=["CL0", "CL1"],\n ),\n "left",\n "multiindex_1",\n ),\n (\n MultiIndex.from_arrays([np.arange(4), np.mod(range(4), 2)]),\n "right",\n "multiindex_2",\n ),\n ],\n)\ndef test_to_html_multiindex(columns, justify, expected, datapath):\n df = DataFrame([list("abcd"), list("efgh")], columns=columns)\n result = df.to_html(justify=justify)\n expected = expected_html(datapath, expected)\n assert result == expected\n\n\ndef test_to_html_justify(justify, datapath):\n df = DataFrame(\n {"A": [6, 30000, 2], "B": [1, 2, 70000], "C": [223442, 0, 1]},\n columns=["A", "B", "C"],\n )\n result = df.to_html(justify=justify)\n expected = expected_html(datapath, "justify").format(justify=justify)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "justify", ["super-right", "small-left", "noinherit", "tiny", "pandas"]\n)\ndef test_to_html_invalid_justify(justify):\n # GH 17527\n df = DataFrame()\n msg = "Invalid value for justify parameter"\n\n with pytest.raises(ValueError, match=msg):\n df.to_html(justify=justify)\n\n\nclass TestHTMLIndex:\n @pytest.fixture\n def df(self):\n index = ["foo", "bar", "baz"]\n df = DataFrame(\n {"A": [1, 2, 3], "B": [1.2, 3.4, 5.6], "C": ["one", "two", np.nan]},\n columns=["A", "B", "C"],\n index=index,\n )\n return df\n\n @pytest.fixture\n def expected_without_index(self, datapath):\n return expected_html(datapath, "index_2")\n\n def test_to_html_flat_index_without_name(\n self, datapath, df, expected_without_index\n ):\n expected_with_index = expected_html(datapath, "index_1")\n assert df.to_html() == expected_with_index\n\n result = df.to_html(index=False)\n for i in df.index:\n assert i not in result\n assert result == expected_without_index\n\n def test_to_html_flat_index_with_name(self, datapath, df, expected_without_index):\n df.index = Index(["foo", "bar", "baz"], name="idx")\n expected_with_index = expected_html(datapath, "index_3")\n assert df.to_html() == expected_with_index\n assert df.to_html(index=False) == expected_without_index\n\n def test_to_html_multiindex_without_names(\n self, datapath, df, expected_without_index\n ):\n tuples = [("foo", "car"), ("foo", "bike"), ("bar", "car")]\n df.index = MultiIndex.from_tuples(tuples)\n\n expected_with_index = expected_html(datapath, "index_4")\n assert df.to_html() == expected_with_index\n\n result = df.to_html(index=False)\n for i in ["foo", "bar", "car", "bike"]:\n assert i not in result\n # must be the same result as normal index\n assert result == expected_without_index\n\n def test_to_html_multiindex_with_names(self, datapath, df, expected_without_index):\n tuples = [("foo", "car"), ("foo", "bike"), ("bar", "car")]\n df.index = MultiIndex.from_tuples(tuples, names=["idx1", "idx2"])\n expected_with_index = expected_html(datapath, "index_5")\n assert df.to_html() == expected_with_index\n assert df.to_html(index=False) == expected_without_index\n\n\n@pytest.mark.parametrize("classes", ["sortable draggable", ["sortable", "draggable"]])\ndef test_to_html_with_classes(classes, datapath):\n df = DataFrame()\n expected = expected_html(datapath, "with_classes")\n result = df.to_html(classes=classes)\n assert result == expected\n\n\ndef test_to_html_no_index_max_rows(datapath):\n # GH 14998\n df = DataFrame({"A": [1, 2, 3, 4]})\n result = df.to_html(index=False, max_rows=1)\n expected = expected_html(datapath, "gh14998_expected_output")\n assert result == expected\n\n\ndef test_to_html_multiindex_max_cols(datapath):\n # GH 6131\n index = MultiIndex(\n levels=[["ba", "bb", "bc"], ["ca", "cb", "cc"]],\n codes=[[0, 1, 2], [0, 1, 2]],\n names=["b", "c"],\n )\n columns = MultiIndex(\n levels=[["d"], ["aa", "ab", "ac"]],\n codes=[[0, 0, 0], [0, 1, 2]],\n names=[None, "a"],\n )\n data = np.array(\n [[1.0, np.nan, np.nan], [np.nan, 2.0, np.nan], [np.nan, np.nan, 3.0]]\n )\n df = DataFrame(data, index, columns)\n result = df.to_html(max_cols=2)\n expected = expected_html(datapath, "gh6131_expected_output")\n assert result == expected\n\n\ndef test_to_html_multi_indexes_index_false(datapath):\n # GH 22579\n df = DataFrame(\n {"a": range(10), "b": range(10, 20), "c": range(10, 20), "d": range(10, 20)}\n )\n df.columns = MultiIndex.from_product([["a", "b"], ["c", "d"]])\n df.index = MultiIndex.from_product([["a", "b"], ["c", "d", "e", "f", "g"]])\n result = df.to_html(index=False)\n expected = expected_html(datapath, "gh22579_expected_output")\n assert result == expected\n\n\n@pytest.mark.parametrize("index_names", [True, False])\n@pytest.mark.parametrize("header", [True, False])\n@pytest.mark.parametrize("index", [True, False])\n@pytest.mark.parametrize(\n "column_index, column_type",\n [\n (Index([0, 1]), "unnamed_standard"),\n (Index([0, 1], name="columns.name"), "named_standard"),\n (MultiIndex.from_product([["a"], ["b", "c"]]), "unnamed_multi"),\n (\n MultiIndex.from_product(\n [["a"], ["b", "c"]], names=["columns.name.0", "columns.name.1"]\n ),\n "named_multi",\n ),\n ],\n)\n@pytest.mark.parametrize(\n "row_index, row_type",\n [\n (Index([0, 1]), "unnamed_standard"),\n (Index([0, 1], name="index.name"), "named_standard"),\n (MultiIndex.from_product([["a"], ["b", "c"]]), "unnamed_multi"),\n (\n MultiIndex.from_product(\n [["a"], ["b", "c"]], names=["index.name.0", "index.name.1"]\n ),\n "named_multi",\n ),\n ],\n)\ndef test_to_html_basic_alignment(\n datapath, row_index, row_type, column_index, column_type, index, header, index_names\n):\n # GH 22747, GH 22579\n df = DataFrame(np.zeros((2, 2), dtype=int), index=row_index, columns=column_index)\n result = df.to_html(index=index, header=header, index_names=index_names)\n\n if not index:\n row_type = "none"\n elif not index_names and row_type.startswith("named"):\n row_type = "un" + row_type\n\n if not header:\n column_type = "none"\n elif not index_names and column_type.startswith("named"):\n column_type = "un" + column_type\n\n filename = "index_" + row_type + "_columns_" + column_type\n expected = expected_html(datapath, filename)\n assert result == expected\n\n\n@pytest.mark.parametrize("index_names", [True, False])\n@pytest.mark.parametrize("header", [True, False])\n@pytest.mark.parametrize("index", [True, False])\n@pytest.mark.parametrize(\n "column_index, column_type",\n [\n (Index(np.arange(8)), "unnamed_standard"),\n (Index(np.arange(8), name="columns.name"), "named_standard"),\n (\n MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]),\n "unnamed_multi",\n ),\n (\n MultiIndex.from_product(\n [["a", "b"], ["c", "d"], ["e", "f"]], names=["foo", None, "baz"]\n ),\n "named_multi",\n ),\n ],\n)\n@pytest.mark.parametrize(\n "row_index, row_type",\n [\n (Index(np.arange(8)), "unnamed_standard"),\n (Index(np.arange(8), name="index.name"), "named_standard"),\n (\n MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]),\n "unnamed_multi",\n ),\n (\n MultiIndex.from_product(\n [["a", "b"], ["c", "d"], ["e", "f"]], names=["foo", None, "baz"]\n ),\n "named_multi",\n ),\n ],\n)\ndef test_to_html_alignment_with_truncation(\n datapath, row_index, row_type, column_index, column_type, index, header, index_names\n):\n # GH 22747, GH 22579\n df = DataFrame(np.arange(64).reshape(8, 8), index=row_index, columns=column_index)\n result = df.to_html(\n max_rows=4, max_cols=4, index=index, header=header, index_names=index_names\n )\n\n if not index:\n row_type = "none"\n elif not index_names and row_type.startswith("named"):\n row_type = "un" + row_type\n\n if not header:\n column_type = "none"\n elif not index_names and column_type.startswith("named"):\n column_type = "un" + column_type\n\n filename = "trunc_df_index_" + row_type + "_columns_" + column_type\n expected = expected_html(datapath, filename)\n assert result == expected\n\n\n@pytest.mark.parametrize("index", [False, 0])\ndef test_to_html_truncation_index_false_max_rows(datapath, index):\n # GH 15019\n data = [\n [1.764052, 0.400157],\n [0.978738, 2.240893],\n [1.867558, -0.977278],\n [0.950088, -0.151357],\n [-0.103219, 0.410599],\n ]\n df = DataFrame(data)\n result = df.to_html(max_rows=4, index=index)\n expected = expected_html(datapath, "gh15019_expected_output")\n assert result == expected\n\n\n@pytest.mark.parametrize("index", [False, 0])\n@pytest.mark.parametrize(\n "col_index_named, expected_output",\n [(False, "gh22783_expected_output"), (True, "gh22783_named_columns_index")],\n)\ndef test_to_html_truncation_index_false_max_cols(\n datapath, index, col_index_named, expected_output\n):\n # GH 22783\n data = [\n [1.764052, 0.400157, 0.978738, 2.240893, 1.867558],\n [-0.977278, 0.950088, -0.151357, -0.103219, 0.410599],\n ]\n df = DataFrame(data)\n if col_index_named:\n df.columns.rename("columns.name", inplace=True)\n result = df.to_html(max_cols=4, index=index)\n expected = expected_html(datapath, expected_output)\n assert result == expected\n\n\n@pytest.mark.parametrize("notebook", [True, False])\ndef test_to_html_notebook_has_style(notebook):\n df = DataFrame({"A": [1, 2, 3]})\n result = df.to_html(notebook=notebook)\n\n if notebook:\n assert "tbody tr th:only-of-type" in result\n assert "vertical-align: middle;" in result\n assert "thead th" in result\n else:\n assert "tbody tr th:only-of-type" not in result\n assert "vertical-align: middle;" not in result\n assert "thead th" not in result\n\n\ndef test_to_html_with_index_names_false():\n # GH 16493\n df = DataFrame({"A": [1, 2]}, index=Index(["a", "b"], name="myindexname"))\n result = df.to_html(index_names=False)\n assert "myindexname" not in result\n\n\ndef test_to_html_with_id():\n # GH 8496\n df = DataFrame({"A": [1, 2]}, index=Index(["a", "b"], name="myindexname"))\n result = df.to_html(index_names=False, table_id="TEST_ID")\n assert ' id="TEST_ID"' in result\n\n\n@pytest.mark.parametrize(\n "value,float_format,expected",\n [\n (0.19999, "%.3f", "gh21625_expected_output"),\n (100.0, "%.0f", "gh22270_expected_output"),\n ],\n)\ndef test_to_html_float_format_no_fixed_width(value, float_format, expected, datapath):\n # GH 21625, GH 22270\n df = DataFrame({"x": [value]})\n expected = expected_html(datapath, expected)\n result = df.to_html(float_format=float_format)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "render_links,expected",\n [(True, "render_links_true"), (False, "render_links_false")],\n)\ndef test_to_html_render_links(render_links, expected, datapath):\n # GH 2679\n data = [\n [0, "https://pandas.pydata.org/?q1=a&q2=b", "pydata.org"],\n [0, "www.pydata.org", "pydata.org"],\n ]\n df = DataFrame(data, columns=Index(["foo", "bar", None], dtype=object))\n\n result = df.to_html(render_links=render_links)\n expected = expected_html(datapath, expected)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "method,expected",\n [\n ("to_html", lambda x: lorem_ipsum),\n ("_repr_html_", lambda x: lorem_ipsum[: x - 4] + "..."), # regression case\n ],\n)\n@pytest.mark.parametrize("max_colwidth", [10, 20, 50, 100])\ndef test_ignore_display_max_colwidth(method, expected, max_colwidth):\n # see gh-17004\n df = DataFrame([lorem_ipsum])\n with option_context("display.max_colwidth", max_colwidth):\n result = getattr(df, method)()\n expected = expected(max_colwidth)\n assert expected in result\n\n\n@pytest.mark.parametrize("classes", [True, 0])\ndef test_to_html_invalid_classes_type(classes):\n # GH 25608\n df = DataFrame()\n msg = "classes must be a string, list, or tuple"\n\n with pytest.raises(TypeError, match=msg):\n df.to_html(classes=classes)\n\n\ndef test_to_html_round_column_headers():\n # GH 17280\n df = DataFrame([1], columns=[0.55555])\n with option_context("display.precision", 3):\n html = df.to_html(notebook=False)\n notebook = df.to_html(notebook=True)\n assert "0.55555" in html\n assert "0.556" in notebook\n\n\n@pytest.mark.parametrize("unit", ["100px", "10%", "5em", 150])\ndef test_to_html_with_col_space_units(unit):\n # GH 25941\n df = DataFrame(np.random.default_rng(2).random(size=(1, 3)))\n result = df.to_html(col_space=unit)\n result = result.split("tbody")[0]\n hdrs = [x for x in result.split("\n") if re.search(r"<th[>\s]", x)]\n if isinstance(unit, int):\n unit = str(unit) + "px"\n for h in hdrs:\n expected = f'<th style="min-width: {unit};">'\n assert expected in h\n\n\nclass TestReprHTML:\n def test_html_repr_min_rows_default(self, datapath):\n # gh-27991\n\n # default setting no truncation even if above min_rows\n df = DataFrame({"a": range(20)})\n result = df._repr_html_()\n expected = expected_html(datapath, "html_repr_min_rows_default_no_truncation")\n assert result == expected\n\n # default of max_rows 60 triggers truncation if above\n df = DataFrame({"a": range(61)})\n result = df._repr_html_()\n expected = expected_html(datapath, "html_repr_min_rows_default_truncated")\n assert result == expected\n\n @pytest.mark.parametrize(\n "max_rows,min_rows,expected",\n [\n # truncated after first two rows\n (10, 4, "html_repr_max_rows_10_min_rows_4"),\n # when set to None, follow value of max_rows\n (12, None, "html_repr_max_rows_12_min_rows_None"),\n # when set value higher as max_rows, use the minimum\n (10, 12, "html_repr_max_rows_10_min_rows_12"),\n # max_rows of None -> never truncate\n (None, 12, "html_repr_max_rows_None_min_rows_12"),\n ],\n )\n def test_html_repr_min_rows(self, datapath, max_rows, min_rows, expected):\n # gh-27991\n\n df = DataFrame({"a": range(61)})\n expected = expected_html(datapath, expected)\n with option_context("display.max_rows", max_rows, "display.min_rows", min_rows):\n result = df._repr_html_()\n assert result == expected\n\n def test_repr_html_ipython_config(self, ip):\n code = textwrap.dedent(\n """\\n from pandas import DataFrame\n df = DataFrame({"A": [1, 2]})\n df._repr_html_()\n\n cfg = get_ipython().config\n cfg['IPKernelApp']['parent_appname']\n df._repr_html_()\n """\n )\n result = ip.run_cell(code, silent=True)\n assert not result.error_in_exec\n\n def test_info_repr_html(self):\n max_rows = 60\n max_cols = 20\n # Long\n h, w = max_rows + 1, max_cols - 1\n df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})\n assert r"&lt;class" not in df._repr_html_()\n with option_context("display.large_repr", "info"):\n assert r"&lt;class" in df._repr_html_()\n\n # Wide\n h, w = max_rows - 1, max_cols + 1\n df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})\n assert "<class" not in df._repr_html_()\n with option_context(\n "display.large_repr", "info", "display.max_columns", max_cols\n ):\n assert "&lt;class" in df._repr_html_()\n\n def test_fake_qtconsole_repr_html(self, float_frame):\n df = float_frame\n\n def get_ipython():\n return {"config": {"KernelApp": {"parent_appname": "ipython-qtconsole"}}}\n\n repstr = df._repr_html_()\n assert repstr is not None\n\n with option_context("display.max_rows", 5, "display.max_columns", 2):\n repstr = df._repr_html_()\n\n assert "class" in repstr # info fallback\n\n def test_repr_html(self, float_frame):\n df = float_frame\n df._repr_html_()\n\n with option_context("display.max_rows", 1, "display.max_columns", 1):\n df._repr_html_()\n\n with option_context("display.notebook_repr_html", False):\n df._repr_html_()\n\n df = DataFrame([[1, 2], [3, 4]])\n with option_context("display.show_dimensions", True):\n assert "2 rows" in df._repr_html_()\n with option_context("display.show_dimensions", False):\n assert "2 rows" not in df._repr_html_()\n\n def test_repr_html_mathjax(self):\n df = DataFrame([[1, 2], [3, 4]])\n assert "tex2jax_ignore" not in df._repr_html_()\n\n with option_context("display.html.use_mathjax", False):\n assert "tex2jax_ignore" in df._repr_html_()\n\n def test_repr_html_wide(self):\n max_cols = 20\n df = DataFrame([["a" * 25] * (max_cols - 1)] * 10)\n with option_context("display.max_rows", 60, "display.max_columns", 20):\n assert "..." not in df._repr_html_()\n\n wide_df = DataFrame([["a" * 25] * (max_cols + 1)] * 10)\n with option_context("display.max_rows", 60, "display.max_columns", 20):\n assert "..." in wide_df._repr_html_()\n\n def test_repr_html_wide_multiindex_cols(self):\n max_cols = 20\n\n mcols = MultiIndex.from_product(\n [np.arange(max_cols // 2), ["foo", "bar"]], names=["first", "second"]\n )\n df = DataFrame([["a" * 25] * len(mcols)] * 10, columns=mcols)\n reg_repr = df._repr_html_()\n assert "..." not in reg_repr\n\n mcols = MultiIndex.from_product(\n (np.arange(1 + (max_cols // 2)), ["foo", "bar"]), names=["first", "second"]\n )\n df = DataFrame([["a" * 25] * len(mcols)] * 10, columns=mcols)\n with option_context("display.max_rows", 60, "display.max_columns", 20):\n assert "..." in df._repr_html_()\n\n def test_repr_html_long(self):\n with option_context("display.max_rows", 60):\n max_rows = get_option("display.max_rows")\n h = max_rows - 1\n df = DataFrame({"A": np.arange(1, 1 + h), "B": np.arange(41, 41 + h)})\n reg_repr = df._repr_html_()\n assert ".." not in reg_repr\n assert str(41 + max_rows // 2) in reg_repr\n\n h = max_rows + 1\n df = DataFrame({"A": np.arange(1, 1 + h), "B": np.arange(41, 41 + h)})\n long_repr = df._repr_html_()\n assert ".." in long_repr\n assert str(41 + max_rows // 2) not in long_repr\n assert f"{h} rows " in long_repr\n assert "2 columns" in long_repr\n\n def test_repr_html_float(self):\n with option_context("display.max_rows", 60):\n max_rows = get_option("display.max_rows")\n h = max_rows - 1\n df = DataFrame(\n {\n "idx": np.linspace(-10, 10, h),\n "A": np.arange(1, 1 + h),\n "B": np.arange(41, 41 + h),\n }\n ).set_index("idx")\n reg_repr = df._repr_html_()\n assert ".." not in reg_repr\n assert f"<td>{40 + h}</td>" in reg_repr\n\n h = max_rows + 1\n df = DataFrame(\n {\n "idx": np.linspace(-10, 10, h),\n "A": np.arange(1, 1 + h),\n "B": np.arange(41, 41 + h),\n }\n ).set_index("idx")\n long_repr = df._repr_html_()\n assert ".." in long_repr\n assert "<td>31</td>" not in long_repr\n assert f"{h} rows " in long_repr\n assert "2 columns" in long_repr\n\n def test_repr_html_long_multiindex(self):\n max_rows = 60\n max_L1 = max_rows // 2\n\n tuples = list(itertools.product(np.arange(max_L1), ["foo", "bar"]))\n idx = MultiIndex.from_tuples(tuples, names=["first", "second"])\n df = DataFrame(\n np.random.default_rng(2).standard_normal((max_L1 * 2, 2)),\n index=idx,\n columns=["A", "B"],\n )\n with option_context("display.max_rows", 60, "display.max_columns", 20):\n reg_repr = df._repr_html_()\n assert "..." not in reg_repr\n\n tuples = list(itertools.product(np.arange(max_L1 + 1), ["foo", "bar"]))\n idx = MultiIndex.from_tuples(tuples, names=["first", "second"])\n df = DataFrame(\n np.random.default_rng(2).standard_normal(((max_L1 + 1) * 2, 2)),\n index=idx,\n columns=["A", "B"],\n )\n long_repr = df._repr_html_()\n assert "..." in long_repr\n\n def test_repr_html_long_and_wide(self):\n max_cols = 20\n max_rows = 60\n\n h, w = max_rows - 1, max_cols - 1\n df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})\n with option_context("display.max_rows", 60, "display.max_columns", 20):\n assert "..." not in df._repr_html_()\n\n h, w = max_rows + 1, max_cols + 1\n df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)})\n with option_context("display.max_rows", 60, "display.max_columns", 20):\n assert "..." in df._repr_html_()\n\n\ndef test_to_html_multilevel(multiindex_year_month_day_dataframe_random_data):\n ymd = multiindex_year_month_day_dataframe_random_data\n\n ymd.columns.name = "foo"\n ymd.to_html()\n ymd.T.to_html()\n\n\n@pytest.mark.parametrize("na_rep", ["NaN", "Ted"])\ndef test_to_html_na_rep_and_float_format(na_rep, datapath):\n # https://github.com/pandas-dev/pandas/issues/13828\n df = DataFrame(\n [\n ["A", 1.2225],\n ["A", None],\n ],\n columns=["Group", "Data"],\n )\n result = df.to_html(na_rep=na_rep, float_format="{:.2f}".format)\n expected = expected_html(datapath, "gh13828_expected_output")\n expected = expected.format(na_rep=na_rep)\n assert result == expected\n\n\ndef test_to_html_na_rep_non_scalar_data(datapath):\n # GH47103\n df = DataFrame([{"a": 1, "b": [1, 2, 3]}])\n result = df.to_html(na_rep="-")\n expected = expected_html(datapath, "gh47103_expected_output")\n assert result == expected\n\n\ndef test_to_html_float_format_object_col(datapath):\n # GH#40024\n df = DataFrame(data={"x": [1000.0, "test"]})\n result = df.to_html(float_format=lambda x: f"{x:,.0f}")\n expected = expected_html(datapath, "gh40024_expected_output")\n assert result == expected\n\n\ndef test_to_html_multiindex_col_with_colspace():\n # GH#53885\n df = DataFrame([[1, 2]])\n df.columns = MultiIndex.from_tuples([(1, 1), (2, 1)])\n result = df.to_html(col_space=100)\n expected = (\n '<table border="1" class="dataframe">\n'\n " <thead>\n"\n " <tr>\n"\n ' <th style="min-width: 100px;"></th>\n'\n ' <th style="min-width: 100px;">1</th>\n'\n ' <th style="min-width: 100px;">2</th>\n'\n " </tr>\n"\n " <tr>\n"\n ' <th style="min-width: 100px;"></th>\n'\n ' <th style="min-width: 100px;">1</th>\n'\n ' <th style="min-width: 100px;">1</th>\n'\n " </tr>\n"\n " </thead>\n"\n " <tbody>\n"\n " <tr>\n"\n " <th>0</th>\n"\n " <td>1</td>\n"\n " <td>2</td>\n"\n " </tr>\n"\n " </tbody>\n"\n "</table>"\n )\n assert result == expected\n\n\ndef test_to_html_tuple_col_with_colspace():\n # GH#53885\n df = DataFrame({("a", "b"): [1], "b": [2]})\n result = df.to_html(col_space=100)\n expected = (\n '<table border="1" class="dataframe">\n'\n " <thead>\n"\n ' <tr style="text-align: right;">\n'\n ' <th style="min-width: 100px;"></th>\n'\n ' <th style="min-width: 100px;">(a, b)</th>\n'\n ' <th style="min-width: 100px;">b</th>\n'\n " </tr>\n"\n " </thead>\n"\n " <tbody>\n"\n " <tr>\n"\n " <th>0</th>\n"\n " <td>1</td>\n"\n " <td>2</td>\n"\n " </tr>\n"\n " </tbody>\n"\n "</table>"\n )\n assert result == expected\n\n\ndef test_to_html_empty_complex_array():\n # GH#54167\n df = DataFrame({"x": np.array([], dtype="complex")})\n result = df.to_html(col_space=100)\n expected = (\n '<table border="1" class="dataframe">\n'\n " <thead>\n"\n ' <tr style="text-align: right;">\n'\n ' <th style="min-width: 100px;"></th>\n'\n ' <th style="min-width: 100px;">x</th>\n'\n " </tr>\n"\n " </thead>\n"\n " <tbody>\n"\n " </tbody>\n"\n "</table>"\n )\n assert result == expected\n\n\ndef test_to_html_pos_args_deprecation():\n # GH-54229\n df = DataFrame({"a": [1, 2, 3]})\n msg = (\n r"Starting with pandas version 3.0 all arguments of to_html except for the "\n r"argument 'buf' will be keyword-only."\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n df.to_html(None, None)\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_to_html.py
test_to_html.py
Python
38,699
0.95
0.099405
0.046278
node-utils
277
2025-03-27T10:01:28.280292
MIT
true
f8bebe7b7b0a6f86a4140ac4f68b4cbd
import codecs\nfrom datetime import datetime\nfrom textwrap import dedent\n\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\n\npytest.importorskip("jinja2")\n\n\ndef _dedent(string):\n """Dedent without new line in the beginning.\n\n Built-in textwrap.dedent would keep new line character in the beginning\n of multi-line string starting from the new line.\n This version drops the leading new line character.\n """\n return dedent(string).lstrip()\n\n\n@pytest.fixture\ndef df_short():\n """Short dataframe for testing table/tabular/longtable LaTeX env."""\n return DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n\n\nclass TestToLatex:\n def test_to_latex_to_file(self, float_frame):\n with tm.ensure_clean("test.tex") as path:\n float_frame.to_latex(path)\n with open(path, encoding="utf-8") as f:\n assert float_frame.to_latex() == f.read()\n\n def test_to_latex_to_file_utf8_with_encoding(self):\n # test with utf-8 and encoding option (GH 7061)\n df = DataFrame([["au\xdfgangen"]])\n with tm.ensure_clean("test.tex") as path:\n df.to_latex(path, encoding="utf-8")\n with codecs.open(path, "r", encoding="utf-8") as f:\n assert df.to_latex() == f.read()\n\n def test_to_latex_to_file_utf8_without_encoding(self):\n # test with utf-8 without encoding option\n df = DataFrame([["au\xdfgangen"]])\n with tm.ensure_clean("test.tex") as path:\n df.to_latex(path)\n with codecs.open(path, "r", encoding="utf-8") as f:\n assert df.to_latex() == f.read()\n\n def test_to_latex_tabular_with_index(self):\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex()\n expected = _dedent(\n r"""\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_tabular_without_index(self):\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(index=False)\n expected = _dedent(\n r"""\n \begin{tabular}{rl}\n \toprule\n a & b \\\n \midrule\n 1 & b1 \\\n 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n @pytest.mark.parametrize(\n "bad_column_format",\n [5, 1.2, ["l", "r"], ("r", "c"), {"r", "c", "l"}, {"a": "r", "b": "l"}],\n )\n def test_to_latex_bad_column_format(self, bad_column_format):\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n msg = r"`column_format` must be str or unicode"\n with pytest.raises(ValueError, match=msg):\n df.to_latex(column_format=bad_column_format)\n\n def test_to_latex_column_format_just_works(self, float_frame):\n # GH Bug #9402\n float_frame.to_latex(column_format="lcr")\n\n def test_to_latex_column_format(self):\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(column_format="lcr")\n expected = _dedent(\n r"""\n \begin{tabular}{lcr}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_float_format_object_col(self):\n # GH#40024\n ser = Series([1000.0, "test"])\n result = ser.to_latex(float_format="{:,.0f}".format)\n expected = _dedent(\n r"""\n \begin{tabular}{ll}\n \toprule\n & 0 \\\n \midrule\n 0 & 1,000 \\\n 1 & test \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_empty_tabular(self):\n df = DataFrame()\n result = df.to_latex()\n expected = _dedent(\n r"""\n \begin{tabular}{l}\n \toprule\n \midrule\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_series(self):\n s = Series(["a", "b", "c"])\n result = s.to_latex()\n expected = _dedent(\n r"""\n \begin{tabular}{ll}\n \toprule\n & 0 \\\n \midrule\n 0 & a \\\n 1 & b \\\n 2 & c \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_midrule_location(self):\n # GH 18326\n df = DataFrame({"a": [1, 2]})\n df.index.name = "foo"\n result = df.to_latex(index_names=False)\n expected = _dedent(\n r"""\n \begin{tabular}{lr}\n \toprule\n & a \\\n \midrule\n 0 & 1 \\\n 1 & 2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_pos_args_deprecation(self):\n # GH-54229\n df = DataFrame(\n {\n "name": ["Raphael", "Donatello"],\n "age": [26, 45],\n "height": [181.23, 177.65],\n }\n )\n msg = (\n r"Starting with pandas version 3.0 all arguments of to_latex except for "\n r"the argument 'buf' will be keyword-only."\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n df.to_latex(None, None)\n\n\nclass TestToLatexLongtable:\n def test_to_latex_empty_longtable(self):\n df = DataFrame()\n result = df.to_latex(longtable=True)\n expected = _dedent(\n r"""\n \begin{longtable}{l}\n \toprule\n \midrule\n \endfirsthead\n \toprule\n \midrule\n \endhead\n \midrule\n \multicolumn{0}{r}{Continued on next page} \\\n \midrule\n \endfoot\n \bottomrule\n \endlastfoot\n \end{longtable}\n """\n )\n assert result == expected\n\n def test_to_latex_longtable_with_index(self):\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(longtable=True)\n expected = _dedent(\n r"""\n \begin{longtable}{lrl}\n \toprule\n & a & b \\\n \midrule\n \endfirsthead\n \toprule\n & a & b \\\n \midrule\n \endhead\n \midrule\n \multicolumn{3}{r}{Continued on next page} \\\n \midrule\n \endfoot\n \bottomrule\n \endlastfoot\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \end{longtable}\n """\n )\n assert result == expected\n\n def test_to_latex_longtable_without_index(self):\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(index=False, longtable=True)\n expected = _dedent(\n r"""\n \begin{longtable}{rl}\n \toprule\n a & b \\\n \midrule\n \endfirsthead\n \toprule\n a & b \\\n \midrule\n \endhead\n \midrule\n \multicolumn{2}{r}{Continued on next page} \\\n \midrule\n \endfoot\n \bottomrule\n \endlastfoot\n 1 & b1 \\\n 2 & b2 \\\n \end{longtable}\n """\n )\n assert result == expected\n\n @pytest.mark.parametrize(\n "df, expected_number",\n [\n (DataFrame({"a": [1, 2]}), 1),\n (DataFrame({"a": [1, 2], "b": [3, 4]}), 2),\n (DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}), 3),\n ],\n )\n def test_to_latex_longtable_continued_on_next_page(self, df, expected_number):\n result = df.to_latex(index=False, longtable=True)\n assert rf"\multicolumn{{{expected_number}}}" in result\n\n\nclass TestToLatexHeader:\n def test_to_latex_no_header_with_index(self):\n # GH 7124\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(header=False)\n expected = _dedent(\n r"""\n \begin{tabular}{lrl}\n \toprule\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_no_header_without_index(self):\n # GH 7124\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(index=False, header=False)\n expected = _dedent(\n r"""\n \begin{tabular}{rl}\n \toprule\n \midrule\n 1 & b1 \\\n 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_specified_header_with_index(self):\n # GH 7124\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(header=["AA", "BB"])\n expected = _dedent(\n r"""\n \begin{tabular}{lrl}\n \toprule\n & AA & BB \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_specified_header_without_index(self):\n # GH 7124\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(header=["AA", "BB"], index=False)\n expected = _dedent(\n r"""\n \begin{tabular}{rl}\n \toprule\n AA & BB \\\n \midrule\n 1 & b1 \\\n 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n @pytest.mark.parametrize(\n "header, num_aliases",\n [\n (["A"], 1),\n (("B",), 1),\n (("Col1", "Col2", "Col3"), 3),\n (("Col1", "Col2", "Col3", "Col4"), 4),\n ],\n )\n def test_to_latex_number_of_items_in_header_missmatch_raises(\n self,\n header,\n num_aliases,\n ):\n # GH 7124\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n msg = f"Writing 2 cols but got {num_aliases} aliases"\n with pytest.raises(ValueError, match=msg):\n df.to_latex(header=header)\n\n def test_to_latex_decimal(self):\n # GH 12031\n df = DataFrame({"a": [1.0, 2.1], "b": ["b1", "b2"]})\n result = df.to_latex(decimal=",")\n expected = _dedent(\n r"""\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1,000000 & b1 \\\n 1 & 2,100000 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n\nclass TestToLatexBold:\n def test_to_latex_bold_rows(self):\n # GH 16707\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(bold_rows=True)\n expected = _dedent(\n r"""\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n \textbf{0} & 1 & b1 \\\n \textbf{1} & 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_no_bold_rows(self):\n # GH 16707\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(bold_rows=False)\n expected = _dedent(\n r"""\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n\nclass TestToLatexCaptionLabel:\n @pytest.fixture\n def caption_table(self):\n """Caption for table/tabular LaTeX environment."""\n return "a table in a \\texttt{table/tabular} environment"\n\n @pytest.fixture\n def short_caption(self):\n """Short caption for testing \\caption[short_caption]{full_caption}."""\n return "a table"\n\n @pytest.fixture\n def label_table(self):\n """Label for table/tabular LaTeX environment."""\n return "tab:table_tabular"\n\n @pytest.fixture\n def caption_longtable(self):\n """Caption for longtable LaTeX environment."""\n return "a table in a \\texttt{longtable} environment"\n\n @pytest.fixture\n def label_longtable(self):\n """Label for longtable LaTeX environment."""\n return "tab:longtable"\n\n def test_to_latex_caption_only(self, df_short, caption_table):\n # GH 25436\n result = df_short.to_latex(caption=caption_table)\n expected = _dedent(\n r"""\n \begin{table}\n \caption{a table in a \texttt{table/tabular} environment}\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n \end{table}\n """\n )\n assert result == expected\n\n def test_to_latex_label_only(self, df_short, label_table):\n # GH 25436\n result = df_short.to_latex(label=label_table)\n expected = _dedent(\n r"""\n \begin{table}\n \label{tab:table_tabular}\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n \end{table}\n """\n )\n assert result == expected\n\n def test_to_latex_caption_and_label(self, df_short, caption_table, label_table):\n # GH 25436\n result = df_short.to_latex(caption=caption_table, label=label_table)\n expected = _dedent(\n r"""\n \begin{table}\n \caption{a table in a \texttt{table/tabular} environment}\n \label{tab:table_tabular}\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n \end{table}\n """\n )\n assert result == expected\n\n def test_to_latex_caption_and_shortcaption(\n self,\n df_short,\n caption_table,\n short_caption,\n ):\n result = df_short.to_latex(caption=(caption_table, short_caption))\n expected = _dedent(\n r"""\n \begin{table}\n \caption[a table]{a table in a \texttt{table/tabular} environment}\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n \end{table}\n """\n )\n assert result == expected\n\n def test_to_latex_caption_and_shortcaption_list_is_ok(self, df_short):\n caption = ("Long-long-caption", "Short")\n result_tuple = df_short.to_latex(caption=caption)\n result_list = df_short.to_latex(caption=list(caption))\n assert result_tuple == result_list\n\n def test_to_latex_caption_shortcaption_and_label(\n self,\n df_short,\n caption_table,\n short_caption,\n label_table,\n ):\n # test when the short_caption is provided alongside caption and label\n result = df_short.to_latex(\n caption=(caption_table, short_caption),\n label=label_table,\n )\n expected = _dedent(\n r"""\n \begin{table}\n \caption[a table]{a table in a \texttt{table/tabular} environment}\n \label{tab:table_tabular}\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n \end{table}\n """\n )\n assert result == expected\n\n @pytest.mark.parametrize(\n "bad_caption",\n [\n ("full_caption", "short_caption", "extra_string"),\n ("full_caption", "short_caption", 1),\n ("full_caption", "short_caption", None),\n ("full_caption",),\n (None,),\n ],\n )\n def test_to_latex_bad_caption_raises(self, bad_caption):\n # test that wrong number of params is raised\n df = DataFrame({"a": [1]})\n msg = "`caption` must be either a string or 2-tuple of strings"\n with pytest.raises(ValueError, match=msg):\n df.to_latex(caption=bad_caption)\n\n def test_to_latex_two_chars_caption(self, df_short):\n # test that two chars caption is handled correctly\n # it must not be unpacked into long_caption, short_caption.\n result = df_short.to_latex(caption="xy")\n expected = _dedent(\n r"""\n \begin{table}\n \caption{xy}\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n \end{table}\n """\n )\n assert result == expected\n\n def test_to_latex_longtable_caption_only(self, df_short, caption_longtable):\n # GH 25436\n # test when no caption and no label is provided\n # is performed by test_to_latex_longtable()\n result = df_short.to_latex(longtable=True, caption=caption_longtable)\n expected = _dedent(\n r"""\n \begin{longtable}{lrl}\n \caption{a table in a \texttt{longtable} environment} \\\n \toprule\n & a & b \\\n \midrule\n \endfirsthead\n \caption[]{a table in a \texttt{longtable} environment} \\\n \toprule\n & a & b \\\n \midrule\n \endhead\n \midrule\n \multicolumn{3}{r}{Continued on next page} \\\n \midrule\n \endfoot\n \bottomrule\n \endlastfoot\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \end{longtable}\n """\n )\n assert result == expected\n\n def test_to_latex_longtable_label_only(self, df_short, label_longtable):\n # GH 25436\n result = df_short.to_latex(longtable=True, label=label_longtable)\n expected = _dedent(\n r"""\n \begin{longtable}{lrl}\n \label{tab:longtable} \\\n \toprule\n & a & b \\\n \midrule\n \endfirsthead\n \toprule\n & a & b \\\n \midrule\n \endhead\n \midrule\n \multicolumn{3}{r}{Continued on next page} \\\n \midrule\n \endfoot\n \bottomrule\n \endlastfoot\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \end{longtable}\n """\n )\n assert result == expected\n\n def test_to_latex_longtable_caption_and_label(\n self,\n df_short,\n caption_longtable,\n label_longtable,\n ):\n # GH 25436\n result = df_short.to_latex(\n longtable=True,\n caption=caption_longtable,\n label=label_longtable,\n )\n expected = _dedent(\n r"""\n \begin{longtable}{lrl}\n \caption{a table in a \texttt{longtable} environment} \label{tab:longtable} \\\n \toprule\n & a & b \\\n \midrule\n \endfirsthead\n \caption[]{a table in a \texttt{longtable} environment} \\\n \toprule\n & a & b \\\n \midrule\n \endhead\n \midrule\n \multicolumn{3}{r}{Continued on next page} \\\n \midrule\n \endfoot\n \bottomrule\n \endlastfoot\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \end{longtable}\n """\n )\n assert result == expected\n\n def test_to_latex_longtable_caption_shortcaption_and_label(\n self,\n df_short,\n caption_longtable,\n short_caption,\n label_longtable,\n ):\n # test when the caption, the short_caption and the label are provided\n result = df_short.to_latex(\n longtable=True,\n caption=(caption_longtable, short_caption),\n label=label_longtable,\n )\n expected = _dedent(\n r"""\n\begin{longtable}{lrl}\n\caption[a table]{a table in a \texttt{longtable} environment} \label{tab:longtable} \\\n\toprule\n & a & b \\\n\midrule\n\endfirsthead\n\caption[]{a table in a \texttt{longtable} environment} \\\n\toprule\n & a & b \\\n\midrule\n\endhead\n\midrule\n\multicolumn{3}{r}{Continued on next page} \\\n\midrule\n\endfoot\n\bottomrule\n\endlastfoot\n0 & 1 & b1 \\\n1 & 2 & b2 \\\n\end{longtable}\n"""\n )\n assert result == expected\n\n\nclass TestToLatexEscape:\n @pytest.fixture\n def df_with_symbols(self):\n """Dataframe with special characters for testing chars escaping."""\n a = "a"\n b = "b"\n yield DataFrame({"co$e^x$": {a: "a", b: "b"}, "co^l1": {a: "a", b: "b"}})\n\n def test_to_latex_escape_false(self, df_with_symbols):\n result = df_with_symbols.to_latex(escape=False)\n expected = _dedent(\n r"""\n \begin{tabular}{lll}\n \toprule\n & co$e^x$ & co^l1 \\\n \midrule\n a & a & a \\\n b & b & b \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_escape_default(self, df_with_symbols):\n # gh50871: in v2.0 escape is False by default (styler.format.escape=None)\n default = df_with_symbols.to_latex()\n specified_true = df_with_symbols.to_latex(escape=True)\n assert default != specified_true\n\n def test_to_latex_special_escape(self):\n df = DataFrame([r"a\b\c", r"^a^b^c", r"~a~b~c"])\n result = df.to_latex(escape=True)\n expected = _dedent(\n r"""\n \begin{tabular}{ll}\n \toprule\n & 0 \\\n \midrule\n 0 & a\textbackslash b\textbackslash c \\\n 1 & \textasciicircum a\textasciicircum b\textasciicircum c \\\n 2 & \textasciitilde a\textasciitilde b\textasciitilde c \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_escape_special_chars(self):\n special_characters = ["&", "%", "$", "#", "_", "{", "}", "~", "^", "\\"]\n df = DataFrame(data=special_characters)\n result = df.to_latex(escape=True)\n expected = _dedent(\n r"""\n \begin{tabular}{ll}\n \toprule\n & 0 \\\n \midrule\n 0 & \& \\\n 1 & \% \\\n 2 & \$ \\\n 3 & \# \\\n 4 & \_ \\\n 5 & \{ \\\n 6 & \} \\\n 7 & \textasciitilde \\\n 8 & \textasciicircum \\\n 9 & \textbackslash \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_specified_header_special_chars_without_escape(self):\n # GH 7124\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(header=["$A$", "$B$"], escape=False)\n expected = _dedent(\n r"""\n \begin{tabular}{lrl}\n \toprule\n & $A$ & $B$ \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n\nclass TestToLatexPosition:\n def test_to_latex_position(self):\n the_position = "h"\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(position=the_position)\n expected = _dedent(\n r"""\n \begin{table}[h]\n \begin{tabular}{lrl}\n \toprule\n & a & b \\\n \midrule\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \bottomrule\n \end{tabular}\n \end{table}\n """\n )\n assert result == expected\n\n def test_to_latex_longtable_position(self):\n the_position = "t"\n df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})\n result = df.to_latex(longtable=True, position=the_position)\n expected = _dedent(\n r"""\n \begin{longtable}[t]{lrl}\n \toprule\n & a & b \\\n \midrule\n \endfirsthead\n \toprule\n & a & b \\\n \midrule\n \endhead\n \midrule\n \multicolumn{3}{r}{Continued on next page} \\\n \midrule\n \endfoot\n \bottomrule\n \endlastfoot\n 0 & 1 & b1 \\\n 1 & 2 & b2 \\\n \end{longtable}\n """\n )\n assert result == expected\n\n\nclass TestToLatexFormatters:\n def test_to_latex_with_formatters(self):\n df = DataFrame(\n {\n "datetime64": [\n datetime(2016, 1, 1),\n datetime(2016, 2, 5),\n datetime(2016, 3, 3),\n ],\n "float": [1.0, 2.0, 3.0],\n "int": [1, 2, 3],\n "object": [(1, 2), True, False],\n }\n )\n\n formatters = {\n "datetime64": lambda x: x.strftime("%Y-%m"),\n "float": lambda x: f"[{x: 4.1f}]",\n "int": lambda x: f"0x{x:x}",\n "object": lambda x: f"-{x!s}-",\n "__index__": lambda x: f"index: {x}",\n }\n result = df.to_latex(formatters=dict(formatters))\n\n expected = _dedent(\n r"""\n \begin{tabular}{llrrl}\n \toprule\n & datetime64 & float & int & object \\\n \midrule\n index: 0 & 2016-01 & [ 1.0] & 0x1 & -(1, 2)- \\\n index: 1 & 2016-02 & [ 2.0] & 0x2 & -True- \\\n index: 2 & 2016-03 & [ 3.0] & 0x3 & -False- \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_float_format_no_fixed_width_3decimals(self):\n # GH 21625\n df = DataFrame({"x": [0.19999]})\n result = df.to_latex(float_format="%.3f")\n expected = _dedent(\n r"""\n \begin{tabular}{lr}\n \toprule\n & x \\\n \midrule\n 0 & 0.200 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_float_format_no_fixed_width_integer(self):\n # GH 22270\n df = DataFrame({"x": [100.0]})\n result = df.to_latex(float_format="%.0f")\n expected = _dedent(\n r"""\n \begin{tabular}{lr}\n \toprule\n & x \\\n \midrule\n 0 & 100 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n @pytest.mark.parametrize("na_rep", ["NaN", "Ted"])\n def test_to_latex_na_rep_and_float_format(self, na_rep):\n df = DataFrame(\n [\n ["A", 1.2225],\n ["A", None],\n ],\n columns=["Group", "Data"],\n )\n result = df.to_latex(na_rep=na_rep, float_format="{:.2f}".format)\n expected = _dedent(\n rf"""\n \begin{{tabular}}{{llr}}\n \toprule\n & Group & Data \\\n \midrule\n 0 & A & 1.22 \\\n 1 & A & {na_rep} \\\n \bottomrule\n \end{{tabular}}\n """\n )\n assert result == expected\n\n\nclass TestToLatexMultiindex:\n @pytest.fixture\n def multiindex_frame(self):\n """Multiindex dataframe for testing multirow LaTeX macros."""\n yield DataFrame.from_dict(\n {\n ("c1", 0): Series({x: x for x in range(4)}),\n ("c1", 1): Series({x: x + 4 for x in range(4)}),\n ("c2", 0): Series({x: x for x in range(4)}),\n ("c2", 1): Series({x: x + 4 for x in range(4)}),\n ("c3", 0): Series({x: x for x in range(4)}),\n }\n ).T\n\n @pytest.fixture\n def multicolumn_frame(self):\n """Multicolumn dataframe for testing multicolumn LaTeX macros."""\n yield DataFrame(\n {\n ("c1", 0): {x: x for x in range(5)},\n ("c1", 1): {x: x + 5 for x in range(5)},\n ("c2", 0): {x: x for x in range(5)},\n ("c2", 1): {x: x + 5 for x in range(5)},\n ("c3", 0): {x: x for x in range(5)},\n }\n )\n\n def test_to_latex_multindex_header(self):\n # GH 16718\n df = DataFrame({"a": [0], "b": [1], "c": [2], "d": [3]})\n df = df.set_index(["a", "b"])\n observed = df.to_latex(header=["r1", "r2"], multirow=False)\n expected = _dedent(\n r"""\n \begin{tabular}{llrr}\n \toprule\n & & r1 & r2 \\\n a & b & & \\\n \midrule\n 0 & 1 & 2 & 3 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert observed == expected\n\n def test_to_latex_multiindex_empty_name(self):\n # GH 18669\n mi = pd.MultiIndex.from_product([[1, 2]], names=[""])\n df = DataFrame(-1, index=mi, columns=range(4))\n observed = df.to_latex()\n expected = _dedent(\n r"""\n \begin{tabular}{lrrrr}\n \toprule\n & 0 & 1 & 2 & 3 \\\n & & & & \\\n \midrule\n 1 & -1 & -1 & -1 & -1 \\\n 2 & -1 & -1 & -1 & -1 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert observed == expected\n\n def test_to_latex_multiindex_column_tabular(self):\n df = DataFrame({("x", "y"): ["a"]})\n result = df.to_latex()\n expected = _dedent(\n r"""\n \begin{tabular}{ll}\n \toprule\n & x \\\n & y \\\n \midrule\n 0 & a \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_multiindex_small_tabular(self):\n df = DataFrame({("x", "y"): ["a"]}).T\n result = df.to_latex(multirow=False)\n expected = _dedent(\n r"""\n \begin{tabular}{lll}\n \toprule\n & & 0 \\\n \midrule\n x & y & a \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_multiindex_tabular(self, multiindex_frame):\n result = multiindex_frame.to_latex(multirow=False)\n expected = _dedent(\n r"""\n \begin{tabular}{llrrrr}\n \toprule\n & & 0 & 1 & 2 & 3 \\\n \midrule\n c1 & 0 & 0 & 1 & 2 & 3 \\\n & 1 & 4 & 5 & 6 & 7 \\\n c2 & 0 & 0 & 1 & 2 & 3 \\\n & 1 & 4 & 5 & 6 & 7 \\\n c3 & 0 & 0 & 1 & 2 & 3 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_multicolumn_tabular(self, multiindex_frame):\n # GH 14184\n df = multiindex_frame.T\n df.columns.names = ["a", "b"]\n result = df.to_latex(multirow=False)\n expected = _dedent(\n r"""\n \begin{tabular}{lrrrrr}\n \toprule\n a & \multicolumn{2}{r}{c1} & \multicolumn{2}{r}{c2} & c3 \\\n b & 0 & 1 & 0 & 1 & 0 \\\n \midrule\n 0 & 0 & 4 & 0 & 4 & 0 \\\n 1 & 1 & 5 & 1 & 5 & 1 \\\n 2 & 2 & 6 & 2 & 6 & 2 \\\n 3 & 3 & 7 & 3 & 7 & 3 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_index_has_name_tabular(self):\n # GH 10660\n df = DataFrame({"a": [0, 0, 1, 1], "b": list("abab"), "c": [1, 2, 3, 4]})\n result = df.set_index(["a", "b"]).to_latex(multirow=False)\n expected = _dedent(\n r"""\n \begin{tabular}{llr}\n \toprule\n & & c \\\n a & b & \\\n \midrule\n 0 & a & 1 \\\n & b & 2 \\\n 1 & a & 3 \\\n & b & 4 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_groupby_tabular(self):\n # GH 10660\n df = DataFrame({"a": [0, 0, 1, 1], "b": list("abab"), "c": [1, 2, 3, 4]})\n result = (\n df.groupby("a")\n .describe()\n .to_latex(float_format="{:.1f}".format, escape=True)\n )\n expected = _dedent(\n r"""\n \begin{tabular}{lrrrrrrrr}\n \toprule\n & \multicolumn{8}{r}{c} \\\n & count & mean & std & min & 25\% & 50\% & 75\% & max \\\n a & & & & & & & & \\\n \midrule\n 0 & 2.0 & 1.5 & 0.7 & 1.0 & 1.2 & 1.5 & 1.8 & 2.0 \\\n 1 & 2.0 & 3.5 & 0.7 & 3.0 & 3.2 & 3.5 & 3.8 & 4.0 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_multiindex_dupe_level(self):\n # see gh-14484\n #\n # If an index is repeated in subsequent rows, it should be\n # replaced with a blank in the created table. This should\n # ONLY happen if all higher order indices (to the left) are\n # equal too. In this test, 'c' has to be printed both times\n # because the higher order index 'A' != 'B'.\n df = DataFrame(\n index=pd.MultiIndex.from_tuples([("A", "c"), ("B", "c")]), columns=["col"]\n )\n result = df.to_latex(multirow=False)\n expected = _dedent(\n r"""\n \begin{tabular}{lll}\n \toprule\n & & col \\\n \midrule\n A & c & NaN \\\n B & c & NaN \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_multicolumn_default(self, multicolumn_frame):\n result = multicolumn_frame.to_latex()\n expected = _dedent(\n r"""\n \begin{tabular}{lrrrrr}\n \toprule\n & \multicolumn{2}{r}{c1} & \multicolumn{2}{r}{c2} & c3 \\\n & 0 & 1 & 0 & 1 & 0 \\\n \midrule\n 0 & 0 & 5 & 0 & 5 & 0 \\\n 1 & 1 & 6 & 1 & 6 & 1 \\\n 2 & 2 & 7 & 2 & 7 & 2 \\\n 3 & 3 & 8 & 3 & 8 & 3 \\\n 4 & 4 & 9 & 4 & 9 & 4 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_multicolumn_false(self, multicolumn_frame):\n result = multicolumn_frame.to_latex(multicolumn=False, multicolumn_format="l")\n expected = _dedent(\n r"""\n \begin{tabular}{lrrrrr}\n \toprule\n & c1 & & c2 & & c3 \\\n & 0 & 1 & 0 & 1 & 0 \\\n \midrule\n 0 & 0 & 5 & 0 & 5 & 0 \\\n 1 & 1 & 6 & 1 & 6 & 1 \\\n 2 & 2 & 7 & 2 & 7 & 2 \\\n 3 & 3 & 8 & 3 & 8 & 3 \\\n 4 & 4 & 9 & 4 & 9 & 4 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_multirow_true(self, multicolumn_frame):\n result = multicolumn_frame.T.to_latex(multirow=True)\n expected = _dedent(\n r"""\n \begin{tabular}{llrrrrr}\n \toprule\n & & 0 & 1 & 2 & 3 & 4 \\\n \midrule\n \multirow[t]{2}{*}{c1} & 0 & 0 & 1 & 2 & 3 & 4 \\\n & 1 & 5 & 6 & 7 & 8 & 9 \\\n \cline{1-7}\n \multirow[t]{2}{*}{c2} & 0 & 0 & 1 & 2 & 3 & 4 \\\n & 1 & 5 & 6 & 7 & 8 & 9 \\\n \cline{1-7}\n c3 & 0 & 0 & 1 & 2 & 3 & 4 \\\n \cline{1-7}\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_multicolumnrow_with_multicol_format(self, multicolumn_frame):\n multicolumn_frame.index = multicolumn_frame.T.index\n result = multicolumn_frame.T.to_latex(\n multirow=True,\n multicolumn=True,\n multicolumn_format="c",\n )\n expected = _dedent(\n r"""\n \begin{tabular}{llrrrrr}\n \toprule\n & & \multicolumn{2}{c}{c1} & \multicolumn{2}{c}{c2} & c3 \\\n & & 0 & 1 & 0 & 1 & 0 \\\n \midrule\n \multirow[t]{2}{*}{c1} & 0 & 0 & 1 & 2 & 3 & 4 \\\n & 1 & 5 & 6 & 7 & 8 & 9 \\\n \cline{1-7}\n \multirow[t]{2}{*}{c2} & 0 & 0 & 1 & 2 & 3 & 4 \\\n & 1 & 5 & 6 & 7 & 8 & 9 \\\n \cline{1-7}\n c3 & 0 & 0 & 1 & 2 & 3 & 4 \\\n \cline{1-7}\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n @pytest.mark.parametrize("name0", [None, "named0"])\n @pytest.mark.parametrize("name1", [None, "named1"])\n @pytest.mark.parametrize("axes", [[0], [1], [0, 1]])\n def test_to_latex_multiindex_names(self, name0, name1, axes):\n # GH 18667\n names = [name0, name1]\n mi = pd.MultiIndex.from_product([[1, 2], [3, 4]])\n df = DataFrame(-1, index=mi.copy(), columns=mi.copy())\n for idx in axes:\n df.axes[idx].names = names\n\n idx_names = tuple(n or "" for n in names)\n idx_names_row = (\n f"{idx_names[0]} & {idx_names[1]} & & & & \\\\\n"\n if (0 in axes and any(names))\n else ""\n )\n col_names = [n if (bool(n) and 1 in axes) else "" for n in names]\n observed = df.to_latex(multirow=False)\n # pylint: disable-next=consider-using-f-string\n expected = r"""\begin{tabular}{llrrrr}\n\toprule\n & %s & \multicolumn{2}{r}{1} & \multicolumn{2}{r}{2} \\\n & %s & 3 & 4 & 3 & 4 \\\n%s\midrule\n1 & 3 & -1 & -1 & -1 & -1 \\\n & 4 & -1 & -1 & -1 & -1 \\\n2 & 3 & -1 & -1 & -1 & -1 \\\n & 4 & -1 & -1 & -1 & -1 \\\n\bottomrule\n\end{tabular}\n""" % tuple(\n list(col_names) + [idx_names_row]\n )\n assert observed == expected\n\n @pytest.mark.parametrize("one_row", [True, False])\n def test_to_latex_multiindex_nans(self, one_row):\n # GH 14249\n df = DataFrame({"a": [None, 1], "b": [2, 3], "c": [4, 5]})\n if one_row:\n df = df.iloc[[0]]\n observed = df.set_index(["a", "b"]).to_latex(multirow=False)\n expected = _dedent(\n r"""\n \begin{tabular}{llr}\n \toprule\n & & c \\\n a & b & \\\n \midrule\n NaN & 2 & 4 \\\n """\n )\n if not one_row:\n expected += r"""1.000000 & 3 & 5 \\\n"""\n expected += r"""\bottomrule\n\end{tabular}\n"""\n assert observed == expected\n\n def test_to_latex_non_string_index(self):\n # GH 19981\n df = DataFrame([[1, 2, 3]] * 2).set_index([0, 1])\n result = df.to_latex(multirow=False)\n expected = _dedent(\n r"""\n \begin{tabular}{llr}\n \toprule\n & & 2 \\\n 0 & 1 & \\\n \midrule\n 1 & 2 & 3 \\\n & 2 & 3 \\\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n\n def test_to_latex_multiindex_multirow(self):\n # GH 16719\n mi = pd.MultiIndex.from_product(\n [[0.0, 1.0], [3.0, 2.0, 1.0], ["0", "1"]], names=["i", "val0", "val1"]\n )\n df = DataFrame(index=mi)\n result = df.to_latex(multirow=True, escape=False)\n expected = _dedent(\n r"""\n \begin{tabular}{lll}\n \toprule\n i & val0 & val1 \\\n \midrule\n \multirow[t]{6}{*}{0.000000} & \multirow[t]{2}{*}{3.000000} & 0 \\\n & & 1 \\\n \cline{2-3}\n & \multirow[t]{2}{*}{2.000000} & 0 \\\n & & 1 \\\n \cline{2-3}\n & \multirow[t]{2}{*}{1.000000} & 0 \\\n & & 1 \\\n \cline{1-3} \cline{2-3}\n \multirow[t]{6}{*}{1.000000} & \multirow[t]{2}{*}{3.000000} & 0 \\\n & & 1 \\\n \cline{2-3}\n & \multirow[t]{2}{*}{2.000000} & 0 \\\n & & 1 \\\n \cline{2-3}\n & \multirow[t]{2}{*}{1.000000} & 0 \\\n & & 1 \\\n \cline{1-3} \cline{2-3}\n \bottomrule\n \end{tabular}\n """\n )\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_to_latex.py
test_to_latex.py
Python
41,660
0.95
0.078596
0.036036
vue-tools
400
2025-02-25T16:19:38.308108
GPL-3.0
true
f7a3c8e54ff45c4a6e51c5cf3e9fedee
from io import (\n BytesIO,\n StringIO,\n)\n\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\npytest.importorskip("tabulate")\n\n\ndef test_simple():\n buf = StringIO()\n df = pd.DataFrame([1, 2, 3])\n df.to_markdown(buf=buf)\n result = buf.getvalue()\n assert (\n result == "| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"\n )\n\n\ndef test_empty_frame():\n buf = StringIO()\n df = pd.DataFrame({"id": [], "first_name": [], "last_name": []}).set_index("id")\n df.to_markdown(buf=buf)\n result = buf.getvalue()\n assert result == (\n "| id | first_name | last_name |\n"\n "|------|--------------|-------------|"\n )\n\n\ndef test_other_tablefmt():\n buf = StringIO()\n df = pd.DataFrame([1, 2, 3])\n df.to_markdown(buf=buf, tablefmt="jira")\n result = buf.getvalue()\n assert result == "|| || 0 ||\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"\n\n\ndef test_other_headers():\n buf = StringIO()\n df = pd.DataFrame([1, 2, 3])\n df.to_markdown(buf=buf, headers=["foo", "bar"])\n result = buf.getvalue()\n assert result == (\n "| foo | bar |\n|------:|------:|\n| 0 "\n "| 1 |\n| 1 | 2 |\n| 2 | 3 |"\n )\n\n\ndef test_series():\n buf = StringIO()\n s = pd.Series([1, 2, 3], name="foo")\n s.to_markdown(buf=buf)\n result = buf.getvalue()\n assert result == (\n "| | foo |\n|---:|------:|\n| 0 | 1 "\n "|\n| 1 | 2 |\n| 2 | 3 |"\n )\n\n\ndef test_no_buf():\n df = pd.DataFrame([1, 2, 3])\n result = df.to_markdown()\n assert (\n result == "| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"\n )\n\n\n@pytest.mark.parametrize("index", [True, False])\ndef test_index(index):\n # GH 32667\n\n df = pd.DataFrame([1, 2, 3])\n\n result = df.to_markdown(index=index)\n\n if index:\n expected = (\n "| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"\n )\n else:\n expected = "| 0 |\n|----:|\n| 1 |\n| 2 |\n| 3 |"\n assert result == expected\n\n\ndef test_showindex_disallowed_in_kwargs():\n # GH 32667; disallowing showindex in kwargs enforced in 2.0\n df = pd.DataFrame([1, 2, 3])\n with pytest.raises(ValueError, match="Pass 'index' instead of 'showindex"):\n df.to_markdown(index=True, showindex=True)\n\n\ndef test_markdown_pos_args_deprecatation():\n # GH-54229\n df = pd.DataFrame({"a": [1, 2, 3]})\n msg = (\n r"Starting with pandas version 3.0 all arguments of to_markdown except for the "\n r"argument 'buf' will be keyword-only."\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n buffer = BytesIO()\n df.to_markdown(buffer, "grid")\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_to_markdown.py
test_to_markdown.py
Python
2,757
0.95
0.103774
0.036585
node-utils
484
2025-02-24T12:45:16.151569
GPL-3.0
true
59f55e5bb561c1b23a0815f639b8dd71
from datetime import (\n datetime,\n timedelta,\n)\nfrom io import StringIO\nimport re\nimport sys\nfrom textwrap import dedent\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nfrom pandas import (\n CategoricalIndex,\n DataFrame,\n Index,\n NaT,\n Series,\n Timestamp,\n concat,\n date_range,\n get_option,\n option_context,\n read_csv,\n timedelta_range,\n to_datetime,\n)\nimport pandas._testing as tm\n\n\ndef _three_digit_exp():\n return f"{1.7e8:.4g}" == "1.7e+008"\n\n\nclass TestDataFrameToStringFormatters:\n def test_to_string_masked_ea_with_formatter(self):\n # GH#39336\n df = DataFrame(\n {\n "a": Series([0.123456789, 1.123456789], dtype="Float64"),\n "b": Series([1, 2], dtype="Int64"),\n }\n )\n result = df.to_string(formatters=["{:.2f}".format, "{:.2f}".format])\n expected = dedent(\n """\\n a b\n 0 0.12 1.00\n 1 1.12 2.00"""\n )\n assert result == expected\n\n def test_to_string_with_formatters(self):\n df = DataFrame(\n {\n "int": [1, 2, 3],\n "float": [1.0, 2.0, 3.0],\n "object": [(1, 2), True, False],\n },\n columns=["int", "float", "object"],\n )\n\n formatters = [\n ("int", lambda x: f"0x{x:x}"),\n ("float", lambda x: f"[{x: 4.1f}]"),\n ("object", lambda x: f"-{x!s}-"),\n ]\n result = df.to_string(formatters=dict(formatters))\n result2 = df.to_string(formatters=list(zip(*formatters))[1])\n assert result == (\n " int float object\n"\n "0 0x1 [ 1.0] -(1, 2)-\n"\n "1 0x2 [ 2.0] -True-\n"\n "2 0x3 [ 3.0] -False-"\n )\n assert result == result2\n\n def test_to_string_with_datetime64_monthformatter(self):\n months = [datetime(2016, 1, 1), datetime(2016, 2, 2)]\n x = DataFrame({"months": months})\n\n def format_func(x):\n return x.strftime("%Y-%m")\n\n result = x.to_string(formatters={"months": format_func})\n expected = dedent(\n """\\n months\n 0 2016-01\n 1 2016-02"""\n )\n assert result.strip() == expected\n\n def test_to_string_with_datetime64_hourformatter(self):\n x = DataFrame(\n {"hod": to_datetime(["10:10:10.100", "12:12:12.120"], format="%H:%M:%S.%f")}\n )\n\n def format_func(x):\n return x.strftime("%H:%M")\n\n result = x.to_string(formatters={"hod": format_func})\n expected = dedent(\n """\\n hod\n 0 10:10\n 1 12:12"""\n )\n assert result.strip() == expected\n\n def test_to_string_with_formatters_unicode(self):\n df = DataFrame({"c/\u03c3": [1, 2, 3]})\n result = df.to_string(formatters={"c/\u03c3": str})\n expected = dedent(\n """\\n c/\u03c3\n 0 1\n 1 2\n 2 3"""\n )\n assert result == expected\n\n def test_to_string_index_formatter(self):\n df = DataFrame([range(5), range(5, 10), range(10, 15)])\n\n rs = df.to_string(formatters={"__index__": lambda x: "abc"[x]})\n\n xp = dedent(\n """\\n 0 1 2 3 4\n a 0 1 2 3 4\n b 5 6 7 8 9\n c 10 11 12 13 14\\n """\n )\n assert rs == xp\n\n def test_no_extra_space(self):\n # GH#52690: Check that no extra space is given\n col1 = "TEST"\n col2 = "PANDAS"\n col3 = "to_string"\n expected = f"{col1:<6s} {col2:<7s} {col3:<10s}"\n df = DataFrame([{"col1": "TEST", "col2": "PANDAS", "col3": "to_string"}])\n d = {"col1": "{:<6s}".format, "col2": "{:<7s}".format, "col3": "{:<10s}".format}\n result = df.to_string(index=False, header=False, formatters=d)\n assert result == expected\n\n\nclass TestDataFrameToStringColSpace:\n def test_to_string_with_column_specific_col_space_raises(self):\n df = DataFrame(\n np.random.default_rng(2).random(size=(3, 3)), columns=["a", "b", "c"]\n )\n\n msg = (\n "Col_space length\\(\\d+\\) should match "\n "DataFrame number of columns\\(\\d+\\)"\n )\n with pytest.raises(ValueError, match=msg):\n df.to_string(col_space=[30, 40])\n\n with pytest.raises(ValueError, match=msg):\n df.to_string(col_space=[30, 40, 50, 60])\n\n msg = "unknown column"\n with pytest.raises(ValueError, match=msg):\n df.to_string(col_space={"a": "foo", "b": 23, "d": 34})\n\n def test_to_string_with_column_specific_col_space(self):\n df = DataFrame(\n np.random.default_rng(2).random(size=(3, 3)), columns=["a", "b", "c"]\n )\n\n result = df.to_string(col_space={"a": 10, "b": 11, "c": 12})\n # 3 separating space + each col_space for (id, a, b, c)\n assert len(result.split("\n")[1]) == (3 + 1 + 10 + 11 + 12)\n\n result = df.to_string(col_space=[10, 11, 12])\n assert len(result.split("\n")[1]) == (3 + 1 + 10 + 11 + 12)\n\n def test_to_string_with_col_space(self):\n df = DataFrame(np.random.default_rng(2).random(size=(1, 3)))\n c10 = len(df.to_string(col_space=10).split("\n")[1])\n c20 = len(df.to_string(col_space=20).split("\n")[1])\n c30 = len(df.to_string(col_space=30).split("\n")[1])\n assert c10 < c20 < c30\n\n # GH#8230\n # col_space wasn't being applied with header=False\n with_header = df.to_string(col_space=20)\n with_header_row1 = with_header.splitlines()[1]\n no_header = df.to_string(col_space=20, header=False)\n assert len(with_header_row1) == len(no_header)\n\n def test_to_string_repr_tuples(self):\n buf = StringIO()\n\n df = DataFrame({"tups": list(zip(range(10), range(10)))})\n repr(df)\n df.to_string(col_space=10, buf=buf)\n\n\nclass TestDataFrameToStringHeader:\n def test_to_string_header_false(self):\n # GH#49230\n df = DataFrame([1, 2])\n df.index.name = "a"\n s = df.to_string(header=False)\n expected = "a \n0 1\n1 2"\n assert s == expected\n\n df = DataFrame([[1, 2], [3, 4]])\n df.index.name = "a"\n s = df.to_string(header=False)\n expected = "a \n0 1 2\n1 3 4"\n assert s == expected\n\n def test_to_string_multindex_header(self):\n # GH#16718\n df = DataFrame({"a": [0], "b": [1], "c": [2], "d": [3]}).set_index(["a", "b"])\n res = df.to_string(header=["r1", "r2"])\n exp = " r1 r2\na b \n0 1 2 3"\n assert res == exp\n\n def test_to_string_no_header(self):\n df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})\n\n df_s = df.to_string(header=False)\n expected = "0 1 4\n1 2 5\n2 3 6"\n\n assert df_s == expected\n\n def test_to_string_specified_header(self):\n df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})\n\n df_s = df.to_string(header=["X", "Y"])\n expected = " X Y\n0 1 4\n1 2 5\n2 3 6"\n\n assert df_s == expected\n\n msg = "Writing 2 cols but got 1 aliases"\n with pytest.raises(ValueError, match=msg):\n df.to_string(header=["X"])\n\n\nclass TestDataFrameToStringLineWidth:\n def test_to_string_line_width(self):\n df = DataFrame(123, index=range(10, 15), columns=range(30))\n lines = df.to_string(line_width=80)\n assert max(len(line) for line in lines.split("\n")) == 80\n\n def test_to_string_line_width_no_index(self):\n # GH#13998, GH#22505\n df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})\n\n df_s = df.to_string(line_width=1, index=False)\n expected = " x \\\n 1 \n 2 \n 3 \n\n y \n 4 \n 5 \n 6 "\n\n assert df_s == expected\n\n df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})\n\n df_s = df.to_string(line_width=1, index=False)\n expected = " x \\\n11 \n22 \n33 \n\n y \n 4 \n 5 \n 6 "\n\n assert df_s == expected\n\n df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})\n\n df_s = df.to_string(line_width=1, index=False)\n expected = " x \\\n 11 \n 22 \n-33 \n\n y \n 4 \n 5 \n-6 "\n\n assert df_s == expected\n\n def test_to_string_line_width_no_header(self):\n # GH#53054\n df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})\n\n df_s = df.to_string(line_width=1, header=False)\n expected = "0 1 \\\n1 2 \n2 3 \n\n0 4 \n1 5 \n2 6 "\n\n assert df_s == expected\n\n df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})\n\n df_s = df.to_string(line_width=1, header=False)\n expected = "0 11 \\\n1 22 \n2 33 \n\n0 4 \n1 5 \n2 6 "\n\n assert df_s == expected\n\n df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})\n\n df_s = df.to_string(line_width=1, header=False)\n expected = "0 11 \\\n1 22 \n2 -33 \n\n0 4 \n1 5 \n2 -6 "\n\n assert df_s == expected\n\n def test_to_string_line_width_with_both_index_and_header(self):\n # GH#53054\n df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})\n\n df_s = df.to_string(line_width=1)\n expected = (\n " x \\\n0 1 \n1 2 \n2 3 \n\n y \n0 4 \n1 5 \n2 6 "\n )\n\n assert df_s == expected\n\n df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})\n\n df_s = df.to_string(line_width=1)\n expected = (\n " x \\\n0 11 \n1 22 \n2 33 \n\n y \n0 4 \n1 5 \n2 6 "\n )\n\n assert df_s == expected\n\n df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})\n\n df_s = df.to_string(line_width=1)\n expected = (\n " x \\\n0 11 \n1 22 \n2 -33 \n\n y \n0 4 \n1 5 \n2 -6 "\n )\n\n assert df_s == expected\n\n def test_to_string_line_width_no_index_no_header(self):\n # GH#53054\n df = DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})\n\n df_s = df.to_string(line_width=1, index=False, header=False)\n expected = "1 \\\n2 \n3 \n\n4 \n5 \n6 "\n\n assert df_s == expected\n\n df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]})\n\n df_s = df.to_string(line_width=1, index=False, header=False)\n expected = "11 \\\n22 \n33 \n\n4 \n5 \n6 "\n\n assert df_s == expected\n\n df = DataFrame({"x": [11, 22, -33], "y": [4, 5, -6]})\n\n df_s = df.to_string(line_width=1, index=False, header=False)\n expected = " 11 \\\n 22 \n-33 \n\n 4 \n 5 \n-6 "\n\n assert df_s == expected\n\n\nclass TestToStringNumericFormatting:\n def test_to_string_float_format_no_fixed_width(self):\n # GH#21625\n df = DataFrame({"x": [0.19999]})\n expected = " x\n0 0.200"\n assert df.to_string(float_format="%.3f") == expected\n\n # GH#22270\n df = DataFrame({"x": [100.0]})\n expected = " x\n0 100"\n assert df.to_string(float_format="%.0f") == expected\n\n def test_to_string_small_float_values(self):\n df = DataFrame({"a": [1.5, 1e-17, -5.5e-7]})\n\n result = df.to_string()\n # sadness per above\n if _three_digit_exp():\n expected = (\n " a\n"\n "0 1.500000e+000\n"\n "1 1.000000e-017\n"\n "2 -5.500000e-007"\n )\n else:\n expected = (\n " a\n"\n "0 1.500000e+00\n"\n "1 1.000000e-17\n"\n "2 -5.500000e-07"\n )\n assert result == expected\n\n # but not all exactly zero\n df = df * 0\n result = df.to_string()\n expected = " 0\n0 0\n1 0\n2 -0"\n # TODO: assert that these match??\n\n def test_to_string_complex_float_formatting(self):\n # GH #25514, 25745\n with option_context("display.precision", 5):\n df = DataFrame(\n {\n "x": [\n (0.4467846931321966 + 0.0715185102060818j),\n (0.2739442392974528 + 0.23515228785438969j),\n (0.26974928742135185 + 0.3250604054898979j),\n (-1j),\n ]\n }\n )\n result = df.to_string()\n expected = (\n " x\n0 0.44678+0.07152j\n"\n "1 0.27394+0.23515j\n"\n "2 0.26975+0.32506j\n"\n "3 -0.00000-1.00000j"\n )\n assert result == expected\n\n def test_to_string_format_inf(self):\n # GH#24861\n df = DataFrame(\n {\n "A": [-np.inf, np.inf, -1, -2.1234, 3, 4],\n "B": [-np.inf, np.inf, "foo", "foooo", "fooooo", "bar"],\n }\n )\n result = df.to_string()\n\n expected = (\n " A B\n"\n "0 -inf -inf\n"\n "1 inf inf\n"\n "2 -1.0000 foo\n"\n "3 -2.1234 foooo\n"\n "4 3.0000 fooooo\n"\n "5 4.0000 bar"\n )\n assert result == expected\n\n df = DataFrame(\n {\n "A": [-np.inf, np.inf, -1.0, -2.0, 3.0, 4.0],\n "B": [-np.inf, np.inf, "foo", "foooo", "fooooo", "bar"],\n }\n )\n result = df.to_string()\n\n expected = (\n " A B\n"\n "0 -inf -inf\n"\n "1 inf inf\n"\n "2 -1.0 foo\n"\n "3 -2.0 foooo\n"\n "4 3.0 fooooo\n"\n "5 4.0 bar"\n )\n assert result == expected\n\n def test_to_string_int_formatting(self):\n df = DataFrame({"x": [-15, 20, 25, -35]})\n assert issubclass(df["x"].dtype.type, np.integer)\n\n output = df.to_string()\n expected = " x\n0 -15\n1 20\n2 25\n3 -35"\n assert output == expected\n\n def test_to_string_float_formatting(self):\n with option_context(\n "display.precision",\n 5,\n "display.notebook_repr_html",\n False,\n ):\n df = DataFrame(\n {"x": [0, 0.25, 3456.000, 12e45, 1.64e6, 1.7e8, 1.253456, np.pi, -1e6]}\n )\n\n df_s = df.to_string()\n\n if _three_digit_exp():\n expected = (\n " x\n0 0.00000e+000\n1 2.50000e-001\n"\n "2 3.45600e+003\n3 1.20000e+046\n4 1.64000e+006\n"\n "5 1.70000e+008\n6 1.25346e+000\n7 3.14159e+000\n"\n "8 -1.00000e+006"\n )\n else:\n expected = (\n " x\n0 0.00000e+00\n1 2.50000e-01\n"\n "2 3.45600e+03\n3 1.20000e+46\n4 1.64000e+06\n"\n "5 1.70000e+08\n6 1.25346e+00\n7 3.14159e+00\n"\n "8 -1.00000e+06"\n )\n assert df_s == expected\n\n df = DataFrame({"x": [3234, 0.253]})\n df_s = df.to_string()\n\n expected = " x\n0 3234.000\n1 0.253"\n assert df_s == expected\n\n assert get_option("display.precision") == 6\n\n df = DataFrame({"x": [1e9, 0.2512]})\n df_s = df.to_string()\n\n if _three_digit_exp():\n expected = " x\n0 1.000000e+009\n1 2.512000e-001"\n else:\n expected = " x\n0 1.000000e+09\n1 2.512000e-01"\n assert df_s == expected\n\n\nclass TestDataFrameToString:\n def test_to_string_decimal(self):\n # GH#23614\n df = DataFrame({"A": [6.0, 3.1, 2.2]})\n expected = " A\n0 6,0\n1 3,1\n2 2,2"\n assert df.to_string(decimal=",") == expected\n\n def test_to_string_left_justify_cols(self):\n df = DataFrame({"x": [3234, 0.253]})\n df_s = df.to_string(justify="left")\n expected = " x \n0 3234.000\n1 0.253"\n assert df_s == expected\n\n def test_to_string_format_na(self):\n df = DataFrame(\n {\n "A": [np.nan, -1, -2.1234, 3, 4],\n "B": [np.nan, "foo", "foooo", "fooooo", "bar"],\n }\n )\n result = df.to_string()\n\n expected = (\n " A B\n"\n "0 NaN NaN\n"\n "1 -1.0000 foo\n"\n "2 -2.1234 foooo\n"\n "3 3.0000 fooooo\n"\n "4 4.0000 bar"\n )\n assert result == expected\n\n df = DataFrame(\n {\n "A": [np.nan, -1.0, -2.0, 3.0, 4.0],\n "B": [np.nan, "foo", "foooo", "fooooo", "bar"],\n }\n )\n result = df.to_string()\n\n expected = (\n " A B\n"\n "0 NaN NaN\n"\n "1 -1.0 foo\n"\n "2 -2.0 foooo\n"\n "3 3.0 fooooo\n"\n "4 4.0 bar"\n )\n assert result == expected\n\n def test_to_string_with_dict_entries(self):\n df = DataFrame({"A": [{"a": 1, "b": 2}]})\n\n val = df.to_string()\n assert "'a': 1" in val\n assert "'b': 2" in val\n\n def test_to_string_with_categorical_columns(self):\n # GH#35439\n data = [[4, 2], [3, 2], [4, 3]]\n cols = ["aaaaaaaaa", "b"]\n df = DataFrame(data, columns=cols)\n df_cat_cols = DataFrame(data, columns=CategoricalIndex(cols))\n\n assert df.to_string() == df_cat_cols.to_string()\n\n def test_repr_embedded_ndarray(self):\n arr = np.empty(10, dtype=[("err", object)])\n for i in range(len(arr)):\n arr["err"][i] = np.random.default_rng(2).standard_normal(i)\n\n df = DataFrame(arr)\n repr(df["err"])\n repr(df)\n df.to_string()\n\n def test_to_string_truncate(self):\n # GH 9784 - dont truncate when calling DataFrame.to_string\n df = DataFrame(\n [\n {\n "a": "foo",\n "b": "bar",\n "c": "let's make this a very VERY long line that is longer "\n "than the default 50 character limit",\n "d": 1,\n },\n {"a": "foo", "b": "bar", "c": "stuff", "d": 1},\n ]\n )\n df.set_index(["a", "b", "c"])\n assert df.to_string() == (\n " a b "\n " c d\n"\n "0 foo bar let's make this a very VERY long line t"\n "hat is longer than the default 50 character limit 1\n"\n "1 foo bar "\n " stuff 1"\n )\n with option_context("max_colwidth", 20):\n # the display option has no effect on the to_string method\n assert df.to_string() == (\n " a b "\n " c d\n"\n "0 foo bar let's make this a very VERY long line t"\n "hat is longer than the default 50 character limit 1\n"\n "1 foo bar "\n " stuff 1"\n )\n assert df.to_string(max_colwidth=20) == (\n " a b c d\n"\n "0 foo bar let's make this ... 1\n"\n "1 foo bar stuff 1"\n )\n\n @pytest.mark.parametrize(\n "input_array, expected",\n [\n ({"A": ["a"]}, "A\na"),\n ({"A": ["a", "b"], "B": ["c", "dd"]}, "A B\na c\nb dd"),\n ({"A": ["a", 1], "B": ["aa", 1]}, "A B\na aa\n1 1"),\n ],\n )\n def test_format_remove_leading_space_dataframe(self, input_array, expected):\n # GH#24980\n df = DataFrame(input_array).to_string(index=False)\n assert df == expected\n\n @pytest.mark.parametrize(\n "data,expected",\n [\n (\n {"col1": [1, 2], "col2": [3, 4]},\n " col1 col2\n0 1 3\n1 2 4",\n ),\n (\n {"col1": ["Abc", 0.756], "col2": [np.nan, 4.5435]},\n " col1 col2\n0 Abc NaN\n1 0.756 4.5435",\n ),\n (\n {"col1": [np.nan, "a"], "col2": [0.009, 3.543], "col3": ["Abc", 23]},\n " col1 col2 col3\n0 NaN 0.009 Abc\n1 a 3.543 23",\n ),\n ],\n )\n def test_to_string_max_rows_zero(self, data, expected):\n # GH#35394\n result = DataFrame(data=data).to_string(max_rows=0)\n assert result == expected\n\n @pytest.mark.parametrize(\n "max_cols, max_rows, expected",\n [\n (\n 10,\n None,\n " 0 1 2 3 4 ... 6 7 8 9 10\n"\n " 0 0 0 0 0 ... 0 0 0 0 0\n"\n " 0 0 0 0 0 ... 0 0 0 0 0\n"\n " 0 0 0 0 0 ... 0 0 0 0 0\n"\n " 0 0 0 0 0 ... 0 0 0 0 0",\n ),\n (\n None,\n 2,\n " 0 1 2 3 4 5 6 7 8 9 10\n"\n " 0 0 0 0 0 0 0 0 0 0 0\n"\n " .. .. .. .. .. .. .. .. .. .. ..\n"\n " 0 0 0 0 0 0 0 0 0 0 0",\n ),\n (\n 10,\n 2,\n " 0 1 2 3 4 ... 6 7 8 9 10\n"\n " 0 0 0 0 0 ... 0 0 0 0 0\n"\n " .. .. .. .. .. ... .. .. .. .. ..\n"\n " 0 0 0 0 0 ... 0 0 0 0 0",\n ),\n (\n 9,\n 2,\n " 0 1 2 3 ... 7 8 9 10\n"\n " 0 0 0 0 ... 0 0 0 0\n"\n " .. .. .. .. ... .. .. .. ..\n"\n " 0 0 0 0 ... 0 0 0 0",\n ),\n (\n 1,\n 1,\n " 0 ...\n 0 ...\n.. ...",\n ),\n ],\n )\n def test_truncation_no_index(self, max_cols, max_rows, expected):\n df = DataFrame([[0] * 11] * 4)\n assert (\n df.to_string(index=False, max_cols=max_cols, max_rows=max_rows) == expected\n )\n\n def test_to_string_no_index(self):\n # GH#16839, GH#13032\n df = DataFrame({"x": [11, 22], "y": [33, -44], "z": ["AAA", " "]})\n\n df_s = df.to_string(index=False)\n # Leading space is expected for positive numbers.\n expected = " x y z\n11 33 AAA\n22 -44 "\n assert df_s == expected\n\n df_s = df[["y", "x", "z"]].to_string(index=False)\n expected = " y x z\n 33 11 AAA\n-44 22 "\n assert df_s == expected\n\n def test_to_string_unicode_columns(self, float_frame):\n df = DataFrame({"\u03c3": np.arange(10.0)})\n\n buf = StringIO()\n df.to_string(buf=buf)\n buf.getvalue()\n\n buf = StringIO()\n df.info(buf=buf)\n buf.getvalue()\n\n result = float_frame.to_string()\n assert isinstance(result, str)\n\n @pytest.mark.parametrize("na_rep", ["NaN", "Ted"])\n def test_to_string_na_rep_and_float_format(self, na_rep):\n # GH#13828\n df = DataFrame([["A", 1.2225], ["A", None]], columns=["Group", "Data"])\n result = df.to_string(na_rep=na_rep, float_format="{:.2f}".format)\n expected = dedent(\n f"""\\n Group Data\n 0 A 1.22\n 1 A {na_rep}"""\n )\n assert result == expected\n\n def test_to_string_string_dtype(self):\n # GH#50099\n pytest.importorskip("pyarrow")\n df = DataFrame(\n {"x": ["foo", "bar", "baz"], "y": ["a", "b", "c"], "z": [1, 2, 3]}\n )\n df = df.astype(\n {"x": "string[pyarrow]", "y": "string[python]", "z": "int64[pyarrow]"}\n )\n result = df.dtypes.to_string()\n expected = dedent(\n """\\n x string[pyarrow]\n y string[python]\n z int64[pyarrow]"""\n )\n assert result == expected\n\n def test_to_string_pos_args_deprecation(self):\n # GH#54229\n df = DataFrame({"a": [1, 2, 3]})\n msg = (\n "Starting with pandas version 3.0 all arguments of to_string "\n "except for the "\n "argument 'buf' will be keyword-only."\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n buf = StringIO()\n df.to_string(buf, None, None, True, True)\n\n def test_to_string_utf8_columns(self):\n n = "\u05d0".encode()\n df = DataFrame([1, 2], columns=[n])\n\n with option_context("display.max_rows", 1):\n repr(df)\n\n def test_to_string_unicode_two(self):\n dm = DataFrame({"c/\u03c3": []})\n buf = StringIO()\n dm.to_string(buf)\n\n def test_to_string_unicode_three(self):\n dm = DataFrame(["\xc2"])\n buf = StringIO()\n dm.to_string(buf)\n\n def test_to_string_with_float_index(self):\n index = Index([1.5, 2, 3, 4, 5])\n df = DataFrame(np.arange(5), index=index)\n\n result = df.to_string()\n expected = " 0\n1.5 0\n2.0 1\n3.0 2\n4.0 3\n5.0 4"\n assert result == expected\n\n def test_to_string(self):\n # big mixed\n biggie = DataFrame(\n {\n "A": np.random.default_rng(2).standard_normal(200),\n "B": Index([f"{i}?!" for i in range(200)]),\n },\n )\n\n biggie.loc[:20, "A"] = np.nan\n biggie.loc[:20, "B"] = np.nan\n s = biggie.to_string()\n\n buf = StringIO()\n retval = biggie.to_string(buf=buf)\n assert retval is None\n assert buf.getvalue() == s\n\n assert isinstance(s, str)\n\n # print in right order\n result = biggie.to_string(\n columns=["B", "A"], col_space=17, float_format="%.5f".__mod__\n )\n lines = result.split("\n")\n header = lines[0].strip().split()\n joined = "\n".join([re.sub(r"\s+", " ", x).strip() for x in lines[1:]])\n recons = read_csv(StringIO(joined), names=header, header=None, sep=" ")\n tm.assert_series_equal(recons["B"], biggie["B"])\n assert recons["A"].count() == biggie["A"].count()\n assert (np.abs(recons["A"].dropna() - biggie["A"].dropna()) < 0.1).all()\n\n # FIXME: don't leave commented-out\n # expected = ['B', 'A']\n # assert header == expected\n\n result = biggie.to_string(columns=["A"], col_space=17)\n header = result.split("\n")[0].strip().split()\n expected = ["A"]\n assert header == expected\n\n biggie.to_string(columns=["B", "A"], formatters={"A": lambda x: f"{x:.1f}"})\n\n biggie.to_string(columns=["B", "A"], float_format=str)\n biggie.to_string(columns=["B", "A"], col_space=12, float_format=str)\n\n frame = DataFrame(index=np.arange(200))\n frame.to_string()\n\n # TODO: split or simplify this test?\n @pytest.mark.xfail(using_string_dtype(), reason="fix when arrow is default")\n def test_to_string_index_with_nan(self):\n # GH#2850\n df = DataFrame(\n {\n "id1": {0: "1a3", 1: "9h4"},\n "id2": {0: np.nan, 1: "d67"},\n "id3": {0: "78d", 1: "79d"},\n "value": {0: 123, 1: 64},\n }\n )\n\n # multi-index\n y = df.set_index(["id1", "id2", "id3"])\n result = y.to_string()\n expected = (\n " value\nid1 id2 id3 \n"\n "1a3 NaN 78d 123\n9h4 d67 79d 64"\n )\n assert result == expected\n\n # index\n y = df.set_index("id2")\n result = y.to_string()\n expected = (\n " id1 id3 value\nid2 \n"\n "NaN 1a3 78d 123\nd67 9h4 79d 64"\n )\n assert result == expected\n\n # with append (this failed in 0.12)\n y = df.set_index(["id1", "id2"]).set_index("id3", append=True)\n result = y.to_string()\n expected = (\n " value\nid1 id2 id3 \n"\n "1a3 NaN 78d 123\n9h4 d67 79d 64"\n )\n assert result == expected\n\n # all-nan in mi\n df2 = df.copy()\n df2.loc[:, "id2"] = np.nan\n y = df2.set_index("id2")\n result = y.to_string()\n expected = (\n " id1 id3 value\nid2 \n"\n "NaN 1a3 78d 123\nNaN 9h4 79d 64"\n )\n assert result == expected\n\n # partial nan in mi\n df2 = df.copy()\n df2.loc[:, "id2"] = np.nan\n y = df2.set_index(["id2", "id3"])\n result = y.to_string()\n expected = (\n " id1 value\nid2 id3 \n"\n "NaN 78d 1a3 123\n 79d 9h4 64"\n )\n assert result == expected\n\n df = DataFrame(\n {\n "id1": {0: np.nan, 1: "9h4"},\n "id2": {0: np.nan, 1: "d67"},\n "id3": {0: np.nan, 1: "79d"},\n "value": {0: 123, 1: 64},\n }\n )\n\n y = df.set_index(["id1", "id2", "id3"])\n result = y.to_string()\n expected = (\n " value\nid1 id2 id3 \n"\n "NaN NaN NaN 123\n9h4 d67 79d 64"\n )\n assert result == expected\n\n def test_to_string_nonunicode_nonascii_alignment(self):\n df = DataFrame([["aa\xc3\xa4\xc3\xa4", 1], ["bbbb", 2]])\n rep_str = df.to_string()\n lines = rep_str.split("\n")\n assert len(lines[1]) == len(lines[2])\n\n def test_unicode_problem_decoding_as_ascii(self):\n df = DataFrame({"c/\u03c3": Series({"test": np.nan})})\n str(df.to_string())\n\n def test_to_string_repr_unicode(self):\n buf = StringIO()\n\n unicode_values = ["\u03c3"] * 10\n unicode_values = np.array(unicode_values, dtype=object)\n df = DataFrame({"unicode": unicode_values})\n df.to_string(col_space=10, buf=buf)\n\n # it works!\n repr(df)\n # it works even if sys.stdin in None\n _stdin = sys.stdin\n try:\n sys.stdin = None\n repr(df)\n finally:\n sys.stdin = _stdin\n\n\nclass TestSeriesToString:\n def test_to_string_without_index(self):\n # GH#11729 Test index=False option\n ser = Series([1, 2, 3, 4])\n result = ser.to_string(index=False)\n expected = "\n".join(["1", "2", "3", "4"])\n assert result == expected\n\n def test_to_string_name(self):\n ser = Series(range(100), dtype="int64")\n ser.name = "myser"\n res = ser.to_string(max_rows=2, name=True)\n exp = "0 0\n ..\n99 99\nName: myser"\n assert res == exp\n res = ser.to_string(max_rows=2, name=False)\n exp = "0 0\n ..\n99 99"\n assert res == exp\n\n def test_to_string_dtype(self):\n ser = Series(range(100), dtype="int64")\n res = ser.to_string(max_rows=2, dtype=True)\n exp = "0 0\n ..\n99 99\ndtype: int64"\n assert res == exp\n res = ser.to_string(max_rows=2, dtype=False)\n exp = "0 0\n ..\n99 99"\n assert res == exp\n\n def test_to_string_length(self):\n ser = Series(range(100), dtype="int64")\n res = ser.to_string(max_rows=2, length=True)\n exp = "0 0\n ..\n99 99\nLength: 100"\n assert res == exp\n\n def test_to_string_na_rep(self):\n ser = Series(index=range(100), dtype=np.float64)\n res = ser.to_string(na_rep="foo", max_rows=2)\n exp = "0 foo\n ..\n99 foo"\n assert res == exp\n\n def test_to_string_float_format(self):\n ser = Series(range(10), dtype="float64")\n res = ser.to_string(float_format=lambda x: f"{x:2.1f}", max_rows=2)\n exp = "0 0.0\n ..\n9 9.0"\n assert res == exp\n\n def test_to_string_header(self):\n ser = Series(range(10), dtype="int64")\n ser.index.name = "foo"\n res = ser.to_string(header=True, max_rows=2)\n exp = "foo\n0 0\n ..\n9 9"\n assert res == exp\n res = ser.to_string(header=False, max_rows=2)\n exp = "0 0\n ..\n9 9"\n assert res == exp\n\n def test_to_string_empty_col(self):\n # GH#13653\n ser = Series(["", "Hello", "World", "", "", "Mooooo", "", ""])\n res = ser.to_string(index=False)\n exp = " \n Hello\n World\n \n \nMooooo\n \n "\n assert re.match(exp, res)\n\n def test_to_string_timedelta64(self):\n Series(np.array([1100, 20], dtype="timedelta64[ns]")).to_string()\n\n ser = Series(date_range("2012-1-1", periods=3, freq="D"))\n\n # GH#2146\n\n # adding NaTs\n y = ser - ser.shift(1)\n result = y.to_string()\n assert "1 days" in result\n assert "00:00:00" not in result\n assert "NaT" in result\n\n # with frac seconds\n o = Series([datetime(2012, 1, 1, microsecond=150)] * 3)\n y = ser - o\n result = y.to_string()\n assert "-1 days +23:59:59.999850" in result\n\n # rounding?\n o = Series([datetime(2012, 1, 1, 1)] * 3)\n y = ser - o\n result = y.to_string()\n assert "-1 days +23:00:00" in result\n assert "1 days 23:00:00" in result\n\n o = Series([datetime(2012, 1, 1, 1, 1)] * 3)\n y = ser - o\n result = y.to_string()\n assert "-1 days +22:59:00" in result\n assert "1 days 22:59:00" in result\n\n o = Series([datetime(2012, 1, 1, 1, 1, microsecond=150)] * 3)\n y = ser - o\n result = y.to_string()\n assert "-1 days +22:58:59.999850" in result\n assert "0 days 22:58:59.999850" in result\n\n # neg time\n td = timedelta(minutes=5, seconds=3)\n s2 = Series(date_range("2012-1-1", periods=3, freq="D")) + td\n y = ser - s2\n result = y.to_string()\n assert "-1 days +23:54:57" in result\n\n td = timedelta(microseconds=550)\n s2 = Series(date_range("2012-1-1", periods=3, freq="D")) + td\n y = ser - td\n result = y.to_string()\n assert "2012-01-01 23:59:59.999450" in result\n\n # no boxing of the actual elements\n td = Series(timedelta_range("1 days", periods=3))\n result = td.to_string()\n assert result == "0 1 days\n1 2 days\n2 3 days"\n\n def test_to_string(self):\n ts = Series(\n np.arange(10, dtype=np.float64),\n index=date_range("2020-01-01", periods=10, freq="B"),\n )\n buf = StringIO()\n\n s = ts.to_string()\n\n retval = ts.to_string(buf=buf)\n assert retval is None\n assert buf.getvalue().strip() == s\n\n # pass float_format\n format = "%.4f".__mod__\n result = ts.to_string(float_format=format)\n result = [x.split()[1] for x in result.split("\n")[:-1]]\n expected = [format(x) for x in ts]\n assert result == expected\n\n # empty string\n result = ts[:0].to_string()\n assert result == "Series([], Freq: B)"\n\n result = ts[:0].to_string(length=0)\n assert result == "Series([], Freq: B)"\n\n # name and length\n cp = ts.copy()\n cp.name = "foo"\n result = cp.to_string(length=True, name=True, dtype=True)\n last_line = result.split("\n")[-1].strip()\n assert last_line == (f"Freq: B, Name: foo, Length: {len(cp)}, dtype: float64")\n\n @pytest.mark.parametrize(\n "input_array, expected",\n [\n ("a", "a"),\n (["a", "b"], "a\nb"),\n ([1, "a"], "1\na"),\n (1, "1"),\n ([0, -1], " 0\n-1"),\n (1.0, "1.0"),\n ([" a", " b"], " a\n b"),\n ([".1", "1"], ".1\n 1"),\n (["10", "-10"], " 10\n-10"),\n ],\n )\n def test_format_remove_leading_space_series(self, input_array, expected):\n # GH: 24980\n ser = Series(input_array)\n result = ser.to_string(index=False)\n assert result == expected\n\n def test_to_string_complex_number_trims_zeros(self):\n ser = Series([1.000000 + 1.000000j, 1.0 + 1.0j, 1.05 + 1.0j])\n result = ser.to_string()\n expected = dedent(\n """\\n 0 1.00+1.00j\n 1 1.00+1.00j\n 2 1.05+1.00j"""\n )\n assert result == expected\n\n def test_nullable_float_to_string(self, float_ea_dtype):\n # https://github.com/pandas-dev/pandas/issues/36775\n dtype = float_ea_dtype\n ser = Series([0.0, 1.0, None], dtype=dtype)\n result = ser.to_string()\n expected = dedent(\n """\\n 0 0.0\n 1 1.0\n 2 <NA>"""\n )\n assert result == expected\n\n def test_nullable_int_to_string(self, any_int_ea_dtype):\n # https://github.com/pandas-dev/pandas/issues/36775\n dtype = any_int_ea_dtype\n ser = Series([0, 1, None], dtype=dtype)\n result = ser.to_string()\n expected = dedent(\n """\\n 0 0\n 1 1\n 2 <NA>"""\n )\n assert result == expected\n\n def test_to_string_mixed(self):\n ser = Series(["foo", np.nan, -1.23, 4.56])\n result = ser.to_string()\n expected = "".join(["0 foo\n", "1 NaN\n", "2 -1.23\n", "3 4.56"])\n assert result == expected\n\n # but don't count NAs as floats\n ser = Series(["foo", np.nan, "bar", "baz"])\n result = ser.to_string()\n expected = "".join(["0 foo\n", "1 NaN\n", "2 bar\n", "3 baz"])\n assert result == expected\n\n ser = Series(["foo", 5, "bar", "baz"])\n result = ser.to_string()\n expected = "".join(["0 foo\n", "1 5\n", "2 bar\n", "3 baz"])\n assert result == expected\n\n def test_to_string_float_na_spacing(self):\n ser = Series([0.0, 1.5678, 2.0, -3.0, 4.0])\n ser[::2] = np.nan\n\n result = ser.to_string()\n expected = (\n "0 NaN\n"\n "1 1.5678\n"\n "2 NaN\n"\n "3 -3.0000\n"\n "4 NaN"\n )\n assert result == expected\n\n def test_to_string_with_datetimeindex(self):\n index = date_range("20130102", periods=6)\n ser = Series(1, index=index)\n result = ser.to_string()\n assert "2013-01-02" in result\n\n # nat in index\n s2 = Series(2, index=[Timestamp("20130111"), NaT])\n ser = concat([s2, ser])\n result = ser.to_string()\n assert "NaT" in result\n\n # nat in summary\n result = str(s2.index)\n assert "NaT" in result\n
.venv\Lib\site-packages\pandas\tests\io\formats\test_to_string.py
test_to_string.py
Python
39,355
0.95
0.074836
0.058881
vue-tools
436
2024-01-09T00:19:55.860093
MIT
true
e2aaa3150b63cecee5982b469df0e85a
import io\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n NA,\n DataFrame,\n read_csv,\n)\n\npytest.importorskip("jinja2")\n\n\ndef bar_grad(a=None, b=None, c=None, d=None):\n """Used in multiple tests to simplify formatting of expected result"""\n ret = [("width", "10em")]\n if all(x is None for x in [a, b, c, d]):\n return ret\n return ret + [\n (\n "background",\n f"linear-gradient(90deg,{','.join([x for x in [a, b, c, d] if x])})",\n )\n ]\n\n\ndef no_bar():\n return bar_grad()\n\n\ndef bar_to(x, color="#d65f5f"):\n return bar_grad(f" {color} {x:.1f}%", f" transparent {x:.1f}%")\n\n\ndef bar_from_to(x, y, color="#d65f5f"):\n return bar_grad(\n f" transparent {x:.1f}%",\n f" {color} {x:.1f}%",\n f" {color} {y:.1f}%",\n f" transparent {y:.1f}%",\n )\n\n\n@pytest.fixture\ndef df_pos():\n return DataFrame([[1], [2], [3]])\n\n\n@pytest.fixture\ndef df_neg():\n return DataFrame([[-1], [-2], [-3]])\n\n\n@pytest.fixture\ndef df_mix():\n return DataFrame([[-3], [1], [2]])\n\n\n@pytest.mark.parametrize(\n "align, exp",\n [\n ("left", [no_bar(), bar_to(50), bar_to(100)]),\n ("right", [bar_to(100), bar_from_to(50, 100), no_bar()]),\n ("mid", [bar_to(33.33), bar_to(66.66), bar_to(100)]),\n ("zero", [bar_from_to(50, 66.7), bar_from_to(50, 83.3), bar_from_to(50, 100)]),\n ("mean", [bar_to(50), no_bar(), bar_from_to(50, 100)]),\n (2.0, [bar_to(50), no_bar(), bar_from_to(50, 100)]),\n (np.median, [bar_to(50), no_bar(), bar_from_to(50, 100)]),\n ],\n)\ndef test_align_positive_cases(df_pos, align, exp):\n # test different align cases for all positive values\n result = df_pos.style.bar(align=align)._compute().ctx\n expected = {(0, 0): exp[0], (1, 0): exp[1], (2, 0): exp[2]}\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "align, exp",\n [\n ("left", [bar_to(100), bar_to(50), no_bar()]),\n ("right", [no_bar(), bar_from_to(50, 100), bar_to(100)]),\n ("mid", [bar_from_to(66.66, 100), bar_from_to(33.33, 100), bar_to(100)]),\n ("zero", [bar_from_to(33.33, 50), bar_from_to(16.66, 50), bar_to(50)]),\n ("mean", [bar_from_to(50, 100), no_bar(), bar_to(50)]),\n (-2.0, [bar_from_to(50, 100), no_bar(), bar_to(50)]),\n (np.median, [bar_from_to(50, 100), no_bar(), bar_to(50)]),\n ],\n)\ndef test_align_negative_cases(df_neg, align, exp):\n # test different align cases for all negative values\n result = df_neg.style.bar(align=align)._compute().ctx\n expected = {(0, 0): exp[0], (1, 0): exp[1], (2, 0): exp[2]}\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "align, exp",\n [\n ("left", [no_bar(), bar_to(80), bar_to(100)]),\n ("right", [bar_to(100), bar_from_to(80, 100), no_bar()]),\n ("mid", [bar_to(60), bar_from_to(60, 80), bar_from_to(60, 100)]),\n ("zero", [bar_to(50), bar_from_to(50, 66.66), bar_from_to(50, 83.33)]),\n ("mean", [bar_to(50), bar_from_to(50, 66.66), bar_from_to(50, 83.33)]),\n (-0.0, [bar_to(50), bar_from_to(50, 66.66), bar_from_to(50, 83.33)]),\n (np.nanmedian, [bar_to(50), no_bar(), bar_from_to(50, 62.5)]),\n ],\n)\n@pytest.mark.parametrize("nans", [True, False])\ndef test_align_mixed_cases(df_mix, align, exp, nans):\n # test different align cases for mixed positive and negative values\n # also test no impact of NaNs and no_bar\n expected = {(0, 0): exp[0], (1, 0): exp[1], (2, 0): exp[2]}\n if nans:\n df_mix.loc[3, :] = np.nan\n expected.update({(3, 0): no_bar()})\n result = df_mix.style.bar(align=align)._compute().ctx\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "align, exp",\n [\n (\n "left",\n {\n "index": [[no_bar(), no_bar()], [bar_to(100), bar_to(100)]],\n "columns": [[no_bar(), bar_to(100)], [no_bar(), bar_to(100)]],\n "none": [[no_bar(), bar_to(33.33)], [bar_to(66.66), bar_to(100)]],\n },\n ),\n (\n "mid",\n {\n "index": [[bar_to(33.33), bar_to(50)], [bar_to(100), bar_to(100)]],\n "columns": [[bar_to(50), bar_to(100)], [bar_to(75), bar_to(100)]],\n "none": [[bar_to(25), bar_to(50)], [bar_to(75), bar_to(100)]],\n },\n ),\n (\n "zero",\n {\n "index": [\n [bar_from_to(50, 66.66), bar_from_to(50, 75)],\n [bar_from_to(50, 100), bar_from_to(50, 100)],\n ],\n "columns": [\n [bar_from_to(50, 75), bar_from_to(50, 100)],\n [bar_from_to(50, 87.5), bar_from_to(50, 100)],\n ],\n "none": [\n [bar_from_to(50, 62.5), bar_from_to(50, 75)],\n [bar_from_to(50, 87.5), bar_from_to(50, 100)],\n ],\n },\n ),\n (\n 2,\n {\n "index": [\n [bar_to(50), no_bar()],\n [bar_from_to(50, 100), bar_from_to(50, 100)],\n ],\n "columns": [\n [bar_to(50), no_bar()],\n [bar_from_to(50, 75), bar_from_to(50, 100)],\n ],\n "none": [\n [bar_from_to(25, 50), no_bar()],\n [bar_from_to(50, 75), bar_from_to(50, 100)],\n ],\n },\n ),\n ],\n)\n@pytest.mark.parametrize("axis", ["index", "columns", "none"])\ndef test_align_axis(align, exp, axis):\n # test all axis combinations with positive values and different aligns\n data = DataFrame([[1, 2], [3, 4]])\n result = (\n data.style.bar(align=align, axis=None if axis == "none" else axis)\n ._compute()\n .ctx\n )\n expected = {\n (0, 0): exp[axis][0][0],\n (0, 1): exp[axis][0][1],\n (1, 0): exp[axis][1][0],\n (1, 1): exp[axis][1][1],\n }\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "values, vmin, vmax",\n [\n ("positive", 1.5, 2.5),\n ("negative", -2.5, -1.5),\n ("mixed", -2.5, 1.5),\n ],\n)\n@pytest.mark.parametrize("nullify", [None, "vmin", "vmax"]) # test min/max separately\n@pytest.mark.parametrize("align", ["left", "right", "zero", "mid"])\ndef test_vmin_vmax_clipping(df_pos, df_neg, df_mix, values, vmin, vmax, nullify, align):\n # test that clipping occurs if any vmin > data_values or vmax < data_values\n if align == "mid": # mid acts as left or right in each case\n if values == "positive":\n align = "left"\n elif values == "negative":\n align = "right"\n df = {"positive": df_pos, "negative": df_neg, "mixed": df_mix}[values]\n vmin = None if nullify == "vmin" else vmin\n vmax = None if nullify == "vmax" else vmax\n\n clip_df = df.where(df <= (vmax if vmax else 999), other=vmax)\n clip_df = clip_df.where(clip_df >= (vmin if vmin else -999), other=vmin)\n\n result = (\n df.style.bar(align=align, vmin=vmin, vmax=vmax, color=["red", "green"])\n ._compute()\n .ctx\n )\n expected = clip_df.style.bar(align=align, color=["red", "green"])._compute().ctx\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "values, vmin, vmax",\n [\n ("positive", 0.5, 4.5),\n ("negative", -4.5, -0.5),\n ("mixed", -4.5, 4.5),\n ],\n)\n@pytest.mark.parametrize("nullify", [None, "vmin", "vmax"]) # test min/max separately\n@pytest.mark.parametrize("align", ["left", "right", "zero", "mid"])\ndef test_vmin_vmax_widening(df_pos, df_neg, df_mix, values, vmin, vmax, nullify, align):\n # test that widening occurs if any vmax > data_values or vmin < data_values\n if align == "mid": # mid acts as left or right in each case\n if values == "positive":\n align = "left"\n elif values == "negative":\n align = "right"\n df = {"positive": df_pos, "negative": df_neg, "mixed": df_mix}[values]\n vmin = None if nullify == "vmin" else vmin\n vmax = None if nullify == "vmax" else vmax\n\n expand_df = df.copy()\n expand_df.loc[3, :], expand_df.loc[4, :] = vmin, vmax\n\n result = (\n df.style.bar(align=align, vmin=vmin, vmax=vmax, color=["red", "green"])\n ._compute()\n .ctx\n )\n expected = expand_df.style.bar(align=align, color=["red", "green"])._compute().ctx\n assert result.items() <= expected.items()\n\n\ndef test_numerics():\n # test data is pre-selected for numeric values\n data = DataFrame([[1, "a"], [2, "b"]])\n result = data.style.bar()._compute().ctx\n assert (0, 1) not in result\n assert (1, 1) not in result\n\n\n@pytest.mark.parametrize(\n "align, exp",\n [\n ("left", [no_bar(), bar_to(100, "green")]),\n ("right", [bar_to(100, "red"), no_bar()]),\n ("mid", [bar_to(25, "red"), bar_from_to(25, 100, "green")]),\n ("zero", [bar_from_to(33.33, 50, "red"), bar_from_to(50, 100, "green")]),\n ],\n)\ndef test_colors_mixed(align, exp):\n data = DataFrame([[-1], [3]])\n result = data.style.bar(align=align, color=["red", "green"])._compute().ctx\n assert result == {(0, 0): exp[0], (1, 0): exp[1]}\n\n\ndef test_bar_align_height():\n # test when keyword height is used 'no-repeat center' and 'background-size' present\n data = DataFrame([[1], [2]])\n result = data.style.bar(align="left", height=50)._compute().ctx\n bg_s = "linear-gradient(90deg, #d65f5f 100.0%, transparent 100.0%) no-repeat center"\n expected = {\n (0, 0): [("width", "10em")],\n (1, 0): [\n ("width", "10em"),\n ("background", bg_s),\n ("background-size", "100% 50.0%"),\n ],\n }\n assert result == expected\n\n\ndef test_bar_value_error_raises():\n df = DataFrame({"A": [-100, -60, -30, -20]})\n\n msg = "`align` should be in {'left', 'right', 'mid', 'mean', 'zero'} or"\n with pytest.raises(ValueError, match=msg):\n df.style.bar(align="poorly", color=["#d65f5f", "#5fba7d"]).to_html()\n\n msg = r"`width` must be a value in \[0, 100\]"\n with pytest.raises(ValueError, match=msg):\n df.style.bar(width=200).to_html()\n\n msg = r"`height` must be a value in \[0, 100\]"\n with pytest.raises(ValueError, match=msg):\n df.style.bar(height=200).to_html()\n\n\ndef test_bar_color_and_cmap_error_raises():\n df = DataFrame({"A": [1, 2, 3, 4]})\n msg = "`color` and `cmap` cannot both be given"\n # Test that providing both color and cmap raises a ValueError\n with pytest.raises(ValueError, match=msg):\n df.style.bar(color="#d65f5f", cmap="viridis").to_html()\n\n\ndef test_bar_invalid_color_type_error_raises():\n df = DataFrame({"A": [1, 2, 3, 4]})\n msg = (\n r"`color` must be string or list or tuple of 2 strings,"\n r"\(eg: color=\['#d65f5f', '#5fba7d'\]\)"\n )\n # Test that providing an invalid color type raises a ValueError\n with pytest.raises(ValueError, match=msg):\n df.style.bar(color=123).to_html()\n\n # Test that providing a color list with more than two elements raises a ValueError\n with pytest.raises(ValueError, match=msg):\n df.style.bar(color=["#d65f5f", "#5fba7d", "#abcdef"]).to_html()\n\n\ndef test_styler_bar_with_NA_values():\n df1 = DataFrame({"A": [1, 2, NA, 4]})\n df2 = DataFrame([[NA, NA], [NA, NA]])\n expected_substring = "style type="\n html_output1 = df1.style.bar(subset="A").to_html()\n html_output2 = df2.style.bar(align="left", axis=None).to_html()\n assert expected_substring in html_output1\n assert expected_substring in html_output2\n\n\ndef test_style_bar_with_pyarrow_NA_values():\n pytest.importorskip("pyarrow")\n data = """name,age,test1,test2,teacher\n Adam,15,95.0,80,Ashby\n Bob,16,81.0,82,Ashby\n Dave,16,89.0,84,Jones\n Fred,15,,88,Jones"""\n df = read_csv(io.StringIO(data), dtype_backend="pyarrow")\n expected_substring = "style type="\n html_output = df.style.bar(subset="test1").to_html()\n assert expected_substring in html_output\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_bar.py
test_bar.py
Python
12,049
0.95
0.119777
0.039216
node-utils
65
2024-03-30T20:35:39.294753
BSD-3-Clause
true
266fdbc05da7b6134b51c04eea8ecded
import pytest\n\njinja2 = pytest.importorskip("jinja2")\n\nfrom pandas import (\n DataFrame,\n MultiIndex,\n)\n\nfrom pandas.io.formats.style import Styler\n\n\n@pytest.fixture\ndef df():\n return DataFrame(\n data=[[0, -0.609], [1, -1.228]],\n columns=["A", "B"],\n index=["x", "y"],\n )\n\n\n@pytest.fixture\ndef styler(df):\n return Styler(df, uuid_len=0)\n\n\ndef test_concat_bad_columns(styler):\n msg = "`other.data` must have same columns as `Styler.data"\n with pytest.raises(ValueError, match=msg):\n styler.concat(DataFrame([[1, 2]]).style)\n\n\ndef test_concat_bad_type(styler):\n msg = "`other` must be of type `Styler`"\n with pytest.raises(TypeError, match=msg):\n styler.concat(DataFrame([[1, 2]]))\n\n\ndef test_concat_bad_index_levels(styler, df):\n df = df.copy()\n df.index = MultiIndex.from_tuples([(0, 0), (1, 1)])\n msg = "number of index levels must be same in `other`"\n with pytest.raises(ValueError, match=msg):\n styler.concat(df.style)\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_exceptions.py
test_exceptions.py
Python
1,002
0.85
0.113636
0
react-lib
70
2024-04-29T19:06:38.316476
BSD-3-Clause
true
b41a00914bd4dda3100793a365b3f02b
import numpy as np\nimport pytest\n\nfrom pandas import (\n NA,\n DataFrame,\n IndexSlice,\n MultiIndex,\n NaT,\n Timestamp,\n option_context,\n)\n\npytest.importorskip("jinja2")\nfrom pandas.io.formats.style import Styler\nfrom pandas.io.formats.style_render import _str_escape\n\n\n@pytest.fixture\ndef df():\n return DataFrame(\n data=[[0, -0.609], [1, -1.228]],\n columns=["A", "B"],\n index=["x", "y"],\n )\n\n\n@pytest.fixture\ndef styler(df):\n return Styler(df, uuid_len=0)\n\n\n@pytest.fixture\ndef df_multi():\n return DataFrame(\n data=np.arange(16).reshape(4, 4),\n columns=MultiIndex.from_product([["A", "B"], ["a", "b"]]),\n index=MultiIndex.from_product([["X", "Y"], ["x", "y"]]),\n )\n\n\n@pytest.fixture\ndef styler_multi(df_multi):\n return Styler(df_multi, uuid_len=0)\n\n\ndef test_display_format(styler):\n ctx = styler.format("{:0.1f}")._translate(True, True)\n assert all(["display_value" in c for c in row] for row in ctx["body"])\n assert all([len(c["display_value"]) <= 3 for c in row[1:]] for row in ctx["body"])\n assert len(ctx["body"][0][1]["display_value"].lstrip("-")) <= 3\n\n\n@pytest.mark.parametrize("index", [True, False])\n@pytest.mark.parametrize("columns", [True, False])\ndef test_display_format_index(styler, index, columns):\n exp_index = ["x", "y"]\n if index:\n styler.format_index(lambda v: v.upper(), axis=0) # test callable\n exp_index = ["X", "Y"]\n\n exp_columns = ["A", "B"]\n if columns:\n styler.format_index("*{}*", axis=1) # test string\n exp_columns = ["*A*", "*B*"]\n\n ctx = styler._translate(True, True)\n\n for r, row in enumerate(ctx["body"]):\n assert row[0]["display_value"] == exp_index[r]\n\n for c, col in enumerate(ctx["head"][1:]):\n assert col["display_value"] == exp_columns[c]\n\n\ndef test_format_dict(styler):\n ctx = styler.format({"A": "{:0.1f}", "B": "{0:.2%}"})._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == "0.0"\n assert ctx["body"][0][2]["display_value"] == "-60.90%"\n\n\ndef test_format_index_dict(styler):\n ctx = styler.format_index({0: lambda v: v.upper()})._translate(True, True)\n for i, val in enumerate(["X", "Y"]):\n assert ctx["body"][i][0]["display_value"] == val\n\n\ndef test_format_string(styler):\n ctx = styler.format("{:.2f}")._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == "0.00"\n assert ctx["body"][0][2]["display_value"] == "-0.61"\n assert ctx["body"][1][1]["display_value"] == "1.00"\n assert ctx["body"][1][2]["display_value"] == "-1.23"\n\n\ndef test_format_callable(styler):\n ctx = styler.format(lambda v: "neg" if v < 0 else "pos")._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == "pos"\n assert ctx["body"][0][2]["display_value"] == "neg"\n assert ctx["body"][1][1]["display_value"] == "pos"\n assert ctx["body"][1][2]["display_value"] == "neg"\n\n\ndef test_format_with_na_rep():\n # GH 21527 28358\n df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])\n\n ctx = df.style.format(None, na_rep="-")._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == "-"\n assert ctx["body"][0][2]["display_value"] == "-"\n\n ctx = df.style.format("{:.2%}", na_rep="-")._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == "-"\n assert ctx["body"][0][2]["display_value"] == "-"\n assert ctx["body"][1][1]["display_value"] == "110.00%"\n assert ctx["body"][1][2]["display_value"] == "120.00%"\n\n ctx = df.style.format("{:.2%}", na_rep="-", subset=["B"])._translate(True, True)\n assert ctx["body"][0][2]["display_value"] == "-"\n assert ctx["body"][1][2]["display_value"] == "120.00%"\n\n\ndef test_format_index_with_na_rep():\n df = DataFrame([[1, 2, 3, 4, 5]], columns=["A", None, np.nan, NaT, NA])\n ctx = df.style.format_index(None, na_rep="--", axis=1)._translate(True, True)\n assert ctx["head"][0][1]["display_value"] == "A"\n for i in [2, 3, 4, 5]:\n assert ctx["head"][0][i]["display_value"] == "--"\n\n\ndef test_format_non_numeric_na():\n # GH 21527 28358\n df = DataFrame(\n {\n "object": [None, np.nan, "foo"],\n "datetime": [None, NaT, Timestamp("20120101")],\n }\n )\n ctx = df.style.format(None, na_rep="-")._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == "-"\n assert ctx["body"][0][2]["display_value"] == "-"\n assert ctx["body"][1][1]["display_value"] == "-"\n assert ctx["body"][1][2]["display_value"] == "-"\n\n\n@pytest.mark.parametrize(\n "func, attr, kwargs",\n [\n ("format", "_display_funcs", {}),\n ("format_index", "_display_funcs_index", {"axis": 0}),\n ("format_index", "_display_funcs_columns", {"axis": 1}),\n ],\n)\ndef test_format_clear(styler, func, attr, kwargs):\n assert (0, 0) not in getattr(styler, attr) # using default\n getattr(styler, func)("{:.2f}", **kwargs)\n assert (0, 0) in getattr(styler, attr) # formatter is specified\n getattr(styler, func)(**kwargs)\n assert (0, 0) not in getattr(styler, attr) # formatter cleared to default\n\n\n@pytest.mark.parametrize(\n "escape, exp",\n [\n ("html", "&lt;&gt;&amp;&#34;%$#_{}~^\\~ ^ \\ "),\n (\n "latex",\n '<>\\&"\\%\\$\\#\\_\\{\\}\\textasciitilde \\textasciicircum '\n "\\textbackslash \\textasciitilde \\space \\textasciicircum \\space "\n "\\textbackslash \\space ",\n ),\n ],\n)\ndef test_format_escape_html(escape, exp):\n chars = '<>&"%$#_{}~^\\~ ^ \\ '\n df = DataFrame([[chars]])\n\n s = Styler(df, uuid_len=0).format("&{0}&", escape=None)\n expected = f'<td id="T__row0_col0" class="data row0 col0" >&{chars}&</td>'\n assert expected in s.to_html()\n\n # only the value should be escaped before passing to the formatter\n s = Styler(df, uuid_len=0).format("&{0}&", escape=escape)\n expected = f'<td id="T__row0_col0" class="data row0 col0" >&{exp}&</td>'\n assert expected in s.to_html()\n\n # also test format_index()\n styler = Styler(DataFrame(columns=[chars]), uuid_len=0)\n styler.format_index("&{0}&", escape=None, axis=1)\n assert styler._translate(True, True)["head"][0][1]["display_value"] == f"&{chars}&"\n styler.format_index("&{0}&", escape=escape, axis=1)\n assert styler._translate(True, True)["head"][0][1]["display_value"] == f"&{exp}&"\n\n\n@pytest.mark.parametrize(\n "chars, expected",\n [\n (\n r"$ \$&%#_{}~^\ $ &%#_{}~^\ $",\n "".join(\n [\n r"$ \$&%#_{}~^\ $ ",\n r"\&\%\#\_\{\}\textasciitilde \textasciicircum ",\n r"\textbackslash \space \$",\n ]\n ),\n ),\n (\n r"\( &%#_{}~^\ \) &%#_{}~^\ \(",\n "".join(\n [\n r"\( &%#_{}~^\ \) ",\n r"\&\%\#\_\{\}\textasciitilde \textasciicircum ",\n r"\textbackslash \space \textbackslash (",\n ]\n ),\n ),\n (\n r"$\&%#_{}^\$",\n r"\$\textbackslash \&\%\#\_\{\}\textasciicircum \textbackslash \$",\n ),\n (\n r"$ \frac{1}{2} $ \( \frac{1}{2} \)",\n "".join(\n [\n r"$ \frac{1}{2} $",\n r" \textbackslash ( \textbackslash frac\{1\}\{2\} \textbackslash )",\n ]\n ),\n ),\n ],\n)\ndef test_format_escape_latex_math(chars, expected):\n # GH 51903\n # latex-math escape works for each DataFrame cell separately. If we have\n # a combination of dollar signs and brackets, the dollar sign would apply.\n df = DataFrame([[chars]])\n s = df.style.format("{0}", escape="latex-math")\n assert s._translate(True, True)["body"][0][1]["display_value"] == expected\n\n\ndef test_format_escape_na_rep():\n # tests the na_rep is not escaped\n df = DataFrame([['<>&"', None]])\n s = Styler(df, uuid_len=0).format("X&{0}>X", escape="html", na_rep="&")\n ex = '<td id="T__row0_col0" class="data row0 col0" >X&&lt;&gt;&amp;&#34;>X</td>'\n expected2 = '<td id="T__row0_col1" class="data row0 col1" >&</td>'\n assert ex in s.to_html()\n assert expected2 in s.to_html()\n\n # also test for format_index()\n df = DataFrame(columns=['<>&"', None])\n styler = Styler(df, uuid_len=0)\n styler.format_index("X&{0}>X", escape="html", na_rep="&", axis=1)\n ctx = styler._translate(True, True)\n assert ctx["head"][0][1]["display_value"] == "X&&lt;&gt;&amp;&#34;>X"\n assert ctx["head"][0][2]["display_value"] == "&"\n\n\ndef test_format_escape_floats(styler):\n # test given formatter for number format is not impacted by escape\n s = styler.format("{:.1f}", escape="html")\n for expected in [">0.0<", ">1.0<", ">-1.2<", ">-0.6<"]:\n assert expected in s.to_html()\n # tests precision of floats is not impacted by escape\n s = styler.format(precision=1, escape="html")\n for expected in [">0<", ">1<", ">-1.2<", ">-0.6<"]:\n assert expected in s.to_html()\n\n\n@pytest.mark.parametrize("formatter", [5, True, [2.0]])\n@pytest.mark.parametrize("func", ["format", "format_index"])\ndef test_format_raises(styler, formatter, func):\n with pytest.raises(TypeError, match="expected str or callable"):\n getattr(styler, func)(formatter)\n\n\n@pytest.mark.parametrize(\n "precision, expected",\n [\n (1, ["1.0", "2.0", "3.2", "4.6"]),\n (2, ["1.00", "2.01", "3.21", "4.57"]),\n (3, ["1.000", "2.009", "3.212", "4.566"]),\n ],\n)\ndef test_format_with_precision(precision, expected):\n # Issue #13257\n df = DataFrame([[1.0, 2.0090, 3.2121, 4.566]], columns=[1.0, 2.0090, 3.2121, 4.566])\n styler = Styler(df)\n styler.format(precision=precision)\n styler.format_index(precision=precision, axis=1)\n\n ctx = styler._translate(True, True)\n for col, exp in enumerate(expected):\n assert ctx["body"][0][col + 1]["display_value"] == exp # format test\n assert ctx["head"][0][col + 1]["display_value"] == exp # format_index test\n\n\n@pytest.mark.parametrize("axis", [0, 1])\n@pytest.mark.parametrize(\n "level, expected",\n [\n (0, ["X", "X", "_", "_"]), # level int\n ("zero", ["X", "X", "_", "_"]), # level name\n (1, ["_", "_", "X", "X"]), # other level int\n ("one", ["_", "_", "X", "X"]), # other level name\n ([0, 1], ["X", "X", "X", "X"]), # both levels\n ([0, "zero"], ["X", "X", "_", "_"]), # level int and name simultaneous\n ([0, "one"], ["X", "X", "X", "X"]), # both levels as int and name\n (["one", "zero"], ["X", "X", "X", "X"]), # both level names, reversed\n ],\n)\ndef test_format_index_level(axis, level, expected):\n midx = MultiIndex.from_arrays([["_", "_"], ["_", "_"]], names=["zero", "one"])\n df = DataFrame([[1, 2], [3, 4]])\n if axis == 0:\n df.index = midx\n else:\n df.columns = midx\n\n styler = df.style.format_index(lambda v: "X", level=level, axis=axis)\n ctx = styler._translate(True, True)\n\n if axis == 0: # compare index\n result = [ctx["body"][s][0]["display_value"] for s in range(2)]\n result += [ctx["body"][s][1]["display_value"] for s in range(2)]\n else: # compare columns\n result = [ctx["head"][0][s + 1]["display_value"] for s in range(2)]\n result += [ctx["head"][1][s + 1]["display_value"] for s in range(2)]\n\n assert expected == result\n\n\ndef test_format_subset():\n df = DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"])\n ctx = df.style.format(\n {"a": "{:0.1f}", "b": "{0:.2%}"}, subset=IndexSlice[0, :]\n )._translate(True, True)\n expected = "0.1"\n raw_11 = "1.123400"\n assert ctx["body"][0][1]["display_value"] == expected\n assert ctx["body"][1][1]["display_value"] == raw_11\n assert ctx["body"][0][2]["display_value"] == "12.34%"\n\n ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, :])._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == expected\n assert ctx["body"][1][1]["display_value"] == raw_11\n\n ctx = df.style.format("{:0.1f}", subset=IndexSlice["a"])._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == expected\n assert ctx["body"][0][2]["display_value"] == "0.123400"\n\n ctx = df.style.format("{:0.1f}", subset=IndexSlice[0, "a"])._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == expected\n assert ctx["body"][1][1]["display_value"] == raw_11\n\n ctx = df.style.format("{:0.1f}", subset=IndexSlice[[0, 1], ["a"]])._translate(\n True, True\n )\n assert ctx["body"][0][1]["display_value"] == expected\n assert ctx["body"][1][1]["display_value"] == "1.1"\n assert ctx["body"][0][2]["display_value"] == "0.123400"\n assert ctx["body"][1][2]["display_value"] == raw_11\n\n\n@pytest.mark.parametrize("formatter", [None, "{:,.1f}"])\n@pytest.mark.parametrize("decimal", [".", "*"])\n@pytest.mark.parametrize("precision", [None, 2])\n@pytest.mark.parametrize("func, col", [("format", 1), ("format_index", 0)])\ndef test_format_thousands(formatter, decimal, precision, func, col):\n styler = DataFrame([[1000000.123456789]], index=[1000000.123456789]).style\n result = getattr(styler, func)( # testing float\n thousands="_", formatter=formatter, decimal=decimal, precision=precision\n )._translate(True, True)\n assert "1_000_000" in result["body"][0][col]["display_value"]\n\n styler = DataFrame([[1000000]], index=[1000000]).style\n result = getattr(styler, func)( # testing int\n thousands="_", formatter=formatter, decimal=decimal, precision=precision\n )._translate(True, True)\n assert "1_000_000" in result["body"][0][col]["display_value"]\n\n styler = DataFrame([[1 + 1000000.123456789j]], index=[1 + 1000000.123456789j]).style\n result = getattr(styler, func)( # testing complex\n thousands="_", formatter=formatter, decimal=decimal, precision=precision\n )._translate(True, True)\n assert "1_000_000" in result["body"][0][col]["display_value"]\n\n\n@pytest.mark.parametrize("formatter", [None, "{:,.4f}"])\n@pytest.mark.parametrize("thousands", [None, ",", "*"])\n@pytest.mark.parametrize("precision", [None, 4])\n@pytest.mark.parametrize("func, col", [("format", 1), ("format_index", 0)])\ndef test_format_decimal(formatter, thousands, precision, func, col):\n styler = DataFrame([[1000000.123456789]], index=[1000000.123456789]).style\n result = getattr(styler, func)( # testing float\n decimal="_", formatter=formatter, thousands=thousands, precision=precision\n )._translate(True, True)\n assert "000_123" in result["body"][0][col]["display_value"]\n\n styler = DataFrame([[1 + 1000000.123456789j]], index=[1 + 1000000.123456789j]).style\n result = getattr(styler, func)( # testing complex\n decimal="_", formatter=formatter, thousands=thousands, precision=precision\n )._translate(True, True)\n assert "000_123" in result["body"][0][col]["display_value"]\n\n\ndef test_str_escape_error():\n msg = "`escape` only permitted in {'html', 'latex', 'latex-math'}, got "\n with pytest.raises(ValueError, match=msg):\n _str_escape("text", "bad_escape")\n\n with pytest.raises(ValueError, match=msg):\n _str_escape("text", [])\n\n _str_escape(2.00, "bad_escape") # OK since dtype is float\n\n\ndef test_long_int_formatting():\n df = DataFrame(data=[[1234567890123456789]], columns=["test"])\n styler = df.style\n ctx = styler._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == "1234567890123456789"\n\n styler = df.style.format(thousands="_")\n ctx = styler._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == "1_234_567_890_123_456_789"\n\n\ndef test_format_options():\n df = DataFrame({"int": [2000, 1], "float": [1.009, None], "str": ["&<", "&~"]})\n ctx = df.style._translate(True, True)\n\n # test option: na_rep\n assert ctx["body"][1][2]["display_value"] == "nan"\n with option_context("styler.format.na_rep", "MISSING"):\n ctx_with_op = df.style._translate(True, True)\n assert ctx_with_op["body"][1][2]["display_value"] == "MISSING"\n\n # test option: decimal and precision\n assert ctx["body"][0][2]["display_value"] == "1.009000"\n with option_context("styler.format.decimal", "_"):\n ctx_with_op = df.style._translate(True, True)\n assert ctx_with_op["body"][0][2]["display_value"] == "1_009000"\n with option_context("styler.format.precision", 2):\n ctx_with_op = df.style._translate(True, True)\n assert ctx_with_op["body"][0][2]["display_value"] == "1.01"\n\n # test option: thousands\n assert ctx["body"][0][1]["display_value"] == "2000"\n with option_context("styler.format.thousands", "_"):\n ctx_with_op = df.style._translate(True, True)\n assert ctx_with_op["body"][0][1]["display_value"] == "2_000"\n\n # test option: escape\n assert ctx["body"][0][3]["display_value"] == "&<"\n assert ctx["body"][1][3]["display_value"] == "&~"\n with option_context("styler.format.escape", "html"):\n ctx_with_op = df.style._translate(True, True)\n assert ctx_with_op["body"][0][3]["display_value"] == "&amp;&lt;"\n with option_context("styler.format.escape", "latex"):\n ctx_with_op = df.style._translate(True, True)\n assert ctx_with_op["body"][1][3]["display_value"] == "\\&\\textasciitilde "\n with option_context("styler.format.escape", "latex-math"):\n ctx_with_op = df.style._translate(True, True)\n assert ctx_with_op["body"][1][3]["display_value"] == "\\&\\textasciitilde "\n\n # test option: formatter\n with option_context("styler.format.formatter", {"int": "{:,.2f}"}):\n ctx_with_op = df.style._translate(True, True)\n assert ctx_with_op["body"][0][1]["display_value"] == "2,000.00"\n\n\ndef test_precision_zero(df):\n styler = Styler(df, precision=0)\n ctx = styler._translate(True, True)\n assert ctx["body"][0][2]["display_value"] == "-1"\n assert ctx["body"][1][2]["display_value"] == "-1"\n\n\n@pytest.mark.parametrize(\n "formatter, exp",\n [\n (lambda x: f"{x:.3f}", "9.000"),\n ("{:.2f}", "9.00"),\n ({0: "{:.1f}"}, "9.0"),\n (None, "9"),\n ],\n)\ndef test_formatter_options_validator(formatter, exp):\n df = DataFrame([[9]])\n with option_context("styler.format.formatter", formatter):\n assert f" {exp} " in df.style.to_latex()\n\n\ndef test_formatter_options_raises():\n msg = "Value must be an instance of"\n with pytest.raises(ValueError, match=msg):\n with option_context("styler.format.formatter", ["bad", "type"]):\n DataFrame().style.to_latex()\n\n\ndef test_1level_multiindex():\n # GH 43383\n midx = MultiIndex.from_product([[1, 2]], names=[""])\n df = DataFrame(-1, index=midx, columns=[0, 1])\n ctx = df.style._translate(True, True)\n assert ctx["body"][0][0]["display_value"] == "1"\n assert ctx["body"][0][0]["is_visible"] is True\n assert ctx["body"][1][0]["display_value"] == "2"\n assert ctx["body"][1][0]["is_visible"] is True\n\n\ndef test_boolean_format():\n # gh 46384: booleans do not collapse to integer representation on display\n df = DataFrame([[True, False]])\n ctx = df.style._translate(True, True)\n assert ctx["body"][0][1]["display_value"] is True\n assert ctx["body"][0][2]["display_value"] is False\n\n\n@pytest.mark.parametrize(\n "hide, labels",\n [\n (False, [1, 2]),\n (True, [1, 2, 3, 4]),\n ],\n)\ndef test_relabel_raise_length(styler_multi, hide, labels):\n if hide:\n styler_multi.hide(axis=0, subset=[("X", "x"), ("Y", "y")])\n with pytest.raises(ValueError, match="``labels`` must be of length equal"):\n styler_multi.relabel_index(labels=labels)\n\n\ndef test_relabel_index(styler_multi):\n labels = [(1, 2), (3, 4)]\n styler_multi.hide(axis=0, subset=[("X", "x"), ("Y", "y")])\n styler_multi.relabel_index(labels=labels)\n ctx = styler_multi._translate(True, True)\n assert {"value": "X", "display_value": 1}.items() <= ctx["body"][0][0].items()\n assert {"value": "y", "display_value": 2}.items() <= ctx["body"][0][1].items()\n assert {"value": "Y", "display_value": 3}.items() <= ctx["body"][1][0].items()\n assert {"value": "x", "display_value": 4}.items() <= ctx["body"][1][1].items()\n\n\ndef test_relabel_columns(styler_multi):\n labels = [(1, 2), (3, 4)]\n styler_multi.hide(axis=1, subset=[("A", "a"), ("B", "b")])\n styler_multi.relabel_index(axis=1, labels=labels)\n ctx = styler_multi._translate(True, True)\n assert {"value": "A", "display_value": 1}.items() <= ctx["head"][0][3].items()\n assert {"value": "B", "display_value": 3}.items() <= ctx["head"][0][4].items()\n assert {"value": "b", "display_value": 2}.items() <= ctx["head"][1][3].items()\n assert {"value": "a", "display_value": 4}.items() <= ctx["head"][1][4].items()\n\n\ndef test_relabel_roundtrip(styler):\n styler.relabel_index(["{}", "{}"])\n ctx = styler._translate(True, True)\n assert {"value": "x", "display_value": "x"}.items() <= ctx["body"][0][0].items()\n assert {"value": "y", "display_value": "y"}.items() <= ctx["body"][1][0].items()\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_format.py
test_format.py
Python
21,154
0.95
0.113879
0.041485
react-lib
185
2025-06-03T15:57:56.218122
GPL-3.0
true
d23c8eca5a46314116d22763026a4dbb
import numpy as np\nimport pytest\n\nfrom pandas import (\n NA,\n DataFrame,\n IndexSlice,\n)\n\npytest.importorskip("jinja2")\n\nfrom pandas.io.formats.style import Styler\n\n\n@pytest.fixture(params=[(None, "float64"), (NA, "Int64")])\ndef df(request):\n # GH 45804\n return DataFrame(\n {"A": [0, np.nan, 10], "B": [1, request.param[0], 2]}, dtype=request.param[1]\n )\n\n\n@pytest.fixture\ndef styler(df):\n return Styler(df, uuid_len=0)\n\n\ndef test_highlight_null(styler):\n result = styler.highlight_null()._compute().ctx\n expected = {\n (1, 0): [("background-color", "red")],\n (1, 1): [("background-color", "red")],\n }\n assert result == expected\n\n\ndef test_highlight_null_subset(styler):\n # GH 31345\n result = (\n styler.highlight_null(color="red", subset=["A"])\n .highlight_null(color="green", subset=["B"])\n ._compute()\n .ctx\n )\n expected = {\n (1, 0): [("background-color", "red")],\n (1, 1): [("background-color", "green")],\n }\n assert result == expected\n\n\n@pytest.mark.parametrize("f", ["highlight_min", "highlight_max"])\ndef test_highlight_minmax_basic(df, f):\n expected = {\n (0, 1): [("background-color", "red")],\n # ignores NaN row,\n (2, 0): [("background-color", "red")],\n }\n if f == "highlight_min":\n df = -df\n result = getattr(df.style, f)(axis=1, color="red")._compute().ctx\n assert result == expected\n\n\n@pytest.mark.parametrize("f", ["highlight_min", "highlight_max"])\n@pytest.mark.parametrize(\n "kwargs",\n [\n {"axis": None, "color": "red"}, # test axis\n {"axis": 0, "subset": ["A"], "color": "red"}, # test subset and ignores NaN\n {"axis": None, "props": "background-color: red"}, # test props\n ],\n)\ndef test_highlight_minmax_ext(df, f, kwargs):\n expected = {(2, 0): [("background-color", "red")]}\n if f == "highlight_min":\n df = -df\n result = getattr(df.style, f)(**kwargs)._compute().ctx\n assert result == expected\n\n\n@pytest.mark.parametrize("f", ["highlight_min", "highlight_max"])\n@pytest.mark.parametrize("axis", [None, 0, 1])\ndef test_highlight_minmax_nulls(f, axis):\n # GH 42750\n expected = {\n (1, 0): [("background-color", "yellow")],\n (1, 1): [("background-color", "yellow")],\n }\n if axis == 1:\n expected.update({(2, 1): [("background-color", "yellow")]})\n\n if f == "highlight_max":\n df = DataFrame({"a": [NA, 1, None], "b": [np.nan, 1, -1]})\n else:\n df = DataFrame({"a": [NA, -1, None], "b": [np.nan, -1, 1]})\n\n result = getattr(df.style, f)(axis=axis)._compute().ctx\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "kwargs",\n [\n {"left": 0, "right": 1}, # test basic range\n {"left": 0, "right": 1, "props": "background-color: yellow"}, # test props\n {"left": -100, "right": 100, "subset": IndexSlice[[0, 1], :]}, # test subset\n {"left": 0, "subset": IndexSlice[[0, 1], :]}, # test no right\n {"right": 1}, # test no left\n {"left": [0, 0, 11], "axis": 0}, # test left as sequence\n {"left": DataFrame({"A": [0, 0, 11], "B": [1, 1, 11]}), "axis": None}, # axis\n {"left": 0, "right": [0, 1], "axis": 1}, # test sequence right\n ],\n)\ndef test_highlight_between(styler, kwargs):\n expected = {\n (0, 0): [("background-color", "yellow")],\n (0, 1): [("background-color", "yellow")],\n }\n result = styler.highlight_between(**kwargs)._compute().ctx\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "arg, map, axis",\n [\n ("left", [1, 2], 0), # 0 axis has 3 elements not 2\n ("left", [1, 2, 3], 1), # 1 axis has 2 elements not 3\n ("left", np.array([[1, 2], [1, 2]]), None), # df is (2,3) not (2,2)\n ("right", [1, 2], 0), # same tests as above for 'right' not 'left'\n ("right", [1, 2, 3], 1), # ..\n ("right", np.array([[1, 2], [1, 2]]), None), # ..\n ],\n)\ndef test_highlight_between_raises(arg, styler, map, axis):\n msg = f"supplied '{arg}' is not correct shape"\n with pytest.raises(ValueError, match=msg):\n styler.highlight_between(**{arg: map, "axis": axis})._compute()\n\n\ndef test_highlight_between_raises2(styler):\n msg = "values can be 'both', 'left', 'right', or 'neither'"\n with pytest.raises(ValueError, match=msg):\n styler.highlight_between(inclusive="badstring")._compute()\n\n with pytest.raises(ValueError, match=msg):\n styler.highlight_between(inclusive=1)._compute()\n\n\n@pytest.mark.parametrize(\n "inclusive, expected",\n [\n (\n "both",\n {\n (0, 0): [("background-color", "yellow")],\n (0, 1): [("background-color", "yellow")],\n },\n ),\n ("neither", {}),\n ("left", {(0, 0): [("background-color", "yellow")]}),\n ("right", {(0, 1): [("background-color", "yellow")]}),\n ],\n)\ndef test_highlight_between_inclusive(styler, inclusive, expected):\n kwargs = {"left": 0, "right": 1, "subset": IndexSlice[[0, 1], :]}\n result = styler.highlight_between(**kwargs, inclusive=inclusive)._compute()\n assert result.ctx == expected\n\n\n@pytest.mark.parametrize(\n "kwargs",\n [\n {"q_left": 0.5, "q_right": 1, "axis": 0}, # base case\n {"q_left": 0.5, "q_right": 1, "axis": None}, # test axis\n {"q_left": 0, "q_right": 1, "subset": IndexSlice[2, :]}, # test subset\n {"q_left": 0.5, "axis": 0}, # test no high\n {"q_right": 1, "subset": IndexSlice[2, :], "axis": 1}, # test no low\n {"q_left": 0.5, "axis": 0, "props": "background-color: yellow"}, # tst prop\n ],\n)\ndef test_highlight_quantile(styler, kwargs):\n expected = {\n (2, 0): [("background-color", "yellow")],\n (2, 1): [("background-color", "yellow")],\n }\n result = styler.highlight_quantile(**kwargs)._compute().ctx\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "f,kwargs",\n [\n ("highlight_min", {"axis": 1, "subset": IndexSlice[1, :]}),\n ("highlight_max", {"axis": 0, "subset": [0]}),\n ("highlight_quantile", {"axis": None, "q_left": 0.6, "q_right": 0.8}),\n ("highlight_between", {"subset": [0]}),\n ],\n)\n@pytest.mark.parametrize(\n "df",\n [\n DataFrame([[0, 10], [20, 30]], dtype=int),\n DataFrame([[0, 10], [20, 30]], dtype=float),\n DataFrame([[0, 10], [20, 30]], dtype="datetime64[ns]"),\n DataFrame([[0, 10], [20, 30]], dtype=str),\n DataFrame([[0, 10], [20, 30]], dtype="timedelta64[ns]"),\n ],\n)\ndef test_all_highlight_dtypes(f, kwargs, df):\n if f == "highlight_quantile" and isinstance(df.iloc[0, 0], (str)):\n return None # quantile incompatible with str\n if f == "highlight_between":\n kwargs["left"] = df.iloc[1, 0] # set the range low for testing\n\n expected = {(1, 0): [("background-color", "yellow")]}\n result = getattr(df.style, f)(**kwargs)._compute().ctx\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_highlight.py
test_highlight.py
Python
7,003
0.95
0.09633
0.021622
react-lib
767
2024-10-13T06:28:05.027859
GPL-3.0
true
c5878d008e6045db33c1613b6bfe7e4f
from textwrap import (\n dedent,\n indent,\n)\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n MultiIndex,\n option_context,\n)\n\njinja2 = pytest.importorskip("jinja2")\nfrom pandas.io.formats.style import Styler\n\n\n@pytest.fixture\ndef env():\n loader = jinja2.PackageLoader("pandas", "io/formats/templates")\n env = jinja2.Environment(loader=loader, trim_blocks=True)\n return env\n\n\n@pytest.fixture\ndef styler():\n return Styler(DataFrame([[2.61], [2.69]], index=["a", "b"], columns=["A"]))\n\n\n@pytest.fixture\ndef styler_mi():\n midx = MultiIndex.from_product([["a", "b"], ["c", "d"]])\n return Styler(DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=midx))\n\n\n@pytest.fixture\ndef tpl_style(env):\n return env.get_template("html_style.tpl")\n\n\n@pytest.fixture\ndef tpl_table(env):\n return env.get_template("html_table.tpl")\n\n\ndef test_html_template_extends_options():\n # make sure if templates are edited tests are updated as are setup fixtures\n # to understand the dependency\n with open("pandas/io/formats/templates/html.tpl", encoding="utf-8") as file:\n result = file.read()\n assert "{% include html_style_tpl %}" in result\n assert "{% include html_table_tpl %}" in result\n\n\ndef test_exclude_styles(styler):\n result = styler.to_html(exclude_styles=True, doctype_html=True)\n expected = dedent(\n """\\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset="utf-8">\n </head>\n <body>\n <table>\n <thead>\n <tr>\n <th >&nbsp;</th>\n <th >A</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th >a</th>\n <td >2.610000</td>\n </tr>\n <tr>\n <th >b</th>\n <td >2.690000</td>\n </tr>\n </tbody>\n </table>\n </body>\n </html>\n """\n )\n assert result == expected\n\n\ndef test_w3_html_format(styler):\n styler.set_uuid("").set_table_styles([{"selector": "th", "props": "att2:v2;"}]).map(\n lambda x: "att1:v1;"\n ).set_table_attributes('class="my-cls1" style="attr3:v3;"').set_td_classes(\n DataFrame(["my-cls2"], index=["a"], columns=["A"])\n ).format(\n "{:.1f}"\n ).set_caption(\n "A comprehensive test"\n )\n expected = dedent(\n """\\n <style type="text/css">\n #T_ th {\n att2: v2;\n }\n #T__row0_col0, #T__row1_col0 {\n att1: v1;\n }\n </style>\n <table id="T_" class="my-cls1" style="attr3:v3;">\n <caption>A comprehensive test</caption>\n <thead>\n <tr>\n <th class="blank level0" >&nbsp;</th>\n <th id="T__level0_col0" class="col_heading level0 col0" >A</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th id="T__level0_row0" class="row_heading level0 row0" >a</th>\n <td id="T__row0_col0" class="data row0 col0 my-cls2" >2.6</td>\n </tr>\n <tr>\n <th id="T__level0_row1" class="row_heading level0 row1" >b</th>\n <td id="T__row1_col0" class="data row1 col0" >2.7</td>\n </tr>\n </tbody>\n </table>\n """\n )\n assert expected == styler.to_html()\n\n\ndef test_colspan_w3():\n # GH 36223\n df = DataFrame(data=[[1, 2]], columns=[["l0", "l0"], ["l1a", "l1b"]])\n styler = Styler(df, uuid="_", cell_ids=False)\n assert '<th class="col_heading level0 col0" colspan="2">l0</th>' in styler.to_html()\n\n\ndef test_rowspan_w3():\n # GH 38533\n df = DataFrame(data=[[1, 2]], index=[["l0", "l0"], ["l1a", "l1b"]])\n styler = Styler(df, uuid="_", cell_ids=False)\n assert '<th class="row_heading level0 row0" rowspan="2">l0</th>' in styler.to_html()\n\n\ndef test_styles(styler):\n styler.set_uuid("abc")\n styler.set_table_styles([{"selector": "td", "props": "color: red;"}])\n result = styler.to_html(doctype_html=True)\n expected = dedent(\n """\\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset="utf-8">\n <style type="text/css">\n #T_abc td {\n color: red;\n }\n </style>\n </head>\n <body>\n <table id="T_abc">\n <thead>\n <tr>\n <th class="blank level0" >&nbsp;</th>\n <th id="T_abc_level0_col0" class="col_heading level0 col0" >A</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th id="T_abc_level0_row0" class="row_heading level0 row0" >a</th>\n <td id="T_abc_row0_col0" class="data row0 col0" >2.610000</td>\n </tr>\n <tr>\n <th id="T_abc_level0_row1" class="row_heading level0 row1" >b</th>\n <td id="T_abc_row1_col0" class="data row1 col0" >2.690000</td>\n </tr>\n </tbody>\n </table>\n </body>\n </html>\n """\n )\n assert result == expected\n\n\ndef test_doctype(styler):\n result = styler.to_html(doctype_html=False)\n assert "<html>" not in result\n assert "<body>" not in result\n assert "<!DOCTYPE html>" not in result\n assert "<head>" not in result\n\n\ndef test_doctype_encoding(styler):\n with option_context("styler.render.encoding", "ASCII"):\n result = styler.to_html(doctype_html=True)\n assert '<meta charset="ASCII">' in result\n result = styler.to_html(doctype_html=True, encoding="ANSI")\n assert '<meta charset="ANSI">' in result\n\n\ndef test_bold_headers_arg(styler):\n result = styler.to_html(bold_headers=True)\n assert "th {\n font-weight: bold;\n}" in result\n result = styler.to_html()\n assert "th {\n font-weight: bold;\n}" not in result\n\n\ndef test_caption_arg(styler):\n result = styler.to_html(caption="foo bar")\n assert "<caption>foo bar</caption>" in result\n result = styler.to_html()\n assert "<caption>foo bar</caption>" not in result\n\n\ndef test_block_names(tpl_style, tpl_table):\n # catch accidental removal of a block\n expected_style = {\n "before_style",\n "style",\n "table_styles",\n "before_cellstyle",\n "cellstyle",\n }\n expected_table = {\n "before_table",\n "table",\n "caption",\n "thead",\n "tbody",\n "after_table",\n "before_head_rows",\n "head_tr",\n "after_head_rows",\n "before_rows",\n "tr",\n "after_rows",\n }\n result1 = set(tpl_style.blocks)\n assert result1 == expected_style\n\n result2 = set(tpl_table.blocks)\n assert result2 == expected_table\n\n\ndef test_from_custom_template_table(tmpdir):\n p = tmpdir.mkdir("tpl").join("myhtml_table.tpl")\n p.write(\n dedent(\n """\\n {% extends "html_table.tpl" %}\n {% block table %}\n <h1>{{custom_title}}</h1>\n {{ super() }}\n {% endblock table %}"""\n )\n )\n result = Styler.from_custom_template(str(tmpdir.join("tpl")), "myhtml_table.tpl")\n assert issubclass(result, Styler)\n assert result.env is not Styler.env\n assert result.template_html_table is not Styler.template_html_table\n styler = result(DataFrame({"A": [1, 2]}))\n assert "<h1>My Title</h1>\n\n\n<table" in styler.to_html(custom_title="My Title")\n\n\ndef test_from_custom_template_style(tmpdir):\n p = tmpdir.mkdir("tpl").join("myhtml_style.tpl")\n p.write(\n dedent(\n """\\n {% extends "html_style.tpl" %}\n {% block style %}\n <link rel="stylesheet" href="mystyle.css">\n {{ super() }}\n {% endblock style %}"""\n )\n )\n result = Styler.from_custom_template(\n str(tmpdir.join("tpl")), html_style="myhtml_style.tpl"\n )\n assert issubclass(result, Styler)\n assert result.env is not Styler.env\n assert result.template_html_style is not Styler.template_html_style\n styler = result(DataFrame({"A": [1, 2]}))\n assert '<link rel="stylesheet" href="mystyle.css">\n\n<style' in styler.to_html()\n\n\ndef test_caption_as_sequence(styler):\n styler.set_caption(("full cap", "short cap"))\n assert "<caption>full cap</caption>" in styler.to_html()\n\n\n@pytest.mark.parametrize("index", [False, True])\n@pytest.mark.parametrize("columns", [False, True])\n@pytest.mark.parametrize("index_name", [True, False])\ndef test_sticky_basic(styler, index, columns, index_name):\n if index_name:\n styler.index.name = "some text"\n if index:\n styler.set_sticky(axis=0)\n if columns:\n styler.set_sticky(axis=1)\n\n left_css = (\n "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"\n " left: 0px;\n z-index: {1};\n}}"\n )\n top_css = (\n "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"\n " top: {1}px;\n z-index: {2};\n{3}}}"\n )\n\n res = styler.set_uuid("").to_html()\n\n # test index stickys over thead and tbody\n assert (left_css.format("thead tr th:nth-child(1)", "3 !important") in res) is index\n assert (left_css.format("tbody tr th:nth-child(1)", "1") in res) is index\n\n # test column stickys including if name row\n assert (\n top_css.format("thead tr:nth-child(1) th", "0", "2", " height: 25px;\n") in res\n ) is (columns and index_name)\n assert (\n top_css.format("thead tr:nth-child(2) th", "25", "2", " height: 25px;\n")\n in res\n ) is (columns and index_name)\n assert (top_css.format("thead tr:nth-child(1) th", "0", "2", "") in res) is (\n columns and not index_name\n )\n\n\n@pytest.mark.parametrize("index", [False, True])\n@pytest.mark.parametrize("columns", [False, True])\ndef test_sticky_mi(styler_mi, index, columns):\n if index:\n styler_mi.set_sticky(axis=0)\n if columns:\n styler_mi.set_sticky(axis=1)\n\n left_css = (\n "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"\n " left: {1}px;\n min-width: 75px;\n max-width: 75px;\n z-index: {2};\n}}"\n )\n top_css = (\n "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"\n " top: {1}px;\n height: 25px;\n z-index: {2};\n}}"\n )\n\n res = styler_mi.set_uuid("").to_html()\n\n # test the index stickys for thead and tbody over both levels\n assert (\n left_css.format("thead tr th:nth-child(1)", "0", "3 !important") in res\n ) is index\n assert (left_css.format("tbody tr th.level0", "0", "1") in res) is index\n assert (\n left_css.format("thead tr th:nth-child(2)", "75", "3 !important") in res\n ) is index\n assert (left_css.format("tbody tr th.level1", "75", "1") in res) is index\n\n # test the column stickys for each level row\n assert (top_css.format("thead tr:nth-child(1) th", "0", "2") in res) is columns\n assert (top_css.format("thead tr:nth-child(2) th", "25", "2") in res) is columns\n\n\n@pytest.mark.parametrize("index", [False, True])\n@pytest.mark.parametrize("columns", [False, True])\n@pytest.mark.parametrize("levels", [[1], ["one"], "one"])\ndef test_sticky_levels(styler_mi, index, columns, levels):\n styler_mi.index.names, styler_mi.columns.names = ["zero", "one"], ["zero", "one"]\n if index:\n styler_mi.set_sticky(axis=0, levels=levels)\n if columns:\n styler_mi.set_sticky(axis=1, levels=levels)\n\n left_css = (\n "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"\n " left: {1}px;\n min-width: 75px;\n max-width: 75px;\n z-index: {2};\n}}"\n )\n top_css = (\n "#T_ {0} {{\n position: sticky;\n background-color: inherit;\n"\n " top: {1}px;\n height: 25px;\n z-index: {2};\n}}"\n )\n\n res = styler_mi.set_uuid("").to_html()\n\n # test no sticking of level0\n assert "#T_ thead tr th:nth-child(1)" not in res\n assert "#T_ tbody tr th.level0" not in res\n assert "#T_ thead tr:nth-child(1) th" not in res\n\n # test sticking level1\n assert (\n left_css.format("thead tr th:nth-child(2)", "0", "3 !important") in res\n ) is index\n assert (left_css.format("tbody tr th.level1", "0", "1") in res) is index\n assert (top_css.format("thead tr:nth-child(2) th", "0", "2") in res) is columns\n\n\ndef test_sticky_raises(styler):\n with pytest.raises(ValueError, match="No axis named bad for object type DataFrame"):\n styler.set_sticky(axis="bad")\n\n\n@pytest.mark.parametrize(\n "sparse_index, sparse_columns",\n [(True, True), (True, False), (False, True), (False, False)],\n)\ndef test_sparse_options(sparse_index, sparse_columns):\n cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])\n ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])\n df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=ridx, columns=cidx)\n styler = df.style\n\n default_html = styler.to_html() # defaults under pd.options to (True , True)\n\n with option_context(\n "styler.sparse.index", sparse_index, "styler.sparse.columns", sparse_columns\n ):\n html1 = styler.to_html()\n assert (html1 == default_html) is (sparse_index and sparse_columns)\n html2 = styler.to_html(sparse_index=sparse_index, sparse_columns=sparse_columns)\n assert html1 == html2\n\n\n@pytest.mark.parametrize("index", [True, False])\n@pytest.mark.parametrize("columns", [True, False])\ndef test_map_header_cell_ids(styler, index, columns):\n # GH 41893\n func = lambda v: "attr: val;"\n styler.uuid, styler.cell_ids = "", False\n if index:\n styler.map_index(func, axis="index")\n if columns:\n styler.map_index(func, axis="columns")\n\n result = styler.to_html()\n\n # test no data cell ids\n assert '<td class="data row0 col0" >2.610000</td>' in result\n assert '<td class="data row1 col0" >2.690000</td>' in result\n\n # test index header ids where needed and css styles\n assert (\n '<th id="T__level0_row0" class="row_heading level0 row0" >a</th>' in result\n ) is index\n assert (\n '<th id="T__level0_row1" class="row_heading level0 row1" >b</th>' in result\n ) is index\n assert ("#T__level0_row0, #T__level0_row1 {\n attr: val;\n}" in result) is index\n\n # test column header ids where needed and css styles\n assert (\n '<th id="T__level0_col0" class="col_heading level0 col0" >A</th>' in result\n ) is columns\n assert ("#T__level0_col0 {\n attr: val;\n}" in result) is columns\n\n\n@pytest.mark.parametrize("rows", [True, False])\n@pytest.mark.parametrize("cols", [True, False])\ndef test_maximums(styler_mi, rows, cols):\n result = styler_mi.to_html(\n max_rows=2 if rows else None,\n max_columns=2 if cols else None,\n )\n\n assert ">5</td>" in result # [[0,1], [4,5]] always visible\n assert (">8</td>" in result) is not rows # first trimmed vertical element\n assert (">2</td>" in result) is not cols # first trimmed horizontal element\n\n\ndef test_replaced_css_class_names():\n css = {\n "row_heading": "ROWHEAD",\n # "col_heading": "COLHEAD",\n "index_name": "IDXNAME",\n # "col": "COL",\n "row": "ROW",\n # "col_trim": "COLTRIM",\n "row_trim": "ROWTRIM",\n "level": "LEVEL",\n "data": "DATA",\n "blank": "BLANK",\n }\n midx = MultiIndex.from_product([["a", "b"], ["c", "d"]])\n styler_mi = Styler(\n DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=midx),\n uuid_len=0,\n ).set_table_styles(css_class_names=css)\n styler_mi.index.names = ["n1", "n2"]\n styler_mi.hide(styler_mi.index[1:], axis=0)\n styler_mi.hide(styler_mi.columns[1:], axis=1)\n styler_mi.map_index(lambda v: "color: red;", axis=0)\n styler_mi.map_index(lambda v: "color: green;", axis=1)\n styler_mi.map(lambda v: "color: blue;")\n expected = dedent(\n """\\n <style type="text/css">\n #T__ROW0_col0 {\n color: blue;\n }\n #T__LEVEL0_ROW0, #T__LEVEL1_ROW0 {\n color: red;\n }\n #T__LEVEL0_col0, #T__LEVEL1_col0 {\n color: green;\n }\n </style>\n <table id="T_">\n <thead>\n <tr>\n <th class="BLANK" >&nbsp;</th>\n <th class="IDXNAME LEVEL0" >n1</th>\n <th id="T__LEVEL0_col0" class="col_heading LEVEL0 col0" >a</th>\n </tr>\n <tr>\n <th class="BLANK" >&nbsp;</th>\n <th class="IDXNAME LEVEL1" >n2</th>\n <th id="T__LEVEL1_col0" class="col_heading LEVEL1 col0" >c</th>\n </tr>\n <tr>\n <th class="IDXNAME LEVEL0" >n1</th>\n <th class="IDXNAME LEVEL1" >n2</th>\n <th class="BLANK col0" >&nbsp;</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th id="T__LEVEL0_ROW0" class="ROWHEAD LEVEL0 ROW0" >a</th>\n <th id="T__LEVEL1_ROW0" class="ROWHEAD LEVEL1 ROW0" >c</th>\n <td id="T__ROW0_col0" class="DATA ROW0 col0" >0</td>\n </tr>\n </tbody>\n </table>\n """\n )\n result = styler_mi.to_html()\n assert result == expected\n\n\ndef test_include_css_style_rules_only_for_visible_cells(styler_mi):\n # GH 43619\n result = (\n styler_mi.set_uuid("")\n .map(lambda v: "color: blue;")\n .hide(styler_mi.data.columns[1:], axis="columns")\n .hide(styler_mi.data.index[1:], axis="index")\n .to_html()\n )\n expected_styles = dedent(\n """\\n <style type="text/css">\n #T__row0_col0 {\n color: blue;\n }\n </style>\n """\n )\n assert expected_styles in result\n\n\ndef test_include_css_style_rules_only_for_visible_index_labels(styler_mi):\n # GH 43619\n result = (\n styler_mi.set_uuid("")\n .map_index(lambda v: "color: blue;", axis="index")\n .hide(styler_mi.data.columns, axis="columns")\n .hide(styler_mi.data.index[1:], axis="index")\n .to_html()\n )\n expected_styles = dedent(\n """\\n <style type="text/css">\n #T__level0_row0, #T__level1_row0 {\n color: blue;\n }\n </style>\n """\n )\n assert expected_styles in result\n\n\ndef test_include_css_style_rules_only_for_visible_column_labels(styler_mi):\n # GH 43619\n result = (\n styler_mi.set_uuid("")\n .map_index(lambda v: "color: blue;", axis="columns")\n .hide(styler_mi.data.columns[1:], axis="columns")\n .hide(styler_mi.data.index, axis="index")\n .to_html()\n )\n expected_styles = dedent(\n """\\n <style type="text/css">\n #T__level0_col0, #T__level1_col0 {\n color: blue;\n }\n </style>\n """\n )\n assert expected_styles in result\n\n\ndef test_hiding_index_columns_multiindex_alignment():\n # gh 43644\n midx = MultiIndex.from_product(\n [["i0", "j0"], ["i1"], ["i2", "j2"]], names=["i-0", "i-1", "i-2"]\n )\n cidx = MultiIndex.from_product(\n [["c0"], ["c1", "d1"], ["c2", "d2"]], names=["c-0", "c-1", "c-2"]\n )\n df = DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=cidx)\n styler = Styler(df, uuid_len=0)\n styler.hide(level=1, axis=0).hide(level=0, axis=1)\n styler.hide([("j0", "i1", "j2")], axis=0)\n styler.hide([("c0", "d1", "d2")], axis=1)\n result = styler.to_html()\n expected = dedent(\n """\\n <style type="text/css">\n </style>\n <table id="T_">\n <thead>\n <tr>\n <th class="blank" >&nbsp;</th>\n <th class="index_name level1" >c-1</th>\n <th id="T__level1_col0" class="col_heading level1 col0" colspan="2">c1</th>\n <th id="T__level1_col2" class="col_heading level1 col2" >d1</th>\n </tr>\n <tr>\n <th class="blank" >&nbsp;</th>\n <th class="index_name level2" >c-2</th>\n <th id="T__level2_col0" class="col_heading level2 col0" >c2</th>\n <th id="T__level2_col1" class="col_heading level2 col1" >d2</th>\n <th id="T__level2_col2" class="col_heading level2 col2" >c2</th>\n </tr>\n <tr>\n <th class="index_name level0" >i-0</th>\n <th class="index_name level2" >i-2</th>\n <th class="blank col0" >&nbsp;</th>\n <th class="blank col1" >&nbsp;</th>\n <th class="blank col2" >&nbsp;</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th id="T__level0_row0" class="row_heading level0 row0" rowspan="2">i0</th>\n <th id="T__level2_row0" class="row_heading level2 row0" >i2</th>\n <td id="T__row0_col0" class="data row0 col0" >0</td>\n <td id="T__row0_col1" class="data row0 col1" >1</td>\n <td id="T__row0_col2" class="data row0 col2" >2</td>\n </tr>\n <tr>\n <th id="T__level2_row1" class="row_heading level2 row1" >j2</th>\n <td id="T__row1_col0" class="data row1 col0" >4</td>\n <td id="T__row1_col1" class="data row1 col1" >5</td>\n <td id="T__row1_col2" class="data row1 col2" >6</td>\n </tr>\n <tr>\n <th id="T__level0_row2" class="row_heading level0 row2" >j0</th>\n <th id="T__level2_row2" class="row_heading level2 row2" >i2</th>\n <td id="T__row2_col0" class="data row2 col0" >8</td>\n <td id="T__row2_col1" class="data row2 col1" >9</td>\n <td id="T__row2_col2" class="data row2 col2" >10</td>\n </tr>\n </tbody>\n </table>\n """\n )\n assert result == expected\n\n\ndef test_hiding_index_columns_multiindex_trimming():\n # gh 44272\n df = DataFrame(np.arange(64).reshape(8, 8))\n df.columns = MultiIndex.from_product([[0, 1, 2, 3], [0, 1]])\n df.index = MultiIndex.from_product([[0, 1, 2, 3], [0, 1]])\n df.index.names, df.columns.names = ["a", "b"], ["c", "d"]\n styler = Styler(df, cell_ids=False, uuid_len=0)\n styler.hide([(0, 0), (0, 1), (1, 0)], axis=1).hide([(0, 0), (0, 1), (1, 0)], axis=0)\n with option_context("styler.render.max_rows", 4, "styler.render.max_columns", 4):\n result = styler.to_html()\n\n expected = dedent(\n """\\n <style type="text/css">\n </style>\n <table id="T_">\n <thead>\n <tr>\n <th class="blank" >&nbsp;</th>\n <th class="index_name level0" >c</th>\n <th class="col_heading level0 col3" >1</th>\n <th class="col_heading level0 col4" colspan="2">2</th>\n <th class="col_heading level0 col6" >3</th>\n </tr>\n <tr>\n <th class="blank" >&nbsp;</th>\n <th class="index_name level1" >d</th>\n <th class="col_heading level1 col3" >1</th>\n <th class="col_heading level1 col4" >0</th>\n <th class="col_heading level1 col5" >1</th>\n <th class="col_heading level1 col6" >0</th>\n <th class="col_heading level1 col_trim" >...</th>\n </tr>\n <tr>\n <th class="index_name level0" >a</th>\n <th class="index_name level1" >b</th>\n <th class="blank col3" >&nbsp;</th>\n <th class="blank col4" >&nbsp;</th>\n <th class="blank col5" >&nbsp;</th>\n <th class="blank col6" >&nbsp;</th>\n <th class="blank col7 col_trim" >&nbsp;</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th class="row_heading level0 row3" >1</th>\n <th class="row_heading level1 row3" >1</th>\n <td class="data row3 col3" >27</td>\n <td class="data row3 col4" >28</td>\n <td class="data row3 col5" >29</td>\n <td class="data row3 col6" >30</td>\n <td class="data row3 col_trim" >...</td>\n </tr>\n <tr>\n <th class="row_heading level0 row4" rowspan="2">2</th>\n <th class="row_heading level1 row4" >0</th>\n <td class="data row4 col3" >35</td>\n <td class="data row4 col4" >36</td>\n <td class="data row4 col5" >37</td>\n <td class="data row4 col6" >38</td>\n <td class="data row4 col_trim" >...</td>\n </tr>\n <tr>\n <th class="row_heading level1 row5" >1</th>\n <td class="data row5 col3" >43</td>\n <td class="data row5 col4" >44</td>\n <td class="data row5 col5" >45</td>\n <td class="data row5 col6" >46</td>\n <td class="data row5 col_trim" >...</td>\n </tr>\n <tr>\n <th class="row_heading level0 row6" >3</th>\n <th class="row_heading level1 row6" >0</th>\n <td class="data row6 col3" >51</td>\n <td class="data row6 col4" >52</td>\n <td class="data row6 col5" >53</td>\n <td class="data row6 col6" >54</td>\n <td class="data row6 col_trim" >...</td>\n </tr>\n <tr>\n <th class="row_heading level0 row_trim" >...</th>\n <th class="row_heading level1 row_trim" >...</th>\n <td class="data col3 row_trim" >...</td>\n <td class="data col4 row_trim" >...</td>\n <td class="data col5 row_trim" >...</td>\n <td class="data col6 row_trim" >...</td>\n <td class="data row_trim col_trim" >...</td>\n </tr>\n </tbody>\n </table>\n """\n )\n\n assert result == expected\n\n\n@pytest.mark.parametrize("type", ["data", "index"])\n@pytest.mark.parametrize(\n "text, exp, found",\n [\n ("no link, just text", False, ""),\n ("subdomain not www: sub.web.com", False, ""),\n ("www subdomain: www.web.com other", True, "www.web.com"),\n ("scheme full structure: http://www.web.com", True, "http://www.web.com"),\n ("scheme no top-level: http://www.web", True, "http://www.web"),\n ("no scheme, no top-level: www.web", False, "www.web"),\n ("https scheme: https://www.web.com", True, "https://www.web.com"),\n ("ftp scheme: ftp://www.web", True, "ftp://www.web"),\n ("ftps scheme: ftps://www.web", True, "ftps://www.web"),\n ("subdirectories: www.web.com/directory", True, "www.web.com/directory"),\n ("Multiple domains: www.1.2.3.4", True, "www.1.2.3.4"),\n ("with port: http://web.com:80", True, "http://web.com:80"),\n (\n "full net_loc scheme: http://user:pass@web.com",\n True,\n "http://user:pass@web.com",\n ),\n (\n "with valid special chars: http://web.com/,.':;~!@#$*()[]",\n True,\n "http://web.com/,.':;~!@#$*()[]",\n ),\n ],\n)\ndef test_rendered_links(type, text, exp, found):\n if type == "data":\n df = DataFrame([text])\n styler = df.style.format(hyperlinks="html")\n else:\n df = DataFrame([0], index=[text])\n styler = df.style.format_index(hyperlinks="html")\n\n rendered = f'<a href="{found}" target="_blank">{found}</a>'\n result = styler.to_html()\n assert (rendered in result) is exp\n assert (text in result) is not exp # test conversion done when expected and not\n\n\ndef test_multiple_rendered_links():\n links = ("www.a.b", "http://a.c", "https://a.d", "ftp://a.e")\n # pylint: disable-next=consider-using-f-string\n df = DataFrame(["text {} {} text {} {}".format(*links)])\n result = df.style.format(hyperlinks="html").to_html()\n href = '<a href="{0}" target="_blank">{0}</a>'\n for link in links:\n assert href.format(link) in result\n assert href.format("text") not in result\n\n\ndef test_concat(styler):\n other = styler.data.agg(["mean"]).style\n styler.concat(other).set_uuid("X")\n result = styler.to_html()\n fp = "foot0_"\n expected = dedent(\n f"""\\n <tr>\n <th id="T_X_level0_row1" class="row_heading level0 row1" >b</th>\n <td id="T_X_row1_col0" class="data row1 col0" >2.690000</td>\n </tr>\n <tr>\n <th id="T_X_level0_{fp}row0" class="{fp}row_heading level0 {fp}row0" >mean</th>\n <td id="T_X_{fp}row0_col0" class="{fp}data {fp}row0 col0" >2.650000</td>\n </tr>\n </tbody>\n</table>\n """\n )\n assert expected in result\n\n\ndef test_concat_recursion(styler):\n df = styler.data\n styler1 = styler\n styler2 = Styler(df.agg(["mean"]), precision=3)\n styler3 = Styler(df.agg(["mean"]), precision=4)\n styler1.concat(styler2.concat(styler3)).set_uuid("X")\n result = styler.to_html()\n # notice that the second concat (last <tr> of the output html),\n # there are two `foot_` in the id and class\n fp1 = "foot0_"\n fp2 = "foot0_foot0_"\n expected = dedent(\n f"""\\n <tr>\n <th id="T_X_level0_row1" class="row_heading level0 row1" >b</th>\n <td id="T_X_row1_col0" class="data row1 col0" >2.690000</td>\n </tr>\n <tr>\n <th id="T_X_level0_{fp1}row0" class="{fp1}row_heading level0 {fp1}row0" >mean</th>\n <td id="T_X_{fp1}row0_col0" class="{fp1}data {fp1}row0 col0" >2.650</td>\n </tr>\n <tr>\n <th id="T_X_level0_{fp2}row0" class="{fp2}row_heading level0 {fp2}row0" >mean</th>\n <td id="T_X_{fp2}row0_col0" class="{fp2}data {fp2}row0 col0" >2.6500</td>\n </tr>\n </tbody>\n</table>\n """\n )\n assert expected in result\n\n\ndef test_concat_chain(styler):\n df = styler.data\n styler1 = styler\n styler2 = Styler(df.agg(["mean"]), precision=3)\n styler3 = Styler(df.agg(["mean"]), precision=4)\n styler1.concat(styler2).concat(styler3).set_uuid("X")\n result = styler.to_html()\n fp1 = "foot0_"\n fp2 = "foot1_"\n expected = dedent(\n f"""\\n <tr>\n <th id="T_X_level0_row1" class="row_heading level0 row1" >b</th>\n <td id="T_X_row1_col0" class="data row1 col0" >2.690000</td>\n </tr>\n <tr>\n <th id="T_X_level0_{fp1}row0" class="{fp1}row_heading level0 {fp1}row0" >mean</th>\n <td id="T_X_{fp1}row0_col0" class="{fp1}data {fp1}row0 col0" >2.650</td>\n </tr>\n <tr>\n <th id="T_X_level0_{fp2}row0" class="{fp2}row_heading level0 {fp2}row0" >mean</th>\n <td id="T_X_{fp2}row0_col0" class="{fp2}data {fp2}row0 col0" >2.6500</td>\n </tr>\n </tbody>\n</table>\n """\n )\n assert expected in result\n\n\ndef test_concat_combined():\n def html_lines(foot_prefix: str):\n assert foot_prefix.endswith("_") or foot_prefix == ""\n fp = foot_prefix\n return indent(\n dedent(\n f"""\\n <tr>\n <th id="T_X_level0_{fp}row0" class="{fp}row_heading level0 {fp}row0" >a</th>\n <td id="T_X_{fp}row0_col0" class="{fp}data {fp}row0 col0" >2.610000</td>\n </tr>\n <tr>\n <th id="T_X_level0_{fp}row1" class="{fp}row_heading level0 {fp}row1" >b</th>\n <td id="T_X_{fp}row1_col0" class="{fp}data {fp}row1 col0" >2.690000</td>\n </tr>\n """\n ),\n prefix=" " * 4,\n )\n\n df = DataFrame([[2.61], [2.69]], index=["a", "b"], columns=["A"])\n s1 = df.style.highlight_max(color="red")\n s2 = df.style.highlight_max(color="green")\n s3 = df.style.highlight_max(color="blue")\n s4 = df.style.highlight_max(color="yellow")\n\n result = s1.concat(s2).concat(s3.concat(s4)).set_uuid("X").to_html()\n expected_css = dedent(\n """\\n <style type="text/css">\n #T_X_row1_col0 {\n background-color: red;\n }\n #T_X_foot0_row1_col0 {\n background-color: green;\n }\n #T_X_foot1_row1_col0 {\n background-color: blue;\n }\n #T_X_foot1_foot0_row1_col0 {\n background-color: yellow;\n }\n </style>\n """\n )\n expected_table = (\n dedent(\n """\\n <table id="T_X">\n <thead>\n <tr>\n <th class="blank level0" >&nbsp;</th>\n <th id="T_X_level0_col0" class="col_heading level0 col0" >A</th>\n </tr>\n </thead>\n <tbody>\n """\n )\n + html_lines("")\n + html_lines("foot0_")\n + html_lines("foot1_")\n + html_lines("foot1_foot0_")\n + dedent(\n """\\n </tbody>\n </table>\n """\n )\n )\n assert expected_css + expected_table == result\n\n\ndef test_to_html_na_rep_non_scalar_data(datapath):\n # GH47103\n df = DataFrame([{"a": 1, "b": [1, 2, 3], "c": np.nan}])\n result = df.style.format(na_rep="-").to_html(table_uuid="test")\n expected = """\\n<style type="text/css">\n</style>\n<table id="T_test">\n <thead>\n <tr>\n <th class="blank level0" >&nbsp;</th>\n <th id="T_test_level0_col0" class="col_heading level0 col0" >a</th>\n <th id="T_test_level0_col1" class="col_heading level0 col1" >b</th>\n <th id="T_test_level0_col2" class="col_heading level0 col2" >c</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th id="T_test_level0_row0" class="row_heading level0 row0" >0</th>\n <td id="T_test_row0_col0" class="data row0 col0" >1</td>\n <td id="T_test_row0_col1" class="data row0 col1" >[1, 2, 3]</td>\n <td id="T_test_row0_col2" class="data row0 col2" >-</td>\n </tr>\n </tbody>\n</table>\n"""\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_html.py
test_html.py
Python
32,702
0.95
0.20218
0.044297
node-utils
235
2023-10-19T19:55:23.974233
BSD-3-Clause
true
d293a6a9e5231ac98111ffcf67467e66
import gc\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n IndexSlice,\n Series,\n)\n\npytest.importorskip("matplotlib")\npytest.importorskip("jinja2")\n\nimport matplotlib as mpl\n\nfrom pandas.io.formats.style import Styler\n\n\n@pytest.fixture(autouse=True)\ndef mpl_cleanup():\n # matplotlib/testing/decorators.py#L24\n # 1) Resets units registry\n # 2) Resets rc_context\n # 3) Closes all figures\n mpl = pytest.importorskip("matplotlib")\n mpl_units = pytest.importorskip("matplotlib.units")\n plt = pytest.importorskip("matplotlib.pyplot")\n orig_units_registry = mpl_units.registry.copy()\n with mpl.rc_context():\n mpl.use("template")\n yield\n mpl_units.registry.clear()\n mpl_units.registry.update(orig_units_registry)\n plt.close("all")\n # https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.6.0.html#garbage-collection-is-no-longer-run-on-figure-close # noqa: E501\n gc.collect(1)\n\n\n@pytest.fixture\ndef df():\n return DataFrame([[1, 2], [2, 4]], columns=["A", "B"])\n\n\n@pytest.fixture\ndef styler(df):\n return Styler(df, uuid_len=0)\n\n\n@pytest.fixture\ndef df_blank():\n return DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"])\n\n\n@pytest.fixture\ndef styler_blank(df_blank):\n return Styler(df_blank, uuid_len=0)\n\n\n@pytest.mark.parametrize("f", ["background_gradient", "text_gradient"])\ndef test_function_gradient(styler, f):\n for c_map in [None, "YlOrRd"]:\n result = getattr(styler, f)(cmap=c_map)._compute().ctx\n assert all("#" in x[0][1] for x in result.values())\n assert result[(0, 0)] == result[(0, 1)]\n assert result[(1, 0)] == result[(1, 1)]\n\n\n@pytest.mark.parametrize("f", ["background_gradient", "text_gradient"])\ndef test_background_gradient_color(styler, f):\n result = getattr(styler, f)(subset=IndexSlice[1, "A"])._compute().ctx\n if f == "background_gradient":\n assert result[(1, 0)] == [("background-color", "#fff7fb"), ("color", "#000000")]\n elif f == "text_gradient":\n assert result[(1, 0)] == [("color", "#fff7fb")]\n\n\n@pytest.mark.parametrize(\n "axis, expected",\n [\n (0, ["low", "low", "high", "high"]),\n (1, ["low", "high", "low", "high"]),\n (None, ["low", "mid", "mid", "high"]),\n ],\n)\n@pytest.mark.parametrize("f", ["background_gradient", "text_gradient"])\ndef test_background_gradient_axis(styler, axis, expected, f):\n if f == "background_gradient":\n colors = {\n "low": [("background-color", "#f7fbff"), ("color", "#000000")],\n "mid": [("background-color", "#abd0e6"), ("color", "#000000")],\n "high": [("background-color", "#08306b"), ("color", "#f1f1f1")],\n }\n elif f == "text_gradient":\n colors = {\n "low": [("color", "#f7fbff")],\n "mid": [("color", "#abd0e6")],\n "high": [("color", "#08306b")],\n }\n result = getattr(styler, f)(cmap="Blues", axis=axis)._compute().ctx\n for i, cell in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]):\n assert result[cell] == colors[expected[i]]\n\n\n@pytest.mark.parametrize(\n "cmap, expected",\n [\n (\n "PuBu",\n {\n (4, 5): [("background-color", "#86b0d3"), ("color", "#000000")],\n (4, 6): [("background-color", "#83afd3"), ("color", "#f1f1f1")],\n },\n ),\n (\n "YlOrRd",\n {\n (4, 8): [("background-color", "#fd913e"), ("color", "#000000")],\n (4, 9): [("background-color", "#fd8f3d"), ("color", "#f1f1f1")],\n },\n ),\n (\n None,\n {\n (7, 0): [("background-color", "#48c16e"), ("color", "#f1f1f1")],\n (7, 1): [("background-color", "#4cc26c"), ("color", "#000000")],\n },\n ),\n ],\n)\ndef test_text_color_threshold(cmap, expected):\n # GH 39888\n df = DataFrame(np.arange(100).reshape(10, 10))\n result = df.style.background_gradient(cmap=cmap, axis=None)._compute().ctx\n for k in expected.keys():\n assert result[k] == expected[k]\n\n\ndef test_background_gradient_vmin_vmax():\n # GH 12145\n df = DataFrame(range(5))\n ctx = df.style.background_gradient(vmin=1, vmax=3)._compute().ctx\n assert ctx[(0, 0)] == ctx[(1, 0)]\n assert ctx[(4, 0)] == ctx[(3, 0)]\n\n\ndef test_background_gradient_int64():\n # GH 28869\n df1 = Series(range(3)).to_frame()\n df2 = Series(range(3), dtype="Int64").to_frame()\n ctx1 = df1.style.background_gradient()._compute().ctx\n ctx2 = df2.style.background_gradient()._compute().ctx\n assert ctx2[(0, 0)] == ctx1[(0, 0)]\n assert ctx2[(1, 0)] == ctx1[(1, 0)]\n assert ctx2[(2, 0)] == ctx1[(2, 0)]\n\n\n@pytest.mark.parametrize(\n "axis, gmap, expected",\n [\n (\n 0,\n [1, 2],\n {\n (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")],\n (1, 0): [("background-color", "#023858"), ("color", "#f1f1f1")],\n (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")],\n (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],\n },\n ),\n (\n 1,\n [1, 2],\n {\n (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")],\n (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")],\n (0, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],\n (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],\n },\n ),\n (\n None,\n np.array([[2, 1], [1, 2]]),\n {\n (0, 0): [("background-color", "#023858"), ("color", "#f1f1f1")],\n (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")],\n (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")],\n (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],\n },\n ),\n ],\n)\ndef test_background_gradient_gmap_array(styler_blank, axis, gmap, expected):\n # tests when gmap is given as a sequence and converted to ndarray\n result = styler_blank.background_gradient(axis=axis, gmap=gmap)._compute().ctx\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "gmap, axis", [([1, 2, 3], 0), ([1, 2], 1), (np.array([[1, 2], [1, 2]]), None)]\n)\ndef test_background_gradient_gmap_array_raises(gmap, axis):\n # test when gmap as converted ndarray is bad shape\n df = DataFrame([[0, 0, 0], [0, 0, 0]])\n msg = "supplied 'gmap' is not correct shape"\n with pytest.raises(ValueError, match=msg):\n df.style.background_gradient(gmap=gmap, axis=axis)._compute()\n\n\n@pytest.mark.parametrize(\n "gmap",\n [\n DataFrame( # reverse the columns\n [[2, 1], [1, 2]], columns=["B", "A"], index=["X", "Y"]\n ),\n DataFrame( # reverse the index\n [[2, 1], [1, 2]], columns=["A", "B"], index=["Y", "X"]\n ),\n DataFrame( # reverse the index and columns\n [[1, 2], [2, 1]], columns=["B", "A"], index=["Y", "X"]\n ),\n DataFrame( # add unnecessary columns\n [[1, 2, 3], [2, 1, 3]], columns=["A", "B", "C"], index=["X", "Y"]\n ),\n DataFrame( # add unnecessary index\n [[1, 2], [2, 1], [3, 3]], columns=["A", "B"], index=["X", "Y", "Z"]\n ),\n ],\n)\n@pytest.mark.parametrize(\n "subset, exp_gmap", # exp_gmap is underlying map DataFrame should conform to\n [\n (None, [[1, 2], [2, 1]]),\n (["A"], [[1], [2]]), # slice only column "A" in data and gmap\n (["B", "A"], [[2, 1], [1, 2]]), # reverse the columns in data\n (IndexSlice["X", :], [[1, 2]]), # slice only index "X" in data and gmap\n (IndexSlice[["Y", "X"], :], [[2, 1], [1, 2]]), # reverse the index in data\n ],\n)\ndef test_background_gradient_gmap_dataframe_align(styler_blank, gmap, subset, exp_gmap):\n # test gmap given as DataFrame that it aligns to the data including subset\n expected = styler_blank.background_gradient(axis=None, gmap=exp_gmap, subset=subset)\n result = styler_blank.background_gradient(axis=None, gmap=gmap, subset=subset)\n assert expected._compute().ctx == result._compute().ctx\n\n\n@pytest.mark.parametrize(\n "gmap, axis, exp_gmap",\n [\n (Series([2, 1], index=["Y", "X"]), 0, [[1, 1], [2, 2]]), # revrse the index\n (Series([2, 1], index=["B", "A"]), 1, [[1, 2], [1, 2]]), # revrse the cols\n (Series([1, 2, 3], index=["X", "Y", "Z"]), 0, [[1, 1], [2, 2]]), # add idx\n (Series([1, 2, 3], index=["A", "B", "C"]), 1, [[1, 2], [1, 2]]), # add col\n ],\n)\ndef test_background_gradient_gmap_series_align(styler_blank, gmap, axis, exp_gmap):\n # test gmap given as Series that it aligns to the data including subset\n expected = styler_blank.background_gradient(axis=None, gmap=exp_gmap)._compute()\n result = styler_blank.background_gradient(axis=axis, gmap=gmap)._compute()\n assert expected.ctx == result.ctx\n\n\n@pytest.mark.parametrize(\n "gmap, axis",\n [\n (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 1),\n (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 0),\n ],\n)\ndef test_background_gradient_gmap_wrong_dataframe(styler_blank, gmap, axis):\n # test giving a gmap in DataFrame but with wrong axis\n msg = "'gmap' is a DataFrame but underlying data for operations is a Series"\n with pytest.raises(ValueError, match=msg):\n styler_blank.background_gradient(gmap=gmap, axis=axis)._compute()\n\n\ndef test_background_gradient_gmap_wrong_series(styler_blank):\n # test giving a gmap in Series form but with wrong axis\n msg = "'gmap' is a Series but underlying data for operations is a DataFrame"\n gmap = Series([1, 2], index=["X", "Y"])\n with pytest.raises(ValueError, match=msg):\n styler_blank.background_gradient(gmap=gmap, axis=None)._compute()\n\n\ndef test_background_gradient_nullable_dtypes():\n # GH 50712\n df1 = DataFrame([[1], [0], [np.nan]], dtype=float)\n df2 = DataFrame([[1], [0], [None]], dtype="Int64")\n\n ctx1 = df1.style.background_gradient()._compute().ctx\n ctx2 = df2.style.background_gradient()._compute().ctx\n assert ctx1 == ctx2\n\n\n@pytest.mark.parametrize(\n "cmap",\n ["PuBu", mpl.colormaps["PuBu"]],\n)\ndef test_bar_colormap(cmap):\n data = DataFrame([[1, 2], [3, 4]])\n ctx = data.style.bar(cmap=cmap, axis=None)._compute().ctx\n pubu_colors = {\n (0, 0): "#d0d1e6",\n (1, 0): "#056faf",\n (0, 1): "#73a9cf",\n (1, 1): "#023858",\n }\n for k, v in pubu_colors.items():\n assert v in ctx[k][1][1]\n\n\ndef test_bar_color_raises(df):\n msg = "`color` must be string or list or tuple of 2 strings"\n with pytest.raises(ValueError, match=msg):\n df.style.bar(color={"a", "b"}).to_html()\n with pytest.raises(ValueError, match=msg):\n df.style.bar(color=["a", "b", "c"]).to_html()\n\n msg = "`color` and `cmap` cannot both be given"\n with pytest.raises(ValueError, match=msg):\n df.style.bar(color="something", cmap="something else").to_html()\n\n\n@pytest.mark.parametrize(\n "plot_method",\n ["scatter", "hexbin"],\n)\ndef test_pass_colormap_instance(df, plot_method):\n # https://github.com/pandas-dev/pandas/issues/49374\n cmap = mpl.colors.ListedColormap([[1, 1, 1], [0, 0, 0]])\n df["c"] = df.A + df.B\n kwargs = {"x": "A", "y": "B", "c": "c", "colormap": cmap}\n if plot_method == "hexbin":\n kwargs["C"] = kwargs.pop("c")\n getattr(df.plot, plot_method)(**kwargs)\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_matplotlib.py
test_matplotlib.py
Python
11,649
0.95
0.092537
0.055944
vue-tools
483
2024-11-23T21:38:58.034752
BSD-3-Clause
true
fbe2bec1bb6b0da0437e9c704b465091
from textwrap import dedent\n\nimport pytest\n\nfrom pandas import (\n DataFrame,\n IndexSlice,\n)\n\npytest.importorskip("jinja2")\n\nfrom pandas.io.formats.style import Styler\n\n\n@pytest.fixture\ndef df():\n return DataFrame(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n index=["i", "j", "j"],\n columns=["c", "d", "d"],\n dtype=float,\n )\n\n\n@pytest.fixture\ndef styler(df):\n return Styler(df, uuid_len=0)\n\n\ndef test_format_non_unique(df):\n # GH 41269\n\n # test dict\n html = df.style.format({"d": "{:.1f}"}).to_html()\n for val in ["1.000000<", "4.000000<", "7.000000<"]:\n assert val in html\n for val in ["2.0<", "3.0<", "5.0<", "6.0<", "8.0<", "9.0<"]:\n assert val in html\n\n # test subset\n html = df.style.format(precision=1, subset=IndexSlice["j", "d"]).to_html()\n for val in ["1.000000<", "4.000000<", "7.000000<", "2.000000<", "3.000000<"]:\n assert val in html\n for val in ["5.0<", "6.0<", "8.0<", "9.0<"]:\n assert val in html\n\n\n@pytest.mark.parametrize("func", ["apply", "map"])\ndef test_apply_map_non_unique_raises(df, func):\n # GH 41269\n if func == "apply":\n op = lambda s: ["color: red;"] * len(s)\n else:\n op = lambda v: "color: red;"\n\n with pytest.raises(KeyError, match="`Styler.apply` and `.map` are not"):\n getattr(df.style, func)(op)._compute()\n\n\ndef test_table_styles_dict_non_unique_index(styler):\n styles = styler.set_table_styles(\n {"j": [{"selector": "td", "props": "a: v;"}]}, axis=1\n ).table_styles\n assert styles == [\n {"selector": "td.row1", "props": [("a", "v")]},\n {"selector": "td.row2", "props": [("a", "v")]},\n ]\n\n\ndef test_table_styles_dict_non_unique_columns(styler):\n styles = styler.set_table_styles(\n {"d": [{"selector": "td", "props": "a: v;"}]}, axis=0\n ).table_styles\n assert styles == [\n {"selector": "td.col1", "props": [("a", "v")]},\n {"selector": "td.col2", "props": [("a", "v")]},\n ]\n\n\ndef test_tooltips_non_unique_raises(styler):\n # ttips has unique keys\n ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"])\n styler.set_tooltips(ttips=ttips) # OK\n\n # ttips has non-unique columns\n ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"])\n with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"):\n styler.set_tooltips(ttips=ttips)\n\n # ttips has non-unique index\n ttips = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"])\n with pytest.raises(KeyError, match="Tooltips render only if `ttips` has unique"):\n styler.set_tooltips(ttips=ttips)\n\n\ndef test_set_td_classes_non_unique_raises(styler):\n # classes has unique keys\n classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "b"])\n styler.set_td_classes(classes=classes) # OK\n\n # classes has non-unique columns\n classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "c"], index=["a", "b"])\n with pytest.raises(KeyError, match="Classes render only if `classes` has unique"):\n styler.set_td_classes(classes=classes)\n\n # classes has non-unique index\n classes = DataFrame([["1", "2"], ["3", "4"]], columns=["c", "d"], index=["a", "a"])\n with pytest.raises(KeyError, match="Classes render only if `classes` has unique"):\n styler.set_td_classes(classes=classes)\n\n\ndef test_hide_columns_non_unique(styler):\n ctx = styler.hide(["d"], axis="columns")._translate(True, True)\n\n assert ctx["head"][0][1]["display_value"] == "c"\n assert ctx["head"][0][1]["is_visible"] is True\n\n assert ctx["head"][0][2]["display_value"] == "d"\n assert ctx["head"][0][2]["is_visible"] is False\n\n assert ctx["head"][0][3]["display_value"] == "d"\n assert ctx["head"][0][3]["is_visible"] is False\n\n assert ctx["body"][0][1]["is_visible"] is True\n assert ctx["body"][0][2]["is_visible"] is False\n assert ctx["body"][0][3]["is_visible"] is False\n\n\ndef test_latex_non_unique(styler):\n result = styler.to_latex()\n assert result == dedent(\n """\\n \\begin{tabular}{lrrr}\n & c & d & d \\\\\n i & 1.000000 & 2.000000 & 3.000000 \\\\\n j & 4.000000 & 5.000000 & 6.000000 \\\\\n j & 7.000000 & 8.000000 & 9.000000 \\\\\n \\end{tabular}\n """\n )\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_non_unique.py
test_non_unique.py
Python
4,366
0.95
0.135714
0.095238
python-kit
282
2023-10-16T06:50:13.964244
MIT
true
ef0a397a2fe331d7cb7107248df9539b
import contextlib\nimport copy\nimport re\nfrom textwrap import dedent\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n IndexSlice,\n MultiIndex,\n Series,\n option_context,\n)\nimport pandas._testing as tm\n\njinja2 = pytest.importorskip("jinja2")\nfrom pandas.io.formats.style import ( # isort:skip\n Styler,\n)\nfrom pandas.io.formats.style_render import (\n _get_level_lengths,\n _get_trimming_maximums,\n maybe_convert_css_to_tuples,\n non_reducing_slice,\n)\n\n\n@pytest.fixture\ndef mi_df():\n return DataFrame(\n [[1, 2], [3, 4]],\n index=MultiIndex.from_product([["i0"], ["i1_a", "i1_b"]]),\n columns=MultiIndex.from_product([["c0"], ["c1_a", "c1_b"]]),\n dtype=int,\n )\n\n\n@pytest.fixture\ndef mi_styler(mi_df):\n return Styler(mi_df, uuid_len=0)\n\n\n@pytest.fixture\ndef mi_styler_comp(mi_styler):\n # comprehensively add features to mi_styler\n mi_styler = mi_styler._copy(deepcopy=True)\n mi_styler.css = {**mi_styler.css, "row": "ROW", "col": "COL"}\n mi_styler.uuid_len = 5\n mi_styler.uuid = "abcde"\n mi_styler.set_caption("capt")\n mi_styler.set_table_styles([{"selector": "a", "props": "a:v;"}])\n mi_styler.hide(axis="columns")\n mi_styler.hide([("c0", "c1_a")], axis="columns", names=True)\n mi_styler.hide(axis="index")\n mi_styler.hide([("i0", "i1_a")], axis="index", names=True)\n mi_styler.set_table_attributes('class="box"')\n other = mi_styler.data.agg(["mean"])\n other.index = MultiIndex.from_product([[""], other.index])\n mi_styler.concat(other.style)\n mi_styler.format(na_rep="MISSING", precision=3)\n mi_styler.format_index(precision=2, axis=0)\n mi_styler.format_index(precision=4, axis=1)\n mi_styler.highlight_max(axis=None)\n mi_styler.map_index(lambda x: "color: white;", axis=0)\n mi_styler.map_index(lambda x: "color: black;", axis=1)\n mi_styler.set_td_classes(\n DataFrame(\n [["a", "b"], ["a", "c"]], index=mi_styler.index, columns=mi_styler.columns\n )\n )\n mi_styler.set_tooltips(\n DataFrame(\n [["a2", "b2"], ["a2", "c2"]],\n index=mi_styler.index,\n columns=mi_styler.columns,\n )\n )\n return mi_styler\n\n\n@pytest.fixture\ndef blank_value():\n return "&nbsp;"\n\n\n@pytest.fixture\ndef df():\n df = DataFrame({"A": [0, 1], "B": np.random.default_rng(2).standard_normal(2)})\n return df\n\n\n@pytest.fixture\ndef styler(df):\n df = DataFrame({"A": [0, 1], "B": np.random.default_rng(2).standard_normal(2)})\n return Styler(df)\n\n\n@pytest.mark.parametrize(\n "sparse_columns, exp_cols",\n [\n (\n True,\n [\n {"is_visible": True, "attributes": 'colspan="2"', "value": "c0"},\n {"is_visible": False, "attributes": "", "value": "c0"},\n ],\n ),\n (\n False,\n [\n {"is_visible": True, "attributes": "", "value": "c0"},\n {"is_visible": True, "attributes": "", "value": "c0"},\n ],\n ),\n ],\n)\ndef test_mi_styler_sparsify_columns(mi_styler, sparse_columns, exp_cols):\n exp_l1_c0 = {"is_visible": True, "attributes": "", "display_value": "c1_a"}\n exp_l1_c1 = {"is_visible": True, "attributes": "", "display_value": "c1_b"}\n\n ctx = mi_styler._translate(True, sparse_columns)\n\n assert exp_cols[0].items() <= ctx["head"][0][2].items()\n assert exp_cols[1].items() <= ctx["head"][0][3].items()\n assert exp_l1_c0.items() <= ctx["head"][1][2].items()\n assert exp_l1_c1.items() <= ctx["head"][1][3].items()\n\n\n@pytest.mark.parametrize(\n "sparse_index, exp_rows",\n [\n (\n True,\n [\n {"is_visible": True, "attributes": 'rowspan="2"', "value": "i0"},\n {"is_visible": False, "attributes": "", "value": "i0"},\n ],\n ),\n (\n False,\n [\n {"is_visible": True, "attributes": "", "value": "i0"},\n {"is_visible": True, "attributes": "", "value": "i0"},\n ],\n ),\n ],\n)\ndef test_mi_styler_sparsify_index(mi_styler, sparse_index, exp_rows):\n exp_l1_r0 = {"is_visible": True, "attributes": "", "display_value": "i1_a"}\n exp_l1_r1 = {"is_visible": True, "attributes": "", "display_value": "i1_b"}\n\n ctx = mi_styler._translate(sparse_index, True)\n\n assert exp_rows[0].items() <= ctx["body"][0][0].items()\n assert exp_rows[1].items() <= ctx["body"][1][0].items()\n assert exp_l1_r0.items() <= ctx["body"][0][1].items()\n assert exp_l1_r1.items() <= ctx["body"][1][1].items()\n\n\ndef test_mi_styler_sparsify_options(mi_styler):\n with option_context("styler.sparse.index", False):\n html1 = mi_styler.to_html()\n with option_context("styler.sparse.index", True):\n html2 = mi_styler.to_html()\n\n assert html1 != html2\n\n with option_context("styler.sparse.columns", False):\n html1 = mi_styler.to_html()\n with option_context("styler.sparse.columns", True):\n html2 = mi_styler.to_html()\n\n assert html1 != html2\n\n\n@pytest.mark.parametrize(\n "rn, cn, max_els, max_rows, max_cols, exp_rn, exp_cn",\n [\n (100, 100, 100, None, None, 12, 6), # reduce to (12, 6) < 100 elements\n (1000, 3, 750, None, None, 250, 3), # dynamically reduce rows to 250, keep cols\n (4, 1000, 500, None, None, 4, 125), # dynamically reduce cols to 125, keep rows\n (1000, 3, 750, 10, None, 10, 3), # overwrite above dynamics with max_row\n (4, 1000, 500, None, 5, 4, 5), # overwrite above dynamics with max_col\n (100, 100, 700, 50, 50, 25, 25), # rows cols below given maxes so < 700 elmts\n ],\n)\ndef test_trimming_maximum(rn, cn, max_els, max_rows, max_cols, exp_rn, exp_cn):\n rn, cn = _get_trimming_maximums(\n rn, cn, max_els, max_rows, max_cols, scaling_factor=0.5\n )\n assert (rn, cn) == (exp_rn, exp_cn)\n\n\n@pytest.mark.parametrize(\n "option, val",\n [\n ("styler.render.max_elements", 6),\n ("styler.render.max_rows", 3),\n ],\n)\ndef test_render_trimming_rows(option, val):\n # test auto and specific trimming of rows\n df = DataFrame(np.arange(120).reshape(60, 2))\n with option_context(option, val):\n ctx = df.style._translate(True, True)\n assert len(ctx["head"][0]) == 3 # index + 2 data cols\n assert len(ctx["body"]) == 4 # 3 data rows + trimming row\n assert len(ctx["body"][0]) == 3 # index + 2 data cols\n\n\n@pytest.mark.parametrize(\n "option, val",\n [\n ("styler.render.max_elements", 6),\n ("styler.render.max_columns", 2),\n ],\n)\ndef test_render_trimming_cols(option, val):\n # test auto and specific trimming of cols\n df = DataFrame(np.arange(30).reshape(3, 10))\n with option_context(option, val):\n ctx = df.style._translate(True, True)\n assert len(ctx["head"][0]) == 4 # index + 2 data cols + trimming col\n assert len(ctx["body"]) == 3 # 3 data rows\n assert len(ctx["body"][0]) == 4 # index + 2 data cols + trimming col\n\n\ndef test_render_trimming_mi():\n midx = MultiIndex.from_product([[1, 2], [1, 2, 3]])\n df = DataFrame(np.arange(36).reshape(6, 6), columns=midx, index=midx)\n with option_context("styler.render.max_elements", 4):\n ctx = df.style._translate(True, True)\n\n assert len(ctx["body"][0]) == 5 # 2 indexes + 2 data cols + trimming row\n assert {"attributes": 'rowspan="2"'}.items() <= ctx["body"][0][0].items()\n assert {"class": "data row0 col_trim"}.items() <= ctx["body"][0][4].items()\n assert {"class": "data row_trim col_trim"}.items() <= ctx["body"][2][4].items()\n assert len(ctx["body"]) == 3 # 2 data rows + trimming row\n\n\ndef test_render_empty_mi():\n # GH 43305\n df = DataFrame(index=MultiIndex.from_product([["A"], [0, 1]], names=[None, "one"]))\n expected = dedent(\n """\\n >\n <thead>\n <tr>\n <th class="index_name level0" >&nbsp;</th>\n <th class="index_name level1" >one</th>\n </tr>\n </thead>\n """\n )\n assert expected in df.style.to_html()\n\n\n@pytest.mark.parametrize("comprehensive", [True, False])\n@pytest.mark.parametrize("render", [True, False])\n@pytest.mark.parametrize("deepcopy", [True, False])\ndef test_copy(comprehensive, render, deepcopy, mi_styler, mi_styler_comp):\n styler = mi_styler_comp if comprehensive else mi_styler\n styler.uuid_len = 5\n\n s2 = copy.deepcopy(styler) if deepcopy else copy.copy(styler) # make copy and check\n assert s2 is not styler\n\n if render:\n styler.to_html()\n\n excl = [\n "cellstyle_map", # render time vars..\n "cellstyle_map_columns",\n "cellstyle_map_index",\n "template_latex", # render templates are class level\n "template_html",\n "template_html_style",\n "template_html_table",\n ]\n if not deepcopy: # check memory locations are equal for all included attributes\n for attr in [a for a in styler.__dict__ if (not callable(a) and a not in excl)]:\n assert id(getattr(s2, attr)) == id(getattr(styler, attr))\n else: # check memory locations are different for nested or mutable vars\n shallow = [\n "data",\n "columns",\n "index",\n "uuid_len",\n "uuid",\n "caption",\n "cell_ids",\n "hide_index_",\n "hide_columns_",\n "hide_index_names",\n "hide_column_names",\n "table_attributes",\n ]\n for attr in shallow:\n assert id(getattr(s2, attr)) == id(getattr(styler, attr))\n\n for attr in [\n a\n for a in styler.__dict__\n if (not callable(a) and a not in excl and a not in shallow)\n ]:\n if getattr(s2, attr) is None:\n assert id(getattr(s2, attr)) == id(getattr(styler, attr))\n else:\n assert id(getattr(s2, attr)) != id(getattr(styler, attr))\n\n\n@pytest.mark.parametrize("deepcopy", [True, False])\ndef test_inherited_copy(mi_styler, deepcopy):\n # Ensure that the inherited class is preserved when a Styler object is copied.\n # GH 52728\n class CustomStyler(Styler):\n pass\n\n custom_styler = CustomStyler(mi_styler.data)\n custom_styler_copy = (\n copy.deepcopy(custom_styler) if deepcopy else copy.copy(custom_styler)\n )\n assert isinstance(custom_styler_copy, CustomStyler)\n\n\ndef test_clear(mi_styler_comp):\n # NOTE: if this test fails for new features then 'mi_styler_comp' should be updated\n # to ensure proper testing of the 'copy', 'clear', 'export' methods with new feature\n # GH 40675\n styler = mi_styler_comp\n styler._compute() # execute applied methods\n\n clean_copy = Styler(styler.data, uuid=styler.uuid)\n\n excl = [\n "data",\n "index",\n "columns",\n "uuid",\n "uuid_len", # uuid is set to be the same on styler and clean_copy\n "cell_ids",\n "cellstyle_map", # execution time only\n "cellstyle_map_columns", # execution time only\n "cellstyle_map_index", # execution time only\n "template_latex", # render templates are class level\n "template_html",\n "template_html_style",\n "template_html_table",\n ]\n # tests vars are not same vals on obj and clean copy before clear (except for excl)\n for attr in [a for a in styler.__dict__ if not (callable(a) or a in excl)]:\n res = getattr(styler, attr) == getattr(clean_copy, attr)\n if hasattr(res, "__iter__") and len(res) > 0:\n assert not all(res) # some element in iterable differs\n elif hasattr(res, "__iter__") and len(res) == 0:\n pass # empty array\n else:\n assert not res # explicit var differs\n\n # test vars have same vales on obj and clean copy after clearing\n styler.clear()\n for attr in [a for a in styler.__dict__ if not callable(a)]:\n res = getattr(styler, attr) == getattr(clean_copy, attr)\n assert all(res) if hasattr(res, "__iter__") else res\n\n\ndef test_export(mi_styler_comp, mi_styler):\n exp_attrs = [\n "_todo",\n "hide_index_",\n "hide_index_names",\n "hide_columns_",\n "hide_column_names",\n "table_attributes",\n "table_styles",\n "css",\n ]\n for attr in exp_attrs:\n check = getattr(mi_styler, attr) == getattr(mi_styler_comp, attr)\n assert not (\n all(check) if (hasattr(check, "__iter__") and len(check) > 0) else check\n )\n\n export = mi_styler_comp.export()\n used = mi_styler.use(export)\n for attr in exp_attrs:\n check = getattr(used, attr) == getattr(mi_styler_comp, attr)\n assert all(check) if (hasattr(check, "__iter__") and len(check) > 0) else check\n\n used.to_html()\n\n\ndef test_hide_raises(mi_styler):\n msg = "`subset` and `level` cannot be passed simultaneously"\n with pytest.raises(ValueError, match=msg):\n mi_styler.hide(axis="index", subset="something", level="something else")\n\n msg = "`level` must be of type `int`, `str` or list of such"\n with pytest.raises(ValueError, match=msg):\n mi_styler.hide(axis="index", level={"bad": 1, "type": 2})\n\n\n@pytest.mark.parametrize("level", [1, "one", [1], ["one"]])\ndef test_hide_index_level(mi_styler, level):\n mi_styler.index.names, mi_styler.columns.names = ["zero", "one"], ["zero", "one"]\n ctx = mi_styler.hide(axis="index", level=level)._translate(False, True)\n assert len(ctx["head"][0]) == 3\n assert len(ctx["head"][1]) == 3\n assert len(ctx["head"][2]) == 4\n assert ctx["head"][2][0]["is_visible"]\n assert not ctx["head"][2][1]["is_visible"]\n\n assert ctx["body"][0][0]["is_visible"]\n assert not ctx["body"][0][1]["is_visible"]\n assert ctx["body"][1][0]["is_visible"]\n assert not ctx["body"][1][1]["is_visible"]\n\n\n@pytest.mark.parametrize("level", [1, "one", [1], ["one"]])\n@pytest.mark.parametrize("names", [True, False])\ndef test_hide_columns_level(mi_styler, level, names):\n mi_styler.columns.names = ["zero", "one"]\n if names:\n mi_styler.index.names = ["zero", "one"]\n ctx = mi_styler.hide(axis="columns", level=level)._translate(True, False)\n assert len(ctx["head"]) == (2 if names else 1)\n\n\n@pytest.mark.parametrize("method", ["map", "apply"])\n@pytest.mark.parametrize("axis", ["index", "columns"])\ndef test_apply_map_header(method, axis):\n # GH 41893\n df = DataFrame({"A": [0, 0], "B": [1, 1]}, index=["C", "D"])\n func = {\n "apply": lambda s: ["attr: val" if ("A" in v or "C" in v) else "" for v in s],\n "map": lambda v: "attr: val" if ("A" in v or "C" in v) else "",\n }\n\n # test execution added to todo\n result = getattr(df.style, f"{method}_index")(func[method], axis=axis)\n assert len(result._todo) == 1\n assert len(getattr(result, f"ctx_{axis}")) == 0\n\n # test ctx object on compute\n result._compute()\n expected = {\n (0, 0): [("attr", "val")],\n }\n assert getattr(result, f"ctx_{axis}") == expected\n\n\n@pytest.mark.parametrize("method", ["apply", "map"])\n@pytest.mark.parametrize("axis", ["index", "columns"])\ndef test_apply_map_header_mi(mi_styler, method, axis):\n # GH 41893\n func = {\n "apply": lambda s: ["attr: val;" if "b" in v else "" for v in s],\n "map": lambda v: "attr: val" if "b" in v else "",\n }\n result = getattr(mi_styler, f"{method}_index")(func[method], axis=axis)._compute()\n expected = {(1, 1): [("attr", "val")]}\n assert getattr(result, f"ctx_{axis}") == expected\n\n\ndef test_apply_map_header_raises(mi_styler):\n # GH 41893\n with pytest.raises(ValueError, match="No axis named bad for object type DataFrame"):\n mi_styler.map_index(lambda v: "attr: val;", axis="bad")._compute()\n\n\nclass TestStyler:\n def test_init_non_pandas(self):\n msg = "``data`` must be a Series or DataFrame"\n with pytest.raises(TypeError, match=msg):\n Styler([1, 2, 3])\n\n def test_init_series(self):\n result = Styler(Series([1, 2]))\n assert result.data.ndim == 2\n\n def test_repr_html_ok(self, styler):\n styler._repr_html_()\n\n def test_repr_html_mathjax(self, styler):\n # gh-19824 / 41395\n assert "tex2jax_ignore" not in styler._repr_html_()\n\n with option_context("styler.html.mathjax", False):\n assert "tex2jax_ignore" in styler._repr_html_()\n\n def test_update_ctx(self, styler):\n styler._update_ctx(DataFrame({"A": ["color: red", "color: blue"]}))\n expected = {(0, 0): [("color", "red")], (1, 0): [("color", "blue")]}\n assert styler.ctx == expected\n\n def test_update_ctx_flatten_multi_and_trailing_semi(self, styler):\n attrs = DataFrame({"A": ["color: red; foo: bar", "color:blue ; foo: baz;"]})\n styler._update_ctx(attrs)\n expected = {\n (0, 0): [("color", "red"), ("foo", "bar")],\n (1, 0): [("color", "blue"), ("foo", "baz")],\n }\n assert styler.ctx == expected\n\n def test_render(self):\n df = DataFrame({"A": [0, 1]})\n style = lambda x: Series(["color: red", "color: blue"], name=x.name)\n s = Styler(df, uuid="AB").apply(style)\n s.to_html()\n # it worked?\n\n def test_multiple_render(self, df):\n # GH 39396\n s = Styler(df, uuid_len=0).map(lambda x: "color: red;", subset=["A"])\n s.to_html() # do 2 renders to ensure css styles not duplicated\n assert (\n '<style type="text/css">\n#T__row0_col0, #T__row1_col0 {\n'\n " color: red;\n}\n</style>" in s.to_html()\n )\n\n def test_render_empty_dfs(self):\n empty_df = DataFrame()\n es = Styler(empty_df)\n es.to_html()\n # An index but no columns\n DataFrame(columns=["a"]).style.to_html()\n # A column but no index\n DataFrame(index=["a"]).style.to_html()\n # No IndexError raised?\n\n def test_render_double(self):\n df = DataFrame({"A": [0, 1]})\n style = lambda x: Series(\n ["color: red; border: 1px", "color: blue; border: 2px"], name=x.name\n )\n s = Styler(df, uuid="AB").apply(style)\n s.to_html()\n # it worked?\n\n def test_set_properties(self):\n df = DataFrame({"A": [0, 1]})\n result = df.style.set_properties(color="white", size="10px")._compute().ctx\n # order is deterministic\n v = [("color", "white"), ("size", "10px")]\n expected = {(0, 0): v, (1, 0): v}\n assert result.keys() == expected.keys()\n for v1, v2 in zip(result.values(), expected.values()):\n assert sorted(v1) == sorted(v2)\n\n def test_set_properties_subset(self):\n df = DataFrame({"A": [0, 1]})\n result = (\n df.style.set_properties(subset=IndexSlice[0, "A"], color="white")\n ._compute()\n .ctx\n )\n expected = {(0, 0): [("color", "white")]}\n assert result == expected\n\n def test_empty_index_name_doesnt_display(self, blank_value):\n # https://github.com/pandas-dev/pandas/pull/12090#issuecomment-180695902\n df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})\n result = df.style._translate(True, True)\n assert len(result["head"]) == 1\n expected = {\n "class": "blank level0",\n "type": "th",\n "value": blank_value,\n "is_visible": True,\n "display_value": blank_value,\n }\n assert expected.items() <= result["head"][0][0].items()\n\n def test_index_name(self):\n # https://github.com/pandas-dev/pandas/issues/11655\n df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})\n result = df.set_index("A").style._translate(True, True)\n expected = {\n "class": "index_name level0",\n "type": "th",\n "value": "A",\n "is_visible": True,\n "display_value": "A",\n }\n assert expected.items() <= result["head"][1][0].items()\n\n def test_numeric_columns(self):\n # https://github.com/pandas-dev/pandas/issues/12125\n # smoke test for _translate\n df = DataFrame({0: [1, 2, 3]})\n df.style._translate(True, True)\n\n def test_apply_axis(self):\n df = DataFrame({"A": [0, 0], "B": [1, 1]})\n f = lambda x: [f"val: {x.max()}" for v in x]\n result = df.style.apply(f, axis=1)\n assert len(result._todo) == 1\n assert len(result.ctx) == 0\n result._compute()\n expected = {\n (0, 0): [("val", "1")],\n (0, 1): [("val", "1")],\n (1, 0): [("val", "1")],\n (1, 1): [("val", "1")],\n }\n assert result.ctx == expected\n\n result = df.style.apply(f, axis=0)\n expected = {\n (0, 0): [("val", "0")],\n (0, 1): [("val", "1")],\n (1, 0): [("val", "0")],\n (1, 1): [("val", "1")],\n }\n result._compute()\n assert result.ctx == expected\n result = df.style.apply(f) # default\n result._compute()\n assert result.ctx == expected\n\n @pytest.mark.parametrize("axis", [0, 1])\n def test_apply_series_return(self, axis):\n # GH 42014\n df = DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"])\n\n # test Series return where len(Series) < df.index or df.columns but labels OK\n func = lambda s: Series(["color: red;"], index=["Y"])\n result = df.style.apply(func, axis=axis)._compute().ctx\n assert result[(1, 1)] == [("color", "red")]\n assert result[(1 - axis, axis)] == [("color", "red")]\n\n # test Series return where labels align but different order\n func = lambda s: Series(["color: red;", "color: blue;"], index=["Y", "X"])\n result = df.style.apply(func, axis=axis)._compute().ctx\n assert result[(0, 0)] == [("color", "blue")]\n assert result[(1, 1)] == [("color", "red")]\n assert result[(1 - axis, axis)] == [("color", "red")]\n assert result[(axis, 1 - axis)] == [("color", "blue")]\n\n @pytest.mark.parametrize("index", [False, True])\n @pytest.mark.parametrize("columns", [False, True])\n def test_apply_dataframe_return(self, index, columns):\n # GH 42014\n df = DataFrame([[1, 2], [3, 4]], index=["X", "Y"], columns=["X", "Y"])\n idxs = ["X", "Y"] if index else ["Y"]\n cols = ["X", "Y"] if columns else ["Y"]\n df_styles = DataFrame("color: red;", index=idxs, columns=cols)\n result = df.style.apply(lambda x: df_styles, axis=None)._compute().ctx\n\n assert result[(1, 1)] == [("color", "red")] # (Y,Y) styles always present\n assert (result[(0, 1)] == [("color", "red")]) is index # (X,Y) only if index\n assert (result[(1, 0)] == [("color", "red")]) is columns # (Y,X) only if cols\n assert (result[(0, 0)] == [("color", "red")]) is (index and columns) # (X,X)\n\n @pytest.mark.parametrize(\n "slice_",\n [\n IndexSlice[:],\n IndexSlice[:, ["A"]],\n IndexSlice[[1], :],\n IndexSlice[[1], ["A"]],\n IndexSlice[:2, ["A", "B"]],\n ],\n )\n @pytest.mark.parametrize("axis", [0, 1])\n def test_apply_subset(self, slice_, axis, df):\n def h(x, color="bar"):\n return Series(f"color: {color}", index=x.index, name=x.name)\n\n result = df.style.apply(h, axis=axis, subset=slice_, color="baz")._compute().ctx\n expected = {\n (r, c): [("color", "baz")]\n for r, row in enumerate(df.index)\n for c, col in enumerate(df.columns)\n if row in df.loc[slice_].index and col in df.loc[slice_].columns\n }\n assert result == expected\n\n @pytest.mark.parametrize(\n "slice_",\n [\n IndexSlice[:],\n IndexSlice[:, ["A"]],\n IndexSlice[[1], :],\n IndexSlice[[1], ["A"]],\n IndexSlice[:2, ["A", "B"]],\n ],\n )\n def test_map_subset(self, slice_, df):\n result = df.style.map(lambda x: "color:baz;", subset=slice_)._compute().ctx\n expected = {\n (r, c): [("color", "baz")]\n for r, row in enumerate(df.index)\n for c, col in enumerate(df.columns)\n if row in df.loc[slice_].index and col in df.loc[slice_].columns\n }\n assert result == expected\n\n @pytest.mark.parametrize(\n "slice_",\n [\n IndexSlice[:, IndexSlice["x", "A"]],\n IndexSlice[:, IndexSlice[:, "A"]],\n IndexSlice[:, IndexSlice[:, ["A", "C"]]], # missing col element\n IndexSlice[IndexSlice["a", 1], :],\n IndexSlice[IndexSlice[:, 1], :],\n IndexSlice[IndexSlice[:, [1, 3]], :], # missing row element\n IndexSlice[:, ("x", "A")],\n IndexSlice[("a", 1), :],\n ],\n )\n def test_map_subset_multiindex(self, slice_):\n # GH 19861\n # edited for GH 33562\n if (\n isinstance(slice_[-1], tuple)\n and isinstance(slice_[-1][-1], list)\n and "C" in slice_[-1][-1]\n ):\n ctx = pytest.raises(KeyError, match="C")\n elif (\n isinstance(slice_[0], tuple)\n and isinstance(slice_[0][1], list)\n and 3 in slice_[0][1]\n ):\n ctx = pytest.raises(KeyError, match="3")\n else:\n ctx = contextlib.nullcontext()\n\n idx = MultiIndex.from_product([["a", "b"], [1, 2]])\n col = MultiIndex.from_product([["x", "y"], ["A", "B"]])\n df = DataFrame(np.random.default_rng(2).random((4, 4)), columns=col, index=idx)\n\n with ctx:\n df.style.map(lambda x: "color: red;", subset=slice_).to_html()\n\n def test_map_subset_multiindex_code(self):\n # https://github.com/pandas-dev/pandas/issues/25858\n # Checks styler.map works with multindex when codes are provided\n codes = np.array([[0, 0, 1, 1], [0, 1, 0, 1]])\n columns = MultiIndex(\n levels=[["a", "b"], ["%", "#"]], codes=codes, names=["", ""]\n )\n df = DataFrame(\n [[1, -1, 1, 1], [-1, 1, 1, 1]], index=["hello", "world"], columns=columns\n )\n pct_subset = IndexSlice[:, IndexSlice[:, "%":"%"]]\n\n def color_negative_red(val):\n color = "red" if val < 0 else "black"\n return f"color: {color}"\n\n df.loc[pct_subset]\n df.style.map(color_negative_red, subset=pct_subset)\n\n @pytest.mark.parametrize(\n "stylefunc", ["background_gradient", "bar", "text_gradient"]\n )\n def test_subset_for_boolean_cols(self, stylefunc):\n # GH47838\n df = DataFrame(\n [\n [1, 2],\n [3, 4],\n ],\n columns=[False, True],\n )\n styled = getattr(df.style, stylefunc)()\n styled._compute()\n assert set(styled.ctx) == {(0, 0), (0, 1), (1, 0), (1, 1)}\n\n def test_empty(self):\n df = DataFrame({"A": [1, 0]})\n s = df.style\n s.ctx = {(0, 0): [("color", "red")], (1, 0): [("", "")]}\n\n result = s._translate(True, True)["cellstyle"]\n expected = [\n {"props": [("color", "red")], "selectors": ["row0_col0"]},\n {"props": [("", "")], "selectors": ["row1_col0"]},\n ]\n assert result == expected\n\n def test_duplicate(self):\n df = DataFrame({"A": [1, 0]})\n s = df.style\n s.ctx = {(0, 0): [("color", "red")], (1, 0): [("color", "red")]}\n\n result = s._translate(True, True)["cellstyle"]\n expected = [\n {"props": [("color", "red")], "selectors": ["row0_col0", "row1_col0"]}\n ]\n assert result == expected\n\n def test_init_with_na_rep(self):\n # GH 21527 28358\n df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])\n\n ctx = Styler(df, na_rep="NA")._translate(True, True)\n assert ctx["body"][0][1]["display_value"] == "NA"\n assert ctx["body"][0][2]["display_value"] == "NA"\n\n def test_caption(self, df):\n styler = Styler(df, caption="foo")\n result = styler.to_html()\n assert all(["caption" in result, "foo" in result])\n\n styler = df.style\n result = styler.set_caption("baz")\n assert styler is result\n assert styler.caption == "baz"\n\n def test_uuid(self, df):\n styler = Styler(df, uuid="abc123")\n result = styler.to_html()\n assert "abc123" in result\n\n styler = df.style\n result = styler.set_uuid("aaa")\n assert result is styler\n assert result.uuid == "aaa"\n\n def test_unique_id(self):\n # See https://github.com/pandas-dev/pandas/issues/16780\n df = DataFrame({"a": [1, 3, 5, 6], "b": [2, 4, 12, 21]})\n result = df.style.to_html(uuid="test")\n assert "test" in result\n ids = re.findall('id="(.*?)"', result)\n assert np.unique(ids).size == len(ids)\n\n def test_table_styles(self, df):\n style = [{"selector": "th", "props": [("foo", "bar")]}] # default format\n styler = Styler(df, table_styles=style)\n result = " ".join(styler.to_html().split())\n assert "th { foo: bar; }" in result\n\n styler = df.style\n result = styler.set_table_styles(style)\n assert styler is result\n assert styler.table_styles == style\n\n # GH 39563\n style = [{"selector": "th", "props": "foo:bar;"}] # css string format\n styler = df.style.set_table_styles(style)\n result = " ".join(styler.to_html().split())\n assert "th { foo: bar; }" in result\n\n def test_table_styles_multiple(self, df):\n ctx = df.style.set_table_styles(\n [\n {"selector": "th,td", "props": "color:red;"},\n {"selector": "tr", "props": "color:green;"},\n ]\n )._translate(True, True)["table_styles"]\n assert ctx == [\n {"selector": "th", "props": [("color", "red")]},\n {"selector": "td", "props": [("color", "red")]},\n {"selector": "tr", "props": [("color", "green")]},\n ]\n\n def test_table_styles_dict_multiple_selectors(self, df):\n # GH 44011\n result = df.style.set_table_styles(\n {\n "B": [\n {"selector": "th,td", "props": [("border-left", "2px solid black")]}\n ]\n }\n )._translate(True, True)["table_styles"]\n\n expected = [\n {"selector": "th.col1", "props": [("border-left", "2px solid black")]},\n {"selector": "td.col1", "props": [("border-left", "2px solid black")]},\n ]\n\n assert result == expected\n\n def test_maybe_convert_css_to_tuples(self):\n expected = [("a", "b"), ("c", "d e")]\n assert maybe_convert_css_to_tuples("a:b;c:d e;") == expected\n assert maybe_convert_css_to_tuples("a: b ;c: d e ") == expected\n expected = []\n assert maybe_convert_css_to_tuples("") == expected\n\n def test_maybe_convert_css_to_tuples_err(self):\n msg = "Styles supplied as string must follow CSS rule formats"\n with pytest.raises(ValueError, match=msg):\n maybe_convert_css_to_tuples("err")\n\n def test_table_attributes(self, df):\n attributes = 'class="foo" data-bar'\n styler = Styler(df, table_attributes=attributes)\n result = styler.to_html()\n assert 'class="foo" data-bar' in result\n\n result = df.style.set_table_attributes(attributes).to_html()\n assert 'class="foo" data-bar' in result\n\n def test_apply_none(self):\n def f(x):\n return DataFrame(\n np.where(x == x.max(), "color: red", ""),\n index=x.index,\n columns=x.columns,\n )\n\n result = DataFrame([[1, 2], [3, 4]]).style.apply(f, axis=None)._compute().ctx\n assert result[(1, 1)] == [("color", "red")]\n\n def test_trim(self, df):\n result = df.style.to_html() # trim=True\n assert result.count("#") == 0\n\n result = df.style.highlight_max().to_html()\n assert result.count("#") == len(df.columns)\n\n def test_export(self, df, styler):\n f = lambda x: "color: red" if x > 0 else "color: blue"\n g = lambda x, z: f"color: {z}" if x > 0 else f"color: {z}"\n style1 = styler\n style1.map(f).map(g, z="b").highlight_max()._compute() # = render\n result = style1.export()\n style2 = df.style\n style2.use(result)\n assert style1._todo == style2._todo\n style2.to_html()\n\n def test_bad_apply_shape(self):\n df = DataFrame([[1, 2], [3, 4]], index=["A", "B"], columns=["X", "Y"])\n\n msg = "resulted in the apply method collapsing to a Series."\n with pytest.raises(ValueError, match=msg):\n df.style._apply(lambda x: "x")\n\n msg = "created invalid {} labels"\n with pytest.raises(ValueError, match=msg.format("index")):\n df.style._apply(lambda x: [""])\n\n with pytest.raises(ValueError, match=msg.format("index")):\n df.style._apply(lambda x: ["", "", "", ""])\n\n with pytest.raises(ValueError, match=msg.format("index")):\n df.style._apply(lambda x: Series(["a:v;", ""], index=["A", "C"]), axis=0)\n\n with pytest.raises(ValueError, match=msg.format("columns")):\n df.style._apply(lambda x: ["", "", ""], axis=1)\n\n with pytest.raises(ValueError, match=msg.format("columns")):\n df.style._apply(lambda x: Series(["a:v;", ""], index=["X", "Z"]), axis=1)\n\n msg = "returned ndarray with wrong shape"\n with pytest.raises(ValueError, match=msg):\n df.style._apply(lambda x: np.array([[""], [""]]), axis=None)\n\n def test_apply_bad_return(self):\n def f(x):\n return ""\n\n df = DataFrame([[1, 2], [3, 4]])\n msg = (\n "must return a DataFrame or ndarray when passed to `Styler.apply` "\n "with axis=None"\n )\n with pytest.raises(TypeError, match=msg):\n df.style._apply(f, axis=None)\n\n @pytest.mark.parametrize("axis", ["index", "columns"])\n def test_apply_bad_labels(self, axis):\n def f(x):\n return DataFrame(**{axis: ["bad", "labels"]})\n\n df = DataFrame([[1, 2], [3, 4]])\n msg = f"created invalid {axis} labels."\n with pytest.raises(ValueError, match=msg):\n df.style._apply(f, axis=None)\n\n def test_get_level_lengths(self):\n index = MultiIndex.from_product([["a", "b"], [0, 1, 2]])\n expected = {\n (0, 0): 3,\n (0, 3): 3,\n (1, 0): 1,\n (1, 1): 1,\n (1, 2): 1,\n (1, 3): 1,\n (1, 4): 1,\n (1, 5): 1,\n }\n result = _get_level_lengths(index, sparsify=True, max_index=100)\n tm.assert_dict_equal(result, expected)\n\n expected = {\n (0, 0): 1,\n (0, 1): 1,\n (0, 2): 1,\n (0, 3): 1,\n (0, 4): 1,\n (0, 5): 1,\n (1, 0): 1,\n (1, 1): 1,\n (1, 2): 1,\n (1, 3): 1,\n (1, 4): 1,\n (1, 5): 1,\n }\n result = _get_level_lengths(index, sparsify=False, max_index=100)\n tm.assert_dict_equal(result, expected)\n\n def test_get_level_lengths_un_sorted(self):\n index = MultiIndex.from_arrays([[1, 1, 2, 1], ["a", "b", "b", "d"]])\n expected = {\n (0, 0): 2,\n (0, 2): 1,\n (0, 3): 1,\n (1, 0): 1,\n (1, 1): 1,\n (1, 2): 1,\n (1, 3): 1,\n }\n result = _get_level_lengths(index, sparsify=True, max_index=100)\n tm.assert_dict_equal(result, expected)\n\n expected = {\n (0, 0): 1,\n (0, 1): 1,\n (0, 2): 1,\n (0, 3): 1,\n (1, 0): 1,\n (1, 1): 1,\n (1, 2): 1,\n (1, 3): 1,\n }\n result = _get_level_lengths(index, sparsify=False, max_index=100)\n tm.assert_dict_equal(result, expected)\n\n def test_mi_sparse_index_names(self, blank_value):\n # Test the class names and displayed value are correct on rendering MI names\n df = DataFrame(\n {"A": [1, 2]},\n index=MultiIndex.from_arrays(\n [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"]\n ),\n )\n result = df.style._translate(True, True)\n head = result["head"][1]\n expected = [\n {\n "class": "index_name level0",\n "display_value": "idx_level_0",\n "is_visible": True,\n },\n {\n "class": "index_name level1",\n "display_value": "idx_level_1",\n "is_visible": True,\n },\n {\n "class": "blank col0",\n "display_value": blank_value,\n "is_visible": True,\n },\n ]\n for i, expected_dict in enumerate(expected):\n assert expected_dict.items() <= head[i].items()\n\n def test_mi_sparse_column_names(self, blank_value):\n df = DataFrame(\n np.arange(16).reshape(4, 4),\n index=MultiIndex.from_arrays(\n [["a", "a", "b", "a"], [0, 1, 1, 2]],\n names=["idx_level_0", "idx_level_1"],\n ),\n columns=MultiIndex.from_arrays(\n [["C1", "C1", "C2", "C2"], [1, 0, 1, 0]], names=["colnam_0", "colnam_1"]\n ),\n )\n result = Styler(df, cell_ids=False)._translate(True, True)\n\n for level in [0, 1]:\n head = result["head"][level]\n expected = [\n {\n "class": "blank",\n "display_value": blank_value,\n "is_visible": True,\n },\n {\n "class": f"index_name level{level}",\n "display_value": f"colnam_{level}",\n "is_visible": True,\n },\n ]\n for i, expected_dict in enumerate(expected):\n assert expected_dict.items() <= head[i].items()\n\n def test_hide_column_headers(self, df, styler):\n ctx = styler.hide(axis="columns")._translate(True, True)\n assert len(ctx["head"]) == 0 # no header entries with an unnamed index\n\n df.index.name = "some_name"\n ctx = df.style.hide(axis="columns")._translate(True, True)\n assert len(ctx["head"]) == 1\n # index names still visible, changed in #42101, reverted in 43404\n\n def test_hide_single_index(self, df):\n # GH 14194\n # single unnamed index\n ctx = df.style._translate(True, True)\n assert ctx["body"][0][0]["is_visible"]\n assert ctx["head"][0][0]["is_visible"]\n ctx2 = df.style.hide(axis="index")._translate(True, True)\n assert not ctx2["body"][0][0]["is_visible"]\n assert not ctx2["head"][0][0]["is_visible"]\n\n # single named index\n ctx3 = df.set_index("A").style._translate(True, True)\n assert ctx3["body"][0][0]["is_visible"]\n assert len(ctx3["head"]) == 2 # 2 header levels\n assert ctx3["head"][0][0]["is_visible"]\n\n ctx4 = df.set_index("A").style.hide(axis="index")._translate(True, True)\n assert not ctx4["body"][0][0]["is_visible"]\n assert len(ctx4["head"]) == 1 # only 1 header levels\n assert not ctx4["head"][0][0]["is_visible"]\n\n def test_hide_multiindex(self):\n # GH 14194\n df = DataFrame(\n {"A": [1, 2], "B": [1, 2]},\n index=MultiIndex.from_arrays(\n [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"]\n ),\n )\n ctx1 = df.style._translate(True, True)\n # tests for 'a' and '0'\n assert ctx1["body"][0][0]["is_visible"]\n assert ctx1["body"][0][1]["is_visible"]\n # check for blank header rows\n assert len(ctx1["head"][0]) == 4 # two visible indexes and two data columns\n\n ctx2 = df.style.hide(axis="index")._translate(True, True)\n # tests for 'a' and '0'\n assert not ctx2["body"][0][0]["is_visible"]\n assert not ctx2["body"][0][1]["is_visible"]\n # check for blank header rows\n assert len(ctx2["head"][0]) == 3 # one hidden (col name) and two data columns\n assert not ctx2["head"][0][0]["is_visible"]\n\n def test_hide_columns_single_level(self, df):\n # GH 14194\n # test hiding single column\n ctx = df.style._translate(True, True)\n assert ctx["head"][0][1]["is_visible"]\n assert ctx["head"][0][1]["display_value"] == "A"\n assert ctx["head"][0][2]["is_visible"]\n assert ctx["head"][0][2]["display_value"] == "B"\n assert ctx["body"][0][1]["is_visible"] # col A, row 1\n assert ctx["body"][1][2]["is_visible"] # col B, row 1\n\n ctx = df.style.hide("A", axis="columns")._translate(True, True)\n assert not ctx["head"][0][1]["is_visible"]\n assert not ctx["body"][0][1]["is_visible"] # col A, row 1\n assert ctx["body"][1][2]["is_visible"] # col B, row 1\n\n # test hiding multiple columns\n ctx = df.style.hide(["A", "B"], axis="columns")._translate(True, True)\n assert not ctx["head"][0][1]["is_visible"]\n assert not ctx["head"][0][2]["is_visible"]\n assert not ctx["body"][0][1]["is_visible"] # col A, row 1\n assert not ctx["body"][1][2]["is_visible"] # col B, row 1\n\n def test_hide_columns_index_mult_levels(self):\n # GH 14194\n # setup dataframe with multiple column levels and indices\n i1 = MultiIndex.from_arrays(\n [["a", "a"], [0, 1]], names=["idx_level_0", "idx_level_1"]\n )\n i2 = MultiIndex.from_arrays(\n [["b", "b"], [0, 1]], names=["col_level_0", "col_level_1"]\n )\n df = DataFrame([[1, 2], [3, 4]], index=i1, columns=i2)\n ctx = df.style._translate(True, True)\n # column headers\n assert ctx["head"][0][2]["is_visible"]\n assert ctx["head"][1][2]["is_visible"]\n assert ctx["head"][1][3]["display_value"] == "1"\n # indices\n assert ctx["body"][0][0]["is_visible"]\n # data\n assert ctx["body"][1][2]["is_visible"]\n assert ctx["body"][1][2]["display_value"] == "3"\n assert ctx["body"][1][3]["is_visible"]\n assert ctx["body"][1][3]["display_value"] == "4"\n\n # hide top column level, which hides both columns\n ctx = df.style.hide("b", axis="columns")._translate(True, True)\n assert not ctx["head"][0][2]["is_visible"] # b\n assert not ctx["head"][1][2]["is_visible"] # 0\n assert not ctx["body"][1][2]["is_visible"] # 3\n assert ctx["body"][0][0]["is_visible"] # index\n\n # hide first column only\n ctx = df.style.hide([("b", 0)], axis="columns")._translate(True, True)\n assert not ctx["head"][0][2]["is_visible"] # b\n assert ctx["head"][0][3]["is_visible"] # b\n assert not ctx["head"][1][2]["is_visible"] # 0\n assert not ctx["body"][1][2]["is_visible"] # 3\n assert ctx["body"][1][3]["is_visible"]\n assert ctx["body"][1][3]["display_value"] == "4"\n\n # hide second column and index\n ctx = df.style.hide([("b", 1)], axis=1).hide(axis=0)._translate(True, True)\n assert not ctx["body"][0][0]["is_visible"] # index\n assert len(ctx["head"][0]) == 3\n assert ctx["head"][0][1]["is_visible"] # b\n assert ctx["head"][1][1]["is_visible"] # 0\n assert not ctx["head"][1][2]["is_visible"] # 1\n assert not ctx["body"][1][3]["is_visible"] # 4\n assert ctx["body"][1][2]["is_visible"]\n assert ctx["body"][1][2]["display_value"] == "3"\n\n # hide top row level, which hides both rows so body empty\n ctx = df.style.hide("a", axis="index")._translate(True, True)\n assert ctx["body"] == []\n\n # hide first row only\n ctx = df.style.hide(("a", 0), axis="index")._translate(True, True)\n for i in [0, 1, 2, 3]:\n assert "row1" in ctx["body"][0][i]["class"] # row0 not included in body\n assert ctx["body"][0][i]["is_visible"]\n\n def test_pipe(self, df):\n def set_caption_from_template(styler, a, b):\n return styler.set_caption(f"Dataframe with a = {a} and b = {b}")\n\n styler = df.style.pipe(set_caption_from_template, "A", b="B")\n assert "Dataframe with a = A and b = B" in styler.to_html()\n\n # Test with an argument that is a (callable, keyword_name) pair.\n def f(a, b, styler):\n return (a, b, styler)\n\n styler = df.style\n result = styler.pipe((f, "styler"), a=1, b=2)\n assert result == (1, 2, styler)\n\n def test_no_cell_ids(self):\n # GH 35588\n # GH 35663\n df = DataFrame(data=[[0]])\n styler = Styler(df, uuid="_", cell_ids=False)\n styler.to_html()\n s = styler.to_html() # render twice to ensure ctx is not updated\n assert s.find('<td class="data row0 col0" >') != -1\n\n @pytest.mark.parametrize(\n "classes",\n [\n DataFrame(\n data=[["", "test-class"], [np.nan, None]],\n columns=["A", "B"],\n index=["a", "b"],\n ),\n DataFrame(data=[["test-class"]], columns=["B"], index=["a"]),\n DataFrame(data=[["test-class", "unused"]], columns=["B", "C"], index=["a"]),\n ],\n )\n def test_set_data_classes(self, classes):\n # GH 36159\n df = DataFrame(data=[[0, 1], [2, 3]], columns=["A", "B"], index=["a", "b"])\n s = Styler(df, uuid_len=0, cell_ids=False).set_td_classes(classes).to_html()\n assert '<td class="data row0 col0" >0</td>' in s\n assert '<td class="data row0 col1 test-class" >1</td>' in s\n assert '<td class="data row1 col0" >2</td>' in s\n assert '<td class="data row1 col1" >3</td>' in s\n # GH 39317\n s = Styler(df, uuid_len=0, cell_ids=True).set_td_classes(classes).to_html()\n assert '<td id="T__row0_col0" class="data row0 col0" >0</td>' in s\n assert '<td id="T__row0_col1" class="data row0 col1 test-class" >1</td>' in s\n assert '<td id="T__row1_col0" class="data row1 col0" >2</td>' in s\n assert '<td id="T__row1_col1" class="data row1 col1" >3</td>' in s\n\n def test_set_data_classes_reindex(self):\n # GH 39317\n df = DataFrame(\n data=[[0, 1, 2], [3, 4, 5], [6, 7, 8]], columns=[0, 1, 2], index=[0, 1, 2]\n )\n classes = DataFrame(\n data=[["mi", "ma"], ["mu", "mo"]],\n columns=[0, 2],\n index=[0, 2],\n )\n s = Styler(df, uuid_len=0).set_td_classes(classes).to_html()\n assert '<td id="T__row0_col0" class="data row0 col0 mi" >0</td>' in s\n assert '<td id="T__row0_col2" class="data row0 col2 ma" >2</td>' in s\n assert '<td id="T__row1_col1" class="data row1 col1" >4</td>' in s\n assert '<td id="T__row2_col0" class="data row2 col0 mu" >6</td>' in s\n assert '<td id="T__row2_col2" class="data row2 col2 mo" >8</td>' in s\n\n def test_chaining_table_styles(self):\n # GH 35607\n df = DataFrame(data=[[0, 1], [1, 2]], columns=["A", "B"])\n styler = df.style.set_table_styles(\n [{"selector": "", "props": [("background-color", "yellow")]}]\n ).set_table_styles(\n [{"selector": ".col0", "props": [("background-color", "blue")]}],\n overwrite=False,\n )\n assert len(styler.table_styles) == 2\n\n def test_column_and_row_styling(self):\n # GH 35607\n df = DataFrame(data=[[0, 1], [1, 2]], columns=["A", "B"])\n s = Styler(df, uuid_len=0)\n s = s.set_table_styles({"A": [{"selector": "", "props": [("color", "blue")]}]})\n assert "#T_ .col0 {\n color: blue;\n}" in s.to_html()\n s = s.set_table_styles(\n {0: [{"selector": "", "props": [("color", "blue")]}]}, axis=1\n )\n assert "#T_ .row0 {\n color: blue;\n}" in s.to_html()\n\n @pytest.mark.parametrize("len_", [1, 5, 32, 33, 100])\n def test_uuid_len(self, len_):\n # GH 36345\n df = DataFrame(data=[["A"]])\n s = Styler(df, uuid_len=len_, cell_ids=False).to_html()\n strt = s.find('id="T_')\n end = s[strt + 6 :].find('"')\n if len_ > 32:\n assert end == 32\n else:\n assert end == len_\n\n @pytest.mark.parametrize("len_", [-2, "bad", None])\n def test_uuid_len_raises(self, len_):\n # GH 36345\n df = DataFrame(data=[["A"]])\n msg = "``uuid_len`` must be an integer in range \\[0, 32\\]."\n with pytest.raises(TypeError, match=msg):\n Styler(df, uuid_len=len_, cell_ids=False).to_html()\n\n @pytest.mark.parametrize(\n "slc",\n [\n IndexSlice[:, :],\n IndexSlice[:, 1],\n IndexSlice[1, :],\n IndexSlice[[1], [1]],\n IndexSlice[1, [1]],\n IndexSlice[[1], 1],\n IndexSlice[1],\n IndexSlice[1, 1],\n slice(None, None, None),\n [0, 1],\n np.array([0, 1]),\n Series([0, 1]),\n ],\n )\n def test_non_reducing_slice(self, slc):\n df = DataFrame([[0, 1], [2, 3]])\n\n tslice_ = non_reducing_slice(slc)\n assert isinstance(df.loc[tslice_], DataFrame)\n\n @pytest.mark.parametrize("box", [list, Series, np.array])\n def test_list_slice(self, box):\n # like dataframe getitem\n subset = box(["A"])\n\n df = DataFrame({"A": [1, 2], "B": [3, 4]}, index=["A", "B"])\n expected = IndexSlice[:, ["A"]]\n\n result = non_reducing_slice(subset)\n tm.assert_frame_equal(df.loc[result], df.loc[expected])\n\n def test_non_reducing_slice_on_multiindex(self):\n # GH 19861\n dic = {\n ("a", "d"): [1, 4],\n ("a", "c"): [2, 3],\n ("b", "c"): [3, 2],\n ("b", "d"): [4, 1],\n }\n df = DataFrame(dic, index=[0, 1])\n idx = IndexSlice\n slice_ = idx[:, idx["b", "d"]]\n tslice_ = non_reducing_slice(slice_)\n\n result = df.loc[tslice_]\n expected = DataFrame({("b", "d"): [4, 1]})\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "slice_",\n [\n IndexSlice[:, :],\n # check cols\n IndexSlice[:, IndexSlice[["a"]]], # inferred deeper need list\n IndexSlice[:, IndexSlice[["a"], ["c"]]], # inferred deeper need list\n IndexSlice[:, IndexSlice["a", "c", :]],\n IndexSlice[:, IndexSlice["a", :, "e"]],\n IndexSlice[:, IndexSlice[:, "c", "e"]],\n IndexSlice[:, IndexSlice["a", ["c", "d"], :]], # check list\n IndexSlice[:, IndexSlice["a", ["c", "d", "-"], :]], # don't allow missing\n IndexSlice[:, IndexSlice["a", ["c", "d", "-"], "e"]], # no slice\n # check rows\n IndexSlice[IndexSlice[["U"]], :], # inferred deeper need list\n IndexSlice[IndexSlice[["U"], ["W"]], :], # inferred deeper need list\n IndexSlice[IndexSlice["U", "W", :], :],\n IndexSlice[IndexSlice["U", :, "Y"], :],\n IndexSlice[IndexSlice[:, "W", "Y"], :],\n IndexSlice[IndexSlice[:, "W", ["Y", "Z"]], :], # check list\n IndexSlice[IndexSlice[:, "W", ["Y", "Z", "-"]], :], # don't allow missing\n IndexSlice[IndexSlice["U", "W", ["Y", "Z", "-"]], :], # no slice\n # check simultaneous\n IndexSlice[IndexSlice[:, "W", "Y"], IndexSlice["a", "c", :]],\n ],\n )\n def test_non_reducing_multi_slice_on_multiindex(self, slice_):\n # GH 33562\n cols = MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]])\n idxs = MultiIndex.from_product([["U", "V"], ["W", "X"], ["Y", "Z"]])\n df = DataFrame(np.arange(64).reshape(8, 8), columns=cols, index=idxs)\n\n for lvl in [0, 1]:\n key = slice_[lvl]\n if isinstance(key, tuple):\n for subkey in key:\n if isinstance(subkey, list) and "-" in subkey:\n # not present in the index level, raises KeyError since 2.0\n with pytest.raises(KeyError, match="-"):\n df.loc[slice_]\n return\n\n expected = df.loc[slice_]\n result = df.loc[non_reducing_slice(slice_)]\n tm.assert_frame_equal(result, expected)\n\n\ndef test_hidden_index_names(mi_df):\n mi_df.index.names = ["Lev0", "Lev1"]\n mi_styler = mi_df.style\n ctx = mi_styler._translate(True, True)\n assert len(ctx["head"]) == 3 # 2 column index levels + 1 index names row\n\n mi_styler.hide(axis="index", names=True)\n ctx = mi_styler._translate(True, True)\n assert len(ctx["head"]) == 2 # index names row is unparsed\n for i in range(4):\n assert ctx["body"][0][i]["is_visible"] # 2 index levels + 2 data values visible\n\n mi_styler.hide(axis="index", level=1)\n ctx = mi_styler._translate(True, True)\n assert len(ctx["head"]) == 2 # index names row is still hidden\n assert ctx["body"][0][0]["is_visible"] is True\n assert ctx["body"][0][1]["is_visible"] is False\n\n\ndef test_hidden_column_names(mi_df):\n mi_df.columns.names = ["Lev0", "Lev1"]\n mi_styler = mi_df.style\n ctx = mi_styler._translate(True, True)\n assert ctx["head"][0][1]["display_value"] == "Lev0"\n assert ctx["head"][1][1]["display_value"] == "Lev1"\n\n mi_styler.hide(names=True, axis="columns")\n ctx = mi_styler._translate(True, True)\n assert ctx["head"][0][1]["display_value"] == "&nbsp;"\n assert ctx["head"][1][1]["display_value"] == "&nbsp;"\n\n mi_styler.hide(level=0, axis="columns")\n ctx = mi_styler._translate(True, True)\n assert len(ctx["head"]) == 1 # no index names and only one visible column headers\n assert ctx["head"][0][1]["display_value"] == "&nbsp;"\n\n\n@pytest.mark.parametrize("caption", [1, ("a", "b", "c"), (1, "s")])\ndef test_caption_raises(mi_styler, caption):\n msg = "`caption` must be either a string or 2-tuple of strings."\n with pytest.raises(ValueError, match=msg):\n mi_styler.set_caption(caption)\n\n\ndef test_hiding_headers_over_index_no_sparsify():\n # GH 43464\n midx = MultiIndex.from_product([[1, 2], ["a", "a", "b"]])\n df = DataFrame(9, index=midx, columns=[0])\n ctx = df.style._translate(False, False)\n assert len(ctx["body"]) == 6\n ctx = df.style.hide((1, "a"), axis=0)._translate(False, False)\n assert len(ctx["body"]) == 4\n assert "row2" in ctx["body"][0][0]["class"]\n\n\ndef test_hiding_headers_over_columns_no_sparsify():\n # GH 43464\n midx = MultiIndex.from_product([[1, 2], ["a", "a", "b"]])\n df = DataFrame(9, columns=midx, index=[0])\n ctx = df.style._translate(False, False)\n for ix in [(0, 1), (0, 2), (1, 1), (1, 2)]:\n assert ctx["head"][ix[0]][ix[1]]["is_visible"] is True\n ctx = df.style.hide((1, "a"), axis="columns")._translate(False, False)\n for ix in [(0, 1), (0, 2), (1, 1), (1, 2)]:\n assert ctx["head"][ix[0]][ix[1]]["is_visible"] is False\n\n\ndef test_get_level_lengths_mi_hidden():\n # GH 43464\n index = MultiIndex.from_arrays([[1, 1, 1, 2, 2, 2], ["a", "a", "b", "a", "a", "b"]])\n expected = {\n (0, 2): 1,\n (0, 3): 1,\n (0, 4): 1,\n (0, 5): 1,\n (1, 2): 1,\n (1, 3): 1,\n (1, 4): 1,\n (1, 5): 1,\n }\n result = _get_level_lengths(\n index,\n sparsify=False,\n max_index=100,\n hidden_elements=[0, 1, 0, 1], # hidden element can repeat if duplicated index\n )\n tm.assert_dict_equal(result, expected)\n\n\ndef test_row_trimming_hide_index():\n # gh 43703\n df = DataFrame([[1], [2], [3], [4], [5]])\n with option_context("styler.render.max_rows", 2):\n ctx = df.style.hide([0, 1], axis="index")._translate(True, True)\n assert len(ctx["body"]) == 3\n for r, val in enumerate(["3", "4", "..."]):\n assert ctx["body"][r][1]["display_value"] == val\n\n\ndef test_row_trimming_hide_index_mi():\n # gh 44247\n df = DataFrame([[1], [2], [3], [4], [5]])\n df.index = MultiIndex.from_product([[0], [0, 1, 2, 3, 4]])\n with option_context("styler.render.max_rows", 2):\n ctx = df.style.hide([(0, 0), (0, 1)], axis="index")._translate(True, True)\n assert len(ctx["body"]) == 3\n\n # level 0 index headers (sparsified)\n assert {"value": 0, "attributes": 'rowspan="2"', "is_visible": True}.items() <= ctx[\n "body"\n ][0][0].items()\n assert {"value": 0, "attributes": "", "is_visible": False}.items() <= ctx["body"][\n 1\n ][0].items()\n assert {"value": "...", "is_visible": True}.items() <= ctx["body"][2][0].items()\n\n for r, val in enumerate(["2", "3", "..."]):\n assert ctx["body"][r][1]["display_value"] == val # level 1 index headers\n for r, val in enumerate(["3", "4", "..."]):\n assert ctx["body"][r][2]["display_value"] == val # data values\n\n\ndef test_col_trimming_hide_columns():\n # gh 44272\n df = DataFrame([[1, 2, 3, 4, 5]])\n with option_context("styler.render.max_columns", 2):\n ctx = df.style.hide([0, 1], axis="columns")._translate(True, True)\n\n assert len(ctx["head"][0]) == 6 # blank, [0, 1 (hidden)], [2 ,3 (visible)], + trim\n for c, vals in enumerate([(1, False), (2, True), (3, True), ("...", True)]):\n assert ctx["head"][0][c + 2]["value"] == vals[0]\n assert ctx["head"][0][c + 2]["is_visible"] == vals[1]\n\n assert len(ctx["body"][0]) == 6 # index + 2 hidden + 2 visible + trimming col\n\n\ndef test_no_empty_apply(mi_styler):\n # 45313\n mi_styler.apply(lambda s: ["a:v;"] * 2, subset=[False, False])\n mi_styler._compute()\n\n\n@pytest.mark.parametrize("format", ["html", "latex", "string"])\ndef test_output_buffer(mi_styler, format):\n # gh 47053\n with tm.ensure_clean(f"delete_me.{format}") as f:\n getattr(mi_styler, f"to_{format}")(f)\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_style.py
test_style.py
Python
58,095
0.75
0.141058
0.065789
react-lib
927
2024-07-07T17:42:01.146898
GPL-3.0
true
7044c413b3eaa5cd6dee46453cb6d0ad
import numpy as np\nimport pytest\n\nfrom pandas import DataFrame\n\npytest.importorskip("jinja2")\nfrom pandas.io.formats.style import Styler\n\n\n@pytest.fixture\ndef df():\n return DataFrame(\n data=[[0, 1, 2], [3, 4, 5], [6, 7, 8]],\n columns=["A", "B", "C"],\n index=["x", "y", "z"],\n )\n\n\n@pytest.fixture\ndef styler(df):\n return Styler(df, uuid_len=0)\n\n\n@pytest.mark.parametrize(\n "ttips",\n [\n DataFrame( # Test basic reindex and ignoring blank\n data=[["Min", "Max"], [np.nan, ""]],\n columns=["A", "C"],\n index=["x", "y"],\n ),\n DataFrame( # Test non-referenced columns, reversed col names, short index\n data=[["Max", "Min", "Bad-Col"]], columns=["C", "A", "D"], index=["x"]\n ),\n ],\n)\ndef test_tooltip_render(ttips, styler):\n # GH 21266\n result = styler.set_tooltips(ttips).to_html()\n\n # test tooltip table level class\n assert "#T_ .pd-t {\n visibility: hidden;\n" in result\n\n # test 'Min' tooltip added\n assert "#T_ #T__row0_col0:hover .pd-t {\n visibility: visible;\n}" in result\n assert '#T_ #T__row0_col0 .pd-t::after {\n content: "Min";\n}' in result\n assert 'class="data row0 col0" >0<span class="pd-t"></span></td>' in result\n\n # test 'Max' tooltip added\n assert "#T_ #T__row0_col2:hover .pd-t {\n visibility: visible;\n}" in result\n assert '#T_ #T__row0_col2 .pd-t::after {\n content: "Max";\n}' in result\n assert 'class="data row0 col2" >2<span class="pd-t"></span></td>' in result\n\n # test Nan, empty string and bad column ignored\n assert "#T_ #T__row1_col0:hover .pd-t {\n visibility: visible;\n}" not in result\n assert "#T_ #T__row1_col1:hover .pd-t {\n visibility: visible;\n}" not in result\n assert "#T_ #T__row0_col1:hover .pd-t {\n visibility: visible;\n}" not in result\n assert "#T_ #T__row1_col2:hover .pd-t {\n visibility: visible;\n}" not in result\n assert "Bad-Col" not in result\n\n\ndef test_tooltip_ignored(styler):\n # GH 21266\n result = styler.to_html() # no set_tooltips() creates no <span>\n assert '<style type="text/css">\n</style>' in result\n assert '<span class="pd-t"></span>' not in result\n\n\ndef test_tooltip_css_class(styler):\n # GH 21266\n result = styler.set_tooltips(\n DataFrame([["tooltip"]], index=["x"], columns=["A"]),\n css_class="other-class",\n props=[("color", "green")],\n ).to_html()\n assert "#T_ .other-class {\n color: green;\n" in result\n assert '#T_ #T__row0_col0 .other-class::after {\n content: "tooltip";\n' in result\n\n # GH 39563\n result = styler.set_tooltips( # set_tooltips overwrites previous\n DataFrame([["tooltip"]], index=["x"], columns=["A"]),\n css_class="another-class",\n props="color:green;color:red;",\n ).to_html()\n assert "#T_ .another-class {\n color: green;\n color: red;\n}" in result\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_tooltip.py
test_tooltip.py
Python
2,899
0.95
0.188235
0.117647
python-kit
809
2025-01-13T18:29:36.972287
MIT
true
21daa6cfbd001361a5f649a70f31b6a6
from textwrap import dedent\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n MultiIndex,\n Series,\n option_context,\n)\n\npytest.importorskip("jinja2")\nfrom pandas.io.formats.style import Styler\nfrom pandas.io.formats.style_render import (\n _parse_latex_cell_styles,\n _parse_latex_css_conversion,\n _parse_latex_header_span,\n _parse_latex_table_styles,\n _parse_latex_table_wrapping,\n)\n\n\n@pytest.fixture\ndef df():\n return DataFrame(\n {"A": [0, 1], "B": [-0.61, -1.22], "C": Series(["ab", "cd"], dtype=object)}\n )\n\n\n@pytest.fixture\ndef df_ext():\n return DataFrame(\n {"A": [0, 1, 2], "B": [-0.61, -1.22, -2.22], "C": ["ab", "cd", "de"]}\n )\n\n\n@pytest.fixture\ndef styler(df):\n return Styler(df, uuid_len=0, precision=2)\n\n\ndef test_minimal_latex_tabular(styler):\n expected = dedent(\n """\\n \\begin{tabular}{lrrl}\n & A & B & C \\\\\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\end{tabular}\n """\n )\n assert styler.to_latex() == expected\n\n\ndef test_tabular_hrules(styler):\n expected = dedent(\n """\\n \\begin{tabular}{lrrl}\n \\toprule\n & A & B & C \\\\\n \\midrule\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\bottomrule\n \\end{tabular}\n """\n )\n assert styler.to_latex(hrules=True) == expected\n\n\ndef test_tabular_custom_hrules(styler):\n styler.set_table_styles(\n [\n {"selector": "toprule", "props": ":hline"},\n {"selector": "bottomrule", "props": ":otherline"},\n ]\n ) # no midrule\n expected = dedent(\n """\\n \\begin{tabular}{lrrl}\n \\hline\n & A & B & C \\\\\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\otherline\n \\end{tabular}\n """\n )\n assert styler.to_latex() == expected\n\n\ndef test_column_format(styler):\n # default setting is already tested in `test_latex_minimal_tabular`\n styler.set_table_styles([{"selector": "column_format", "props": ":cccc"}])\n\n assert "\\begin{tabular}{rrrr}" in styler.to_latex(column_format="rrrr")\n styler.set_table_styles([{"selector": "column_format", "props": ":r|r|cc"}])\n assert "\\begin{tabular}{r|r|cc}" in styler.to_latex()\n\n\ndef test_siunitx_cols(styler):\n expected = dedent(\n """\\n \\begin{tabular}{lSSl}\n {} & {A} & {B} & {C} \\\\\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\end{tabular}\n """\n )\n assert styler.to_latex(siunitx=True) == expected\n\n\ndef test_position(styler):\n assert "\\begin{table}[h!]" in styler.to_latex(position="h!")\n assert "\\end{table}" in styler.to_latex(position="h!")\n styler.set_table_styles([{"selector": "position", "props": ":b!"}])\n assert "\\begin{table}[b!]" in styler.to_latex()\n assert "\\end{table}" in styler.to_latex()\n\n\n@pytest.mark.parametrize("env", [None, "longtable"])\ndef test_label(styler, env):\n assert "\n\\label{text}" in styler.to_latex(label="text", environment=env)\n styler.set_table_styles([{"selector": "label", "props": ":{more §text}"}])\n assert "\n\\label{more :text}" in styler.to_latex(environment=env)\n\n\ndef test_position_float_raises(styler):\n msg = "`position_float` should be one of 'raggedright', 'raggedleft', 'centering',"\n with pytest.raises(ValueError, match=msg):\n styler.to_latex(position_float="bad_string")\n\n msg = "`position_float` cannot be used in 'longtable' `environment`"\n with pytest.raises(ValueError, match=msg):\n styler.to_latex(position_float="centering", environment="longtable")\n\n\n@pytest.mark.parametrize("label", [(None, ""), ("text", "\\label{text}")])\n@pytest.mark.parametrize("position", [(None, ""), ("h!", "{table}[h!]")])\n@pytest.mark.parametrize("caption", [(None, ""), ("text", "\\caption{text}")])\n@pytest.mark.parametrize("column_format", [(None, ""), ("rcrl", "{tabular}{rcrl}")])\n@pytest.mark.parametrize("position_float", [(None, ""), ("centering", "\\centering")])\ndef test_kwargs_combinations(\n styler, label, position, caption, column_format, position_float\n):\n result = styler.to_latex(\n label=label[0],\n position=position[0],\n caption=caption[0],\n column_format=column_format[0],\n position_float=position_float[0],\n )\n assert label[1] in result\n assert position[1] in result\n assert caption[1] in result\n assert column_format[1] in result\n assert position_float[1] in result\n\n\ndef test_custom_table_styles(styler):\n styler.set_table_styles(\n [\n {"selector": "mycommand", "props": ":{myoptions}"},\n {"selector": "mycommand2", "props": ":{myoptions2}"},\n ]\n )\n expected = dedent(\n """\\n \\begin{table}\n \\mycommand{myoptions}\n \\mycommand2{myoptions2}\n """\n )\n assert expected in styler.to_latex()\n\n\ndef test_cell_styling(styler):\n styler.highlight_max(props="itshape:;Huge:--wrap;")\n expected = dedent(\n """\\n \\begin{tabular}{lrrl}\n & A & B & C \\\\\n 0 & 0 & \\itshape {\\Huge -0.61} & ab \\\\\n 1 & \\itshape {\\Huge 1} & -1.22 & \\itshape {\\Huge cd} \\\\\n \\end{tabular}\n """\n )\n assert expected == styler.to_latex()\n\n\ndef test_multiindex_columns(df):\n cidx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])\n df.columns = cidx\n expected = dedent(\n """\\n \\begin{tabular}{lrrl}\n & \\multicolumn{2}{r}{A} & B \\\\\n & a & b & c \\\\\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\end{tabular}\n """\n )\n s = df.style.format(precision=2)\n assert expected == s.to_latex()\n\n # non-sparse\n expected = dedent(\n """\\n \\begin{tabular}{lrrl}\n & A & A & B \\\\\n & a & b & c \\\\\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\end{tabular}\n """\n )\n s = df.style.format(precision=2)\n assert expected == s.to_latex(sparse_columns=False)\n\n\ndef test_multiindex_row(df_ext):\n ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])\n df_ext.index = ridx\n expected = dedent(\n """\\n \\begin{tabular}{llrrl}\n & & A & B & C \\\\\n \\multirow[c]{2}{*}{A} & a & 0 & -0.61 & ab \\\\\n & b & 1 & -1.22 & cd \\\\\n B & c & 2 & -2.22 & de \\\\\n \\end{tabular}\n """\n )\n styler = df_ext.style.format(precision=2)\n result = styler.to_latex()\n assert expected == result\n\n # non-sparse\n expected = dedent(\n """\\n \\begin{tabular}{llrrl}\n & & A & B & C \\\\\n A & a & 0 & -0.61 & ab \\\\\n A & b & 1 & -1.22 & cd \\\\\n B & c & 2 & -2.22 & de \\\\\n \\end{tabular}\n """\n )\n result = styler.to_latex(sparse_index=False)\n assert expected == result\n\n\ndef test_multirow_naive(df_ext):\n ridx = MultiIndex.from_tuples([("X", "x"), ("X", "y"), ("Y", "z")])\n df_ext.index = ridx\n expected = dedent(\n """\\n \\begin{tabular}{llrrl}\n & & A & B & C \\\\\n X & x & 0 & -0.61 & ab \\\\\n & y & 1 & -1.22 & cd \\\\\n Y & z & 2 & -2.22 & de \\\\\n \\end{tabular}\n """\n )\n styler = df_ext.style.format(precision=2)\n result = styler.to_latex(multirow_align="naive")\n assert expected == result\n\n\ndef test_multiindex_row_and_col(df_ext):\n cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])\n ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])\n df_ext.index, df_ext.columns = ridx, cidx\n expected = dedent(\n """\\n \\begin{tabular}{llrrl}\n & & \\multicolumn{2}{l}{Z} & Y \\\\\n & & a & b & c \\\\\n \\multirow[b]{2}{*}{A} & a & 0 & -0.61 & ab \\\\\n & b & 1 & -1.22 & cd \\\\\n B & c & 2 & -2.22 & de \\\\\n \\end{tabular}\n """\n )\n styler = df_ext.style.format(precision=2)\n result = styler.to_latex(multirow_align="b", multicol_align="l")\n assert result == expected\n\n # non-sparse\n expected = dedent(\n """\\n \\begin{tabular}{llrrl}\n & & Z & Z & Y \\\\\n & & a & b & c \\\\\n A & a & 0 & -0.61 & ab \\\\\n A & b & 1 & -1.22 & cd \\\\\n B & c & 2 & -2.22 & de \\\\\n \\end{tabular}\n """\n )\n result = styler.to_latex(sparse_index=False, sparse_columns=False)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "multicol_align, siunitx, header",\n [\n ("naive-l", False, " & A & &"),\n ("naive-r", False, " & & & A"),\n ("naive-l", True, "{} & {A} & {} & {}"),\n ("naive-r", True, "{} & {} & {} & {A}"),\n ],\n)\ndef test_multicol_naive(df, multicol_align, siunitx, header):\n ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("A", "c")])\n df.columns = ridx\n level1 = " & a & b & c" if not siunitx else "{} & {a} & {b} & {c}"\n col_format = "lrrl" if not siunitx else "lSSl"\n expected = dedent(\n f"""\\n \\begin{{tabular}}{{{col_format}}}\n {header} \\\\\n {level1} \\\\\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\end{{tabular}}\n """\n )\n styler = df.style.format(precision=2)\n result = styler.to_latex(multicol_align=multicol_align, siunitx=siunitx)\n assert expected == result\n\n\ndef test_multi_options(df_ext):\n cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])\n ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])\n df_ext.index, df_ext.columns = ridx, cidx\n styler = df_ext.style.format(precision=2)\n\n expected = dedent(\n """\\n & & \\multicolumn{2}{r}{Z} & Y \\\\\n & & a & b & c \\\\\n \\multirow[c]{2}{*}{A} & a & 0 & -0.61 & ab \\\\\n """\n )\n result = styler.to_latex()\n assert expected in result\n\n with option_context("styler.latex.multicol_align", "l"):\n assert " & & \\multicolumn{2}{l}{Z} & Y \\\\" in styler.to_latex()\n\n with option_context("styler.latex.multirow_align", "b"):\n assert "\\multirow[b]{2}{*}{A} & a & 0 & -0.61 & ab \\\\" in styler.to_latex()\n\n\ndef test_multiindex_columns_hidden():\n df = DataFrame([[1, 2, 3, 4]])\n df.columns = MultiIndex.from_tuples([("A", 1), ("A", 2), ("A", 3), ("B", 1)])\n s = df.style\n assert "{tabular}{lrrrr}" in s.to_latex()\n s.set_table_styles([]) # reset the position command\n s.hide([("A", 2)], axis="columns")\n assert "{tabular}{lrrr}" in s.to_latex()\n\n\n@pytest.mark.parametrize(\n "option, value",\n [\n ("styler.sparse.index", True),\n ("styler.sparse.index", False),\n ("styler.sparse.columns", True),\n ("styler.sparse.columns", False),\n ],\n)\ndef test_sparse_options(df_ext, option, value):\n cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])\n ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])\n df_ext.index, df_ext.columns = ridx, cidx\n styler = df_ext.style\n\n latex1 = styler.to_latex()\n with option_context(option, value):\n latex2 = styler.to_latex()\n assert (latex1 == latex2) is value\n\n\ndef test_hidden_index(styler):\n styler.hide(axis="index")\n expected = dedent(\n """\\n \\begin{tabular}{rrl}\n A & B & C \\\\\n 0 & -0.61 & ab \\\\\n 1 & -1.22 & cd \\\\\n \\end{tabular}\n """\n )\n assert styler.to_latex() == expected\n\n\n@pytest.mark.parametrize("environment", ["table", "figure*", None])\ndef test_comprehensive(df_ext, environment):\n # test as many low level features simultaneously as possible\n cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])\n ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])\n df_ext.index, df_ext.columns = ridx, cidx\n stlr = df_ext.style\n stlr.set_caption("mycap")\n stlr.set_table_styles(\n [\n {"selector": "label", "props": ":{fig§item}"},\n {"selector": "position", "props": ":h!"},\n {"selector": "position_float", "props": ":centering"},\n {"selector": "column_format", "props": ":rlrlr"},\n {"selector": "toprule", "props": ":toprule"},\n {"selector": "midrule", "props": ":midrule"},\n {"selector": "bottomrule", "props": ":bottomrule"},\n {"selector": "rowcolors", "props": ":{3}{pink}{}"}, # custom command\n ]\n )\n stlr.highlight_max(axis=0, props="textbf:--rwrap;cellcolor:[rgb]{1,1,0.6}--rwrap")\n stlr.highlight_max(axis=None, props="Huge:--wrap;", subset=[("Z", "a"), ("Z", "b")])\n\n expected = (\n """\\n\\begin{table}[h!]\n\\centering\n\\caption{mycap}\n\\label{fig:item}\n\\rowcolors{3}{pink}{}\n\\begin{tabular}{rlrlr}\n\\toprule\n & & \\multicolumn{2}{r}{Z} & Y \\\\\n & & a & b & c \\\\\n\\midrule\n\\multirow[c]{2}{*}{A} & a & 0 & \\textbf{\\cellcolor[rgb]{1,1,0.6}{-0.61}} & ab \\\\\n & b & 1 & -1.22 & cd \\\\\nB & c & \\textbf{\\cellcolor[rgb]{1,1,0.6}{{\\Huge 2}}} & -2.22 & """\n """\\n\\textbf{\\cellcolor[rgb]{1,1,0.6}{de}} \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n"""\n ).replace("table", environment if environment else "table")\n result = stlr.format(precision=2).to_latex(environment=environment)\n assert result == expected\n\n\ndef test_environment_option(styler):\n with option_context("styler.latex.environment", "bar-env"):\n assert "\\begin{bar-env}" in styler.to_latex()\n assert "\\begin{foo-env}" in styler.to_latex(environment="foo-env")\n\n\ndef test_parse_latex_table_styles(styler):\n styler.set_table_styles(\n [\n {"selector": "foo", "props": [("attr", "value")]},\n {"selector": "bar", "props": [("attr", "overwritten")]},\n {"selector": "bar", "props": [("attr", "baz"), ("attr2", "ignored")]},\n {"selector": "label", "props": [("", "{fig§item}")]},\n ]\n )\n assert _parse_latex_table_styles(styler.table_styles, "bar") == "baz"\n\n # test '§' replaced by ':' [for CSS compatibility]\n assert _parse_latex_table_styles(styler.table_styles, "label") == "{fig:item}"\n\n\ndef test_parse_latex_cell_styles_basic(): # test nesting\n cell_style = [("itshape", "--rwrap"), ("cellcolor", "[rgb]{0,1,1}--rwrap")]\n expected = "\\itshape{\\cellcolor[rgb]{0,1,1}{text}}"\n assert _parse_latex_cell_styles(cell_style, "text") == expected\n\n\n@pytest.mark.parametrize(\n "wrap_arg, expected",\n [ # test wrapping\n ("", "\\<command><options> <display_value>"),\n ("--wrap", "{\\<command><options> <display_value>}"),\n ("--nowrap", "\\<command><options> <display_value>"),\n ("--lwrap", "{\\<command><options>} <display_value>"),\n ("--dwrap", "{\\<command><options>}{<display_value>}"),\n ("--rwrap", "\\<command><options>{<display_value>}"),\n ],\n)\ndef test_parse_latex_cell_styles_braces(wrap_arg, expected):\n cell_style = [("<command>", f"<options>{wrap_arg}")]\n assert _parse_latex_cell_styles(cell_style, "<display_value>") == expected\n\n\ndef test_parse_latex_header_span():\n cell = {"attributes": 'colspan="3"', "display_value": "text", "cellstyle": []}\n expected = "\\multicolumn{3}{Y}{text}"\n assert _parse_latex_header_span(cell, "X", "Y") == expected\n\n cell = {"attributes": 'rowspan="5"', "display_value": "text", "cellstyle": []}\n expected = "\\multirow[X]{5}{*}{text}"\n assert _parse_latex_header_span(cell, "X", "Y") == expected\n\n cell = {"display_value": "text", "cellstyle": []}\n assert _parse_latex_header_span(cell, "X", "Y") == "text"\n\n cell = {"display_value": "text", "cellstyle": [("bfseries", "--rwrap")]}\n assert _parse_latex_header_span(cell, "X", "Y") == "\\bfseries{text}"\n\n\ndef test_parse_latex_table_wrapping(styler):\n styler.set_table_styles(\n [\n {"selector": "toprule", "props": ":value"},\n {"selector": "bottomrule", "props": ":value"},\n {"selector": "midrule", "props": ":value"},\n {"selector": "column_format", "props": ":value"},\n ]\n )\n assert _parse_latex_table_wrapping(styler.table_styles, styler.caption) is False\n assert _parse_latex_table_wrapping(styler.table_styles, "some caption") is True\n styler.set_table_styles(\n [\n {"selector": "not-ignored", "props": ":value"},\n ],\n overwrite=False,\n )\n assert _parse_latex_table_wrapping(styler.table_styles, None) is True\n\n\ndef test_short_caption(styler):\n result = styler.to_latex(caption=("full cap", "short cap"))\n assert "\\caption[short cap]{full cap}" in result\n\n\n@pytest.mark.parametrize(\n "css, expected",\n [\n ([("color", "red")], [("color", "{red}")]), # test color and input format types\n (\n [("color", "rgb(128, 128, 128 )")],\n [("color", "[rgb]{0.502, 0.502, 0.502}")],\n ),\n (\n [("color", "rgb(128, 50%, 25% )")],\n [("color", "[rgb]{0.502, 0.500, 0.250}")],\n ),\n (\n [("color", "rgba(128,128,128,1)")],\n [("color", "[rgb]{0.502, 0.502, 0.502}")],\n ),\n ([("color", "#FF00FF")], [("color", "[HTML]{FF00FF}")]),\n ([("color", "#F0F")], [("color", "[HTML]{FF00FF}")]),\n ([("font-weight", "bold")], [("bfseries", "")]), # test font-weight and types\n ([("font-weight", "bolder")], [("bfseries", "")]),\n ([("font-weight", "normal")], []),\n ([("background-color", "red")], [("cellcolor", "{red}--lwrap")]),\n (\n [("background-color", "#FF00FF")], # test background-color command and wrap\n [("cellcolor", "[HTML]{FF00FF}--lwrap")],\n ),\n ([("font-style", "italic")], [("itshape", "")]), # test font-style and types\n ([("font-style", "oblique")], [("slshape", "")]),\n ([("font-style", "normal")], []),\n ([("color", "red /*--dwrap*/")], [("color", "{red}--dwrap")]), # css comments\n ([("background-color", "red /* --dwrap */")], [("cellcolor", "{red}--dwrap")]),\n ],\n)\ndef test_parse_latex_css_conversion(css, expected):\n result = _parse_latex_css_conversion(css)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "env, inner_env",\n [\n (None, "tabular"),\n ("table", "tabular"),\n ("longtable", "longtable"),\n ],\n)\n@pytest.mark.parametrize(\n "convert, exp", [(True, "bfseries"), (False, "font-weightbold")]\n)\ndef test_parse_latex_css_convert_minimal(styler, env, inner_env, convert, exp):\n # parameters ensure longtable template is also tested\n styler.highlight_max(props="font-weight:bold;")\n result = styler.to_latex(convert_css=convert, environment=env)\n expected = dedent(\n f"""\\n 0 & 0 & \\{exp} -0.61 & ab \\\\\n 1 & \\{exp} 1 & -1.22 & \\{exp} cd \\\\\n \\end{{{inner_env}}}\n """\n )\n assert expected in result\n\n\ndef test_parse_latex_css_conversion_option():\n css = [("command", "option--latex--wrap")]\n expected = [("command", "option--wrap")]\n result = _parse_latex_css_conversion(css)\n assert result == expected\n\n\ndef test_styler_object_after_render(styler):\n # GH 42320\n pre_render = styler._copy(deepcopy=True)\n styler.to_latex(\n column_format="rllr",\n position="h",\n position_float="centering",\n hrules=True,\n label="my lab",\n caption="my cap",\n )\n\n assert pre_render.table_styles == styler.table_styles\n assert pre_render.caption == styler.caption\n\n\ndef test_longtable_comprehensive(styler):\n result = styler.to_latex(\n environment="longtable", hrules=True, label="fig:A", caption=("full", "short")\n )\n expected = dedent(\n """\\n \\begin{longtable}{lrrl}\n \\caption[short]{full} \\label{fig:A} \\\\\n \\toprule\n & A & B & C \\\\\n \\midrule\n \\endfirsthead\n \\caption[]{full} \\\\\n \\toprule\n & A & B & C \\\\\n \\midrule\n \\endhead\n \\midrule\n \\multicolumn{4}{r}{Continued on next page} \\\\\n \\midrule\n \\endfoot\n \\bottomrule\n \\endlastfoot\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\end{longtable}\n """\n )\n assert result == expected\n\n\ndef test_longtable_minimal(styler):\n result = styler.to_latex(environment="longtable")\n expected = dedent(\n """\\n \\begin{longtable}{lrrl}\n & A & B & C \\\\\n \\endfirsthead\n & A & B & C \\\\\n \\endhead\n \\multicolumn{4}{r}{Continued on next page} \\\\\n \\endfoot\n \\endlastfoot\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\end{longtable}\n """\n )\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "sparse, exp, siunitx",\n [\n (True, "{} & \\multicolumn{2}{r}{A} & {B}", True),\n (False, "{} & {A} & {A} & {B}", True),\n (True, " & \\multicolumn{2}{r}{A} & B", False),\n (False, " & A & A & B", False),\n ],\n)\ndef test_longtable_multiindex_columns(df, sparse, exp, siunitx):\n cidx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])\n df.columns = cidx\n with_si = "{} & {a} & {b} & {c} \\\\"\n without_si = " & a & b & c \\\\"\n expected = dedent(\n f"""\\n \\begin{{longtable}}{{l{"SS" if siunitx else "rr"}l}}\n {exp} \\\\\n {with_si if siunitx else without_si}\n \\endfirsthead\n {exp} \\\\\n {with_si if siunitx else without_si}\n \\endhead\n """\n )\n result = df.style.to_latex(\n environment="longtable", sparse_columns=sparse, siunitx=siunitx\n )\n assert expected in result\n\n\n@pytest.mark.parametrize(\n "caption, cap_exp",\n [\n ("full", ("{full}", "")),\n (("full", "short"), ("{full}", "[short]")),\n ],\n)\n@pytest.mark.parametrize("label, lab_exp", [(None, ""), ("tab:A", " \\label{tab:A}")])\ndef test_longtable_caption_label(styler, caption, cap_exp, label, lab_exp):\n cap_exp1 = f"\\caption{cap_exp[1]}{cap_exp[0]}"\n cap_exp2 = f"\\caption[]{cap_exp[0]}"\n\n expected = dedent(\n f"""\\n {cap_exp1}{lab_exp} \\\\\n & A & B & C \\\\\n \\endfirsthead\n {cap_exp2} \\\\\n """\n )\n assert expected in styler.to_latex(\n environment="longtable", caption=caption, label=label\n )\n\n\n@pytest.mark.parametrize("index", [True, False])\n@pytest.mark.parametrize(\n "columns, siunitx",\n [\n (True, True),\n (True, False),\n (False, False),\n ],\n)\ndef test_apply_map_header_render_mi(df_ext, index, columns, siunitx):\n cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")])\n ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")])\n df_ext.index, df_ext.columns = ridx, cidx\n styler = df_ext.style\n\n func = lambda v: "bfseries: --rwrap" if "A" in v or "Z" in v or "c" in v else None\n\n if index:\n styler.map_index(func, axis="index")\n if columns:\n styler.map_index(func, axis="columns")\n\n result = styler.to_latex(siunitx=siunitx)\n\n expected_index = dedent(\n """\\n \\multirow[c]{2}{*}{\\bfseries{A}} & a & 0 & -0.610000 & ab \\\\\n \\bfseries{} & b & 1 & -1.220000 & cd \\\\\n B & \\bfseries{c} & 2 & -2.220000 & de \\\\\n """\n )\n assert (expected_index in result) is index\n\n exp_cols_si = dedent(\n """\\n {} & {} & \\multicolumn{2}{r}{\\bfseries{Z}} & {Y} \\\\\n {} & {} & {a} & {b} & {\\bfseries{c}} \\\\\n """\n )\n exp_cols_no_si = """\\n & & \\multicolumn{2}{r}{\\bfseries{Z}} & Y \\\\\n & & a & b & \\bfseries{c} \\\\\n"""\n assert ((exp_cols_si if siunitx else exp_cols_no_si) in result) is columns\n\n\ndef test_repr_option(styler):\n assert "<style" in styler._repr_html_()[:6]\n assert styler._repr_latex_() is None\n with option_context("styler.render.repr", "latex"):\n assert "\\begin{tabular}" in styler._repr_latex_()[:15]\n assert styler._repr_html_() is None\n\n\n@pytest.mark.parametrize("option", ["hrules"])\ndef test_bool_options(styler, option):\n with option_context(f"styler.latex.{option}", False):\n latex_false = styler.to_latex()\n with option_context(f"styler.latex.{option}", True):\n latex_true = styler.to_latex()\n assert latex_false != latex_true # options are reactive under to_latex(*no_args)\n\n\ndef test_siunitx_basic_headers(styler):\n assert "{} & {A} & {B} & {C} \\\\" in styler.to_latex(siunitx=True)\n assert " & A & B & C \\\\" in styler.to_latex() # default siunitx=False\n\n\n@pytest.mark.parametrize("axis", ["index", "columns"])\ndef test_css_convert_apply_index(styler, axis):\n styler.map_index(lambda x: "font-weight: bold;", axis=axis)\n for label in getattr(styler, axis):\n assert f"\\bfseries {label}" in styler.to_latex(convert_css=True)\n\n\ndef test_hide_index_latex(styler):\n # GH 43637\n styler.hide([0], axis=0)\n result = styler.to_latex()\n expected = dedent(\n """\\n \\begin{tabular}{lrrl}\n & A & B & C \\\\\n 1 & 1 & -1.22 & cd \\\\\n \\end{tabular}\n """\n )\n assert expected == result\n\n\ndef test_latex_hiding_index_columns_multiindex_alignment():\n # gh 43644\n midx = MultiIndex.from_product(\n [["i0", "j0"], ["i1"], ["i2", "j2"]], names=["i-0", "i-1", "i-2"]\n )\n cidx = MultiIndex.from_product(\n [["c0"], ["c1", "d1"], ["c2", "d2"]], names=["c-0", "c-1", "c-2"]\n )\n df = DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=cidx)\n styler = Styler(df, uuid_len=0)\n styler.hide(level=1, axis=0).hide(level=0, axis=1)\n styler.hide([("i0", "i1", "i2")], axis=0)\n styler.hide([("c0", "c1", "c2")], axis=1)\n styler.map(lambda x: "color:{red};" if x == 5 else "")\n styler.map_index(lambda x: "color:{blue};" if "j" in x else "")\n result = styler.to_latex()\n expected = dedent(\n """\\n \\begin{tabular}{llrrr}\n & c-1 & c1 & \\multicolumn{2}{r}{d1} \\\\\n & c-2 & d2 & c2 & d2 \\\\\n i-0 & i-2 & & & \\\\\n i0 & \\color{blue} j2 & \\color{red} 5 & 6 & 7 \\\\\n \\multirow[c]{2}{*}{\\color{blue} j0} & i2 & 9 & 10 & 11 \\\\\n \\color{blue} & \\color{blue} j2 & 13 & 14 & 15 \\\\\n \\end{tabular}\n """\n )\n assert result == expected\n\n\ndef test_rendered_links():\n # note the majority of testing is done in test_html.py: test_rendered_links\n # these test only the alternative latex format is functional\n df = DataFrame(["text www.domain.com text"])\n result = df.style.format(hyperlinks="latex").to_latex()\n assert r"text \href{www.domain.com}{www.domain.com} text" in result\n\n\ndef test_apply_index_hidden_levels():\n # gh 45156\n styler = DataFrame(\n [[1]],\n index=MultiIndex.from_tuples([(0, 1)], names=["l0", "l1"]),\n columns=MultiIndex.from_tuples([(0, 1)], names=["c0", "c1"]),\n ).style\n styler.hide(level=1)\n styler.map_index(lambda v: "color: red;", level=0, axis=1)\n result = styler.to_latex(convert_css=True)\n expected = dedent(\n """\\n \\begin{tabular}{lr}\n c0 & \\color{red} 0 \\\\\n c1 & 1 \\\\\n l0 & \\\\\n 0 & 1 \\\\\n \\end{tabular}\n """\n )\n assert result == expected\n\n\n@pytest.mark.parametrize("clines", ["bad", "index", "skip-last", "all", "data"])\ndef test_clines_validation(clines, styler):\n msg = f"`clines` value of {clines} is invalid."\n with pytest.raises(ValueError, match=msg):\n styler.to_latex(clines=clines)\n\n\n@pytest.mark.parametrize(\n "clines, exp",\n [\n ("all;index", "\n\\cline{1-1}"),\n ("all;data", "\n\\cline{1-2}"),\n ("skip-last;index", ""),\n ("skip-last;data", ""),\n (None, ""),\n ],\n)\n@pytest.mark.parametrize("env", ["table", "longtable"])\ndef test_clines_index(clines, exp, env):\n df = DataFrame([[1], [2], [3], [4]])\n result = df.style.to_latex(clines=clines, environment=env)\n expected = f"""\\n0 & 1 \\\\{exp}\n1 & 2 \\\\{exp}\n2 & 3 \\\\{exp}\n3 & 4 \\\\{exp}\n"""\n assert expected in result\n\n\n@pytest.mark.parametrize(\n "clines, expected",\n [\n (\n None,\n dedent(\n """\\n \\multirow[c]{2}{*}{A} & X & 1 \\\\\n & Y & 2 \\\\\n \\multirow[c]{2}{*}{B} & X & 3 \\\\\n & Y & 4 \\\\\n """\n ),\n ),\n (\n "skip-last;index",\n dedent(\n """\\n \\multirow[c]{2}{*}{A} & X & 1 \\\\\n & Y & 2 \\\\\n \\cline{1-2}\n \\multirow[c]{2}{*}{B} & X & 3 \\\\\n & Y & 4 \\\\\n \\cline{1-2}\n """\n ),\n ),\n (\n "skip-last;data",\n dedent(\n """\\n \\multirow[c]{2}{*}{A} & X & 1 \\\\\n & Y & 2 \\\\\n \\cline{1-3}\n \\multirow[c]{2}{*}{B} & X & 3 \\\\\n & Y & 4 \\\\\n \\cline{1-3}\n """\n ),\n ),\n (\n "all;index",\n dedent(\n """\\n \\multirow[c]{2}{*}{A} & X & 1 \\\\\n \\cline{2-2}\n & Y & 2 \\\\\n \\cline{1-2} \\cline{2-2}\n \\multirow[c]{2}{*}{B} & X & 3 \\\\\n \\cline{2-2}\n & Y & 4 \\\\\n \\cline{1-2} \\cline{2-2}\n """\n ),\n ),\n (\n "all;data",\n dedent(\n """\\n \\multirow[c]{2}{*}{A} & X & 1 \\\\\n \\cline{2-3}\n & Y & 2 \\\\\n \\cline{1-3} \\cline{2-3}\n \\multirow[c]{2}{*}{B} & X & 3 \\\\\n \\cline{2-3}\n & Y & 4 \\\\\n \\cline{1-3} \\cline{2-3}\n """\n ),\n ),\n ],\n)\n@pytest.mark.parametrize("env", ["table"])\ndef test_clines_multiindex(clines, expected, env):\n # also tests simultaneously with hidden rows and a hidden multiindex level\n midx = MultiIndex.from_product([["A", "-", "B"], [0], ["X", "Y"]])\n df = DataFrame([[1], [2], [99], [99], [3], [4]], index=midx)\n styler = df.style\n styler.hide([("-", 0, "X"), ("-", 0, "Y")])\n styler.hide(level=1)\n result = styler.to_latex(clines=clines, environment=env)\n assert expected in result\n\n\ndef test_col_format_len(styler):\n # gh 46037\n result = styler.to_latex(environment="longtable", column_format="lrr{10cm}")\n expected = r"\multicolumn{4}{r}{Continued on next page} \\"\n assert expected in result\n\n\ndef test_concat(styler):\n result = styler.concat(styler.data.agg(["sum"]).style).to_latex()\n expected = dedent(\n """\\n \\begin{tabular}{lrrl}\n & A & B & C \\\\\n 0 & 0 & -0.61 & ab \\\\\n 1 & 1 & -1.22 & cd \\\\\n sum & 1 & -1.830000 & abcd \\\\\n \\end{tabular}\n """\n )\n assert result == expected\n\n\ndef test_concat_recursion():\n # tests hidden row recursion and applied styles\n styler1 = DataFrame([[1], [9]]).style.hide([1]).highlight_min(color="red")\n styler2 = DataFrame([[9], [2]]).style.hide([0]).highlight_min(color="green")\n styler3 = DataFrame([[3], [9]]).style.hide([1]).highlight_min(color="blue")\n\n result = styler1.concat(styler2.concat(styler3)).to_latex(convert_css=True)\n expected = dedent(\n """\\n \\begin{tabular}{lr}\n & 0 \\\\\n 0 & {\\cellcolor{red}} 1 \\\\\n 1 & {\\cellcolor{green}} 2 \\\\\n 0 & {\\cellcolor{blue}} 3 \\\\\n \\end{tabular}\n """\n )\n assert result == expected\n\n\ndef test_concat_chain():\n # tests hidden row recursion and applied styles\n styler1 = DataFrame([[1], [9]]).style.hide([1]).highlight_min(color="red")\n styler2 = DataFrame([[9], [2]]).style.hide([0]).highlight_min(color="green")\n styler3 = DataFrame([[3], [9]]).style.hide([1]).highlight_min(color="blue")\n\n result = styler1.concat(styler2).concat(styler3).to_latex(convert_css=True)\n expected = dedent(\n """\\n \\begin{tabular}{lr}\n & 0 \\\\\n 0 & {\\cellcolor{red}} 1 \\\\\n 1 & {\\cellcolor{green}} 2 \\\\\n 0 & {\\cellcolor{blue}} 3 \\\\\n \\end{tabular}\n """\n )\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "df, expected",\n [\n (\n DataFrame(),\n dedent(\n """\\n \\begin{tabular}{l}\n \\end{tabular}\n """\n ),\n ),\n (\n DataFrame(columns=["a", "b", "c"]),\n dedent(\n """\\n \\begin{tabular}{llll}\n & a & b & c \\\\\n \\end{tabular}\n """\n ),\n ),\n ],\n)\n@pytest.mark.parametrize(\n "clines", [None, "all;data", "all;index", "skip-last;data", "skip-last;index"]\n)\ndef test_empty_clines(df: DataFrame, expected: str, clines: str):\n # GH 47203\n result = df.style.to_latex(clines=clines)\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\io\formats\style\test_to_latex.py
test_to_latex.py
Python
33,008
0.95
0.06422
0.018908
python-kit
857
2025-03-05T01:49:09.020663
GPL-3.0
true
bb24f81a2f72ad2ebc28e5ed6ffff6e9