Skip to content

[ArrowStringArray] REF: str.extract argument validation #41418

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions pandas/core/strings/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@
from functools import wraps
import re
from typing import (
TYPE_CHECKING,
Dict,
Hashable,
List,
Optional,
Pattern,
Union,
)
import warnings

import numpy as np

import pandas._libs.lib as lib
from pandas._typing import FrameOrSeriesUnion
from pandas.util._decorators import Appender

from pandas.core.dtypes.common import (
Expand All @@ -33,6 +36,9 @@

from pandas.core.base import NoNewAttributesMixin

if TYPE_CHECKING:
from pandas import Index

_shared_docs: Dict[str, str] = {}
_cpython_optimized_encoders = (
"utf-8",
Expand Down Expand Up @@ -2276,7 +2282,9 @@ def findall(self, pat, flags=0):
return self._wrap_result(result, returns_string=False)

@forbid_nonstring_types(["bytes"])
def extract(self, pat, flags=0, expand=True):
def extract(
self, pat: str, flags: int = 0, expand: bool = True
) -> Union[FrameOrSeriesUnion, "Index"]:
r"""
Extract capture groups in the regex `pat` as columns in a DataFrame.

Expand Down Expand Up @@ -2357,6 +2365,16 @@ def extract(self, pat, flags=0, expand=True):
2 NaN
dtype: object
"""
if not isinstance(expand, bool):
raise ValueError("expand must be True or False")

regex = re.compile(pat, flags=flags)
if regex.groups == 0:
raise ValueError("pattern contains no capture groups")

if not expand and regex.groups > 1 and isinstance(self._data, ABCIndex):
raise ValueError("only one regex group is supported with Index")

# TODO: dispatch
return str_extract(self, pat, flags, expand=expand)

Expand Down Expand Up @@ -3010,8 +3028,6 @@ def cat_core(list_of_columns: List, sep: str):

def _groups_or_na_fun(regex):
"""Used in both extract_noexpand and extract_frame"""
if regex.groups == 0:
raise ValueError("pattern contains no capture groups")
empty_row = [np.nan] * regex.groups

def f(x):
Expand Down Expand Up @@ -3086,8 +3102,6 @@ def _str_extract_noexpand(arr, pat, flags=0):
# not dispatching, so we have to reconstruct here.
result = pd_array(result, dtype=result_dtype)
else:
if isinstance(arr, ABCIndex):
raise ValueError("only one regex group is supported with Index")
name = None
columns = _get_group_names(regex)
if arr.size == 0:
Expand Down Expand Up @@ -3138,8 +3152,6 @@ def _str_extract_frame(arr, pat, flags=0):


def str_extract(arr, pat, flags=0, expand=True):
if not isinstance(expand, bool):
raise ValueError("expand must be True or False")
if expand:
result = _str_extract_frame(arr._orig, pat, flags=flags)
return result.__finalize__(arr._orig, method="str_extract")
Expand Down