Source code for bigframes.operations.strings

# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import re
from typing import Generic, Hashable, Literal, Optional, TypeVar, Union

import bigframes_vendored.constants as constants
import bigframes_vendored.pandas.core.strings.accessor as vendorstr

import bigframes.core.col
import bigframes.core.indexes.base as indices
import bigframes.dataframe as df
import bigframes.operations as ops
import bigframes.operations.aggregations as agg_ops
import bigframes.series as series
from bigframes._tools import docs
from bigframes.core.logging import log_adapter
from bigframes.operations._op_converters import convert_index, convert_slice

# Maps from python to re2
REGEXP_FLAGS = {
    re.IGNORECASE: "i",
    re.MULTILINE: "m",
    re.DOTALL: "s",
}

T = TypeVar("T", series.Series, indices.Index, bigframes.core.col.Expression)


[docs] @log_adapter.class_logger @docs.inherit_docs(vendorstr.StringMethods) class StringMethods(Generic[T]):
[docs] def __init__(self, data: T): self._data: T = data
def __getitem__(self, key: Union[int, slice]) -> T: if isinstance(key, int): return self._data._apply_unary_op(convert_index(key)) elif isinstance(key, slice): return self._data._apply_unary_op(convert_slice(key)) else: raise ValueError(f"key must be an int or slice, got {type(key).__name__}")
[docs] def find( self, sub: str, start: Optional[int] = None, end: Optional[int] = None, ) -> T: return self._data._apply_unary_op( ops.StrFindOp(substr=sub, start=start, end=end) )
[docs] def len(self) -> T: return self._data._apply_unary_op(ops.len_op)
[docs] def lower(self) -> T: return self._data._apply_unary_op(ops.lower_op)
[docs] def reverse(self) -> T: """Reverse strings in the Series. **Examples:** >>> import bigframes.pandas as bpd >>> s = bpd.Series(["apple", "banana", "", pd.NA]) >>> s.str.reverse() 0 elppa 1 ananab 2 3 <NA> dtype: string Returns: bigframes.series.Series: A Series of booleans indicating whether the given pattern matches the start of each string element. """ # reverse method is in ibis, not pandas. return self._data._apply_unary_op(ops.reverse_op)
[docs] def slice( self, start: Optional