from datetime import ( datetime, timedelta, ) import re import numpy as np import pytest from pandas.compat import pa_version_under21p0 import pandas as pd import pandas._testing as tm from pandas.core.strings.accessor import StringMethods from pandas.tests.strings import is_object_or_nan_string_dtype @pytest.mark.parametrize("pattern", [0, True, pd.Series(["foo", "bar"])]) def test_startswith_endswith_non_str_patterns(pattern): # GH3485 ser = pd.Series(["foo", "bar"]) msg = f"expected a string or tuple, not {type(pattern).__name__}" with pytest.raises(TypeError, match=msg): ser.str.startswith(pattern) with pytest.raises(TypeError, match=msg): ser.str.endswith(pattern) def test_iter_raises(): # GH 54173 ser = pd.Series(["foo", "bar"]) with pytest.raises(TypeError, match="'StringMethods' object is not iterable"): iter(ser.str) # test integer/float dtypes (inferred by constructor) and mixed def test_count(any_string_dtype): ser = pd.Series( ["foo", "foofoo", np.nan, "foooofooofommmfoo"], dtype=any_string_dtype ) result = ser.str.count("f[o]+") if is_object_or_nan_string_dtype(any_string_dtype): expected_dtype = np.float64 item = np.nan else: expected_dtype = "Int64" item = pd.NA expected = pd.Series([1, 2, item, 4], dtype=expected_dtype) tm.assert_series_equal(result, expected) def test_count_mixed_object(): ser = pd.Series( ["a", np.nan, "b", True, datetime(2011, 1, 1), "foo", None, 1, 2.0], dtype=object, ) result = ser.str.count("a") expected = pd.Series([1, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, np.nan]) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "pat, expected_data", [ (r"a(?=b)", [0, 1, 0, 0, None]), (r"(?<=a)b", [0, 1, 0, 0, None]), (r"a(?!b)", [2, 0, 1, 0, None]), (r"(?" ) with pytest.raises(UnicodeEncodeError, match=msg): ser.str.encode("cp1252") result = ser.str.encode("cp1252", "ignore") expected = ser.map(lambda x: x.encode("cp1252", "ignore")) # GH#62164 map may retain dtype backend (e.g. binary[pyarrow]) tm.assert_series_equal(result, expected, check_dtype=False) def test_decode_errors_kwarg(): ser = pd.Series([b"a", b"b", b"a\x9d"]) msg = ( "'charmap' codec can't decode byte 0x9d in position 1: " "character maps to " ) with pytest.raises(UnicodeDecodeError, match=msg): ser.str.decode("cp1252") result = ser.str.decode("cp1252", "ignore") expected = ser.map(lambda x: x.decode("cp1252", "ignore")).astype("str") tm.assert_series_equal(result, expected) def test_decode_string_dtype(string_dtype): # https://github.com/pandas-dev/pandas/pull/60940 ser = pd.Series([b"a", b"b"]) result = ser.str.decode("utf-8", dtype=string_dtype) expected = pd.Series(["a", "b"], dtype=string_dtype) tm.assert_series_equal(result, expected) def test_decode_object_dtype(object_dtype): # https://github.com/pandas-dev/pandas/pull/60940 ser = pd.Series([b"a", rb"\ud800"]) result = ser.str.decode("utf-8", dtype=object_dtype) expected = pd.Series(["a", r"\ud800"], dtype=object_dtype) tm.assert_series_equal(result, expected) def test_decode_bad_dtype(): # https://github.com/pandas-dev/pandas/pull/60940 ser = pd.Series([b"a", b"b"]) msg = "dtype must be string or object, got dtype='int64'" with pytest.raises(ValueError, match=msg): ser.str.decode("utf-8", dtype="int64") @pytest.mark.parametrize( "form, expected", [ ("NFKC", ["ABC", "ABC", "123", np.nan, "アイエ"]), ("NFC", ["ABC", "ABC", "123", np.nan, "アイエ"]), # noqa: RUF001 ], ) def test_normalize(form, expected, any_string_dtype): ser = pd.Series( ["ABC", "ABC", "123", np.nan, "アイエ"], # noqa: RUF001 index=["a", "b", "c", "d", "e"], dtype=any_string_dtype, ) expected = pd.Series( expected, index=["a", "b", "c", "d", "e"], dtype=any_string_dtype ) result = ser.str.normalize(form) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "method, args", [("normalize", ("NFC",)), ("normalize", ("NFKC",)), ("zfill", (5,))] ) def test_str_empty_filter_elementwise_fallback(method, args, any_string_dtype): # GH#64359 an all-False filter leaves an arrow-backed array with zero chunks, # which the elementwise fallbacks used to rebuild without a type ser = pd.Series(["Café", "éclair"], dtype=any_string_dtype) expected = ser[ser == "zzz"] result = getattr(expected.str, method)(*args) tm.assert_series_equal(result, expected) def test_normalize_bad_arg_raises(any_string_dtype): ser = pd.Series( ["ABC", "ABC", "123", np.nan, "アイエ"], # noqa: RUF001 index=["a", "b", "c", "d", "e"], dtype=any_string_dtype, ) with pytest.raises(ValueError, match="invalid normalization form"): ser.str.normalize("xxx") def test_normalize_index(): idx = pd.Index(["ABC", "123", "アイエ"]) # noqa: RUF001 expected = pd.Index(["ABC", "123", "アイエ"]) result = idx.str.normalize("NFKC") tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "values,inferred_type", [ (["a", "b"], "string"), (["a", "b", 1], "mixed-integer"), (["a", "b", 1.3], "mixed"), (["a", "b", 1.3, 1], "mixed-integer"), (["aa", datetime(2011, 1, 1)], "mixed"), ], ) def test_index_str_accessor_visibility(values, inferred_type, index_or_series): obj = index_or_series(values) if index_or_series is pd.Index: assert obj.inferred_type == inferred_type assert isinstance(obj.str, StringMethods) @pytest.mark.parametrize( "values,inferred_type", [ ([1, np.nan], "floating"), ([datetime(2011, 1, 1)], "datetime64"), ([timedelta(1)], "timedelta64"), ], ) def test_index_str_accessor_non_string_values_raises( values, inferred_type, index_or_series ): obj = index_or_series(values) if index_or_series is pd.Index: assert obj.inferred_type == inferred_type msg = "Can only use .str accessor with string values" with pytest.raises(AttributeError, match=msg): obj.str def test_index_str_accessor_multiindex_raises(): # MultiIndex has mixed dtype, but not allow to use accessor idx = pd.MultiIndex.from_tuples([("a", "b"), ("a", "b")]) assert idx.inferred_type == "mixed" msg = "Can only use .str accessor with Index, not MultiIndex" with pytest.raises(AttributeError, match=msg): idx.str def test_str_accessor_no_new_attributes(any_string_dtype): # https://github.com/pandas-dev/pandas/issues/10673 ser = pd.Series(list("aabbcde"), dtype=any_string_dtype) with pytest.raises(AttributeError, match="You cannot add any new attribute"): ser.str.xlabel = "a" def test_cat_on_bytes_raises(): lhs = pd.Series(np.array(list("abc"), "S1").astype(object)) rhs = pd.Series(np.array(list("def"), "S1").astype(object)) msg = "Cannot use .str.cat with values of inferred dtype 'bytes'" with pytest.raises(TypeError, match=msg): lhs.str.cat(rhs) def test_str_accessor_in_apply_func(): # https://github.com/pandas-dev/pandas/issues/38979 df = pd.DataFrame(zip("abc", "def", strict=True)) expected = pd.Series(["A/D", "B/E", "C/F"]) result = df.apply(lambda f: "/".join(f.str.upper()), axis=1) tm.assert_series_equal(result, expected) def test_zfill(): # https://github.com/pandas-dev/pandas/issues/20868 value = pd.Series(["-1", "1", "1000", 10, np.nan]) expected = pd.Series(["-01", "001", "1000", np.nan, np.nan], dtype=object) tm.assert_series_equal(value.str.zfill(3), expected) value = pd.Series(["-2", "+5"]) expected = pd.Series(["-0002", "+0005"]) tm.assert_series_equal(value.str.zfill(5), expected) def test_zfill_with_non_integer_argument(): value = pd.Series(["-2", "+5"]) wid = "a" msg = f"width must be of integer type, not {type(wid).__name__}" with pytest.raises(TypeError, match=msg): value.str.zfill(wid) def test_zfill_with_leading_sign(): value = pd.Series(["-cat", "-1", "+dog"]) expected = pd.Series(["-0cat", "-0001", "+0dog"]) tm.assert_series_equal(value.str.zfill(5), expected) def test_get_with_dict_label(): # GH47911 s = pd.Series( [ {"name": "Hello", "value": "World"}, {"name": "Goodbye", "value": "Planet"}, {"value": "Sea"}, ] ) result = s.str.get("name") expected = pd.Series(["Hello", "Goodbye", None], dtype=object) tm.assert_series_equal(result, expected) result = s.str.get("value") expected = pd.Series(["World", "Planet", "Sea"], dtype=object) tm.assert_series_equal(result, expected) def test_series_str_decode(): # GH 22613 result = pd.Series([b"x", b"y"]).str.decode(encoding="UTF-8", errors="strict") expected = pd.Series(["x", "y"], dtype="str") tm.assert_series_equal(result, expected) @pytest.mark.filterwarnings( "ignore:The 'future.infer_string' option:pandas.errors.Pandas4Warning" ) def test_decode_with_dtype_none(): with pd.option_context("future.infer_string", True): ser = pd.Series([b"a", b"b", b"c"]) result = ser.str.decode("utf-8", dtype=None) expected = pd.Series(["a", "b", "c"], dtype="str") tm.assert_series_equal(result, expected) def test_setitem_with_different_string_storage(): # GH#52987 # Test setitem with values from different string storage type pytest.importorskip("pyarrow") # Test Series[string[python]].__setitem__(Series[string[pyarrow]]) ser_python = pd.Series(range(5), dtype="string[python]") ser_pyarrow = ser_python.astype("string[pyarrow]") ser_python[:2] = ser_pyarrow[:2] expected = pd.Series(["0", "1", "2", "3", "4"], dtype="string[python]") tm.assert_series_equal(ser_python, expected) # Test Series[string[pyarrow]].__setitem__(Series[string[python]]) ser_pyarrow = pd.Series(range(5), dtype="string[pyarrow]") ser_python = ser_pyarrow.astype("string[python]") ser_pyarrow[:2] = ser_python[:2] expected = pd.Series(["0", "1", "2", "3", "4"], dtype="string[pyarrow]") tm.assert_series_equal(ser_pyarrow, expected) # Test with slice and missing values ser_python = pd.Series(["a", "b", None, "d", "e"], dtype="string[python]") ser_pyarrow = pd.Series(["X", "Y", None], dtype="string[pyarrow]") ser_python[1:4] = ser_pyarrow expected = pd.Series(["a", "X", "Y", pd.NA, "e"], dtype="string[python]") tm.assert_series_equal(ser_python, expected) @pytest.mark.parametrize( "pat, expected", [ # lookaround assertions (r"(?=abc)", True), (r"(?<=123)", True), (r"(?!xyz)", True), (r"(?\w+)\s+(?P=word)\b", True), # unicode escape sequences (r"\u20AC", True), (r"\U000020AC", True), (r"\N{EURO SIGN}", True), (r"\\u20AC", False), (r"\\U000020AC", False), (r"\\N{EURO SIGN}", False), (r"\NEURO", False), (r"\\\u20AC", True), (r"\\\\u20AC", False), (r"[\u0e00-\u0e7f]", True), (r"\pL\u20AC", True), # also includes an invalid escape \p for Python (r"\Q\u\E", True), # \Q..\E pattern supported by pyarrow, but prioritize \u ], ) def test_needs_python_regex_unsupported_code(pat, expected): # https://github.com/pandas-dev/pandas/issues/60833 pytest.importorskip("pyarrow") arr = pd.array(["abc"], dtype=pd.StringDtype("pyarrow")) assert arr._needs_python_regex(pat) == expected @pytest.mark.parametrize( "pat, expected", [ (r"\w+", True), (r"\W", True), (r"\d{3}", True), (r"\D", True), (r"\s+", True), (r"\S", True), (r"\bword\b", True), (r"\B", True), (r"[^\w\s]", True), (r"[\w-]", True), (r"(?:x\S)*", True), (r"(foo|bar\d)", True), (r"(?>\w)", True), (r"[a-z0-9_]+", False), (r"\\w", False), (r"abc", False), (r"", False), ], ) def test_needs_python_regex_unicode_classes(pat, expected): # GH#70770 pytest.importorskip("pyarrow") arr = pd.array(["é"], dtype=pd.StringDtype("pyarrow")) assert arr._needs_python_regex(pat) == expected # all-ASCII data keeps the pyarrow path ascii_arr = pd.array(["e", None], dtype=pd.StringDtype("pyarrow")) assert not ascii_arr._needs_python_regex(pat) @pytest.mark.parametrize( "pat, expected", [ (r"test$", True), (r"test\$", False), (r"r[$]", False), ], ) def test_needs_python_regex_newline_sensitive(pat, expected): # https://github.com/pandas-dev/pandas/pull/71387 pytest.importorskip("pyarrow") arr = pd.array(["test\n"], dtype=pd.StringDtype("pyarrow")) assert arr._needs_python_regex(pat) == expected arr = pd.array(["test\ntest", None], dtype=pd.StringDtype("pyarrow")) assert arr._needs_python_regex(pat) == expected # data without newlines keeps the pyarrow path arr_no_newline = pd.array(["e", None], dtype=pd.StringDtype("pyarrow")) assert not arr_no_newline._needs_python_regex(pat)