text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_all(prefix, ignore_deprecated=False):
""" Execute the validation of all docstrings, and return a dict with the results. Parameters prefix : str or N... |
result = {}
seen = {}
# functions from the API docs
api_doc_fnames = os.path.join(
BASE_PATH, 'doc', 'source', 'reference', '*.rst')
api_items = []
for api_doc_fname in glob.glob(api_doc_fnames):
with open(api_doc_fname) as f:
api_items += list(get_api_items(f))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_obj(name):
""" Import Python object from its name as string. Parameters name : str Object name to import (e.g. pandas.Series.str.upper) Returns -------... |
for maxsplit in range(1, name.count('.') + 1):
# TODO when py3 only replace by: module, *func_parts = ...
func_name_split = name.rsplit('.', maxsplit)
module = func_name_split[0]
func_parts = func_name_split[1:]
try:
obj = importlib.im... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _to_original_callable(obj):
""" Find the Python object that contains the source code of the object. This is useful to find the place in the source code (file... |
while True:
if inspect.isfunction(obj) or inspect.isclass(obj):
f = inspect.getfile(obj)
if f.startswith('<') and f.endswith('>'):
return None
return obj
if inspect.ismethod(obj):
obj = obj.__func__
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def method_returns_something(self):
'''
Check if the docstrings method can return something.
Bare returns, returns valued None and returns from nested functions are
disconsidered.
Returns
-------
bool
Whether the docstrings method can return somethin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _value_with_fmt(self, val):
"""Convert numpy types to Python types for the Excel writers. Parameters val : object Value to be written into cells Returns ----... |
fmt = None
if is_integer(val):
val = int(val)
elif is_float(val):
val = float(val)
elif is_bool(val):
val = bool(val)
elif isinstance(val, datetime):
fmt = self.datetime_format
elif isinstance(val, date):
fmt =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_extension(cls, ext):
"""checks that path's extension against the Writer's supported extensions. If it isn't supported, raises UnsupportedFiletypeError.... |
if ext.startswith('.'):
ext = ext[1:]
if not any(ext in extension for extension in cls.supported_extensions):
msg = ("Invalid extension for engine '{engine}': '{ext}'"
.format(engine=pprint_thing(cls.engine),
ext=pprint_thing(ext)))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_where(w):
""" Validate that the where statement is of the right type. The type may either be String, Expr, or list-like of Exprs. Parameters w : St... |
if not (isinstance(w, (Expr, str)) or is_list_like(w)):
raise TypeError("where must be passed as a string, Expr, "
"or list-like of Exprs")
return w |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maybe_expression(s):
""" loose checking if s is a pytables-acceptable expression """ |
if not isinstance(s, str):
return False
ops = ExprVisitor.binary_ops + ExprVisitor.unary_ops + ('=',)
# make sure we have an op at least
return any(op in s for op in ops) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conform(self, rhs):
""" inplace conform rhs """ |
if not is_list_like(rhs):
rhs = [rhs]
if isinstance(rhs, np.ndarray):
rhs = rhs.ravel()
return rhs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(self, v):
""" create and return the op string for this TermValue """ |
val = v.tostring(self.encoding)
return "({lhs} {op} {val})".format(lhs=self.lhs, op=self.op, val=val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_value(self, v):
""" convert the expression that is in the term to something that is accepted by pytables """ |
def stringify(value):
if self.encoding is not None:
encoder = partial(pprint_thing_encoded,
encoding=self.encoding)
else:
encoder = pprint_thing
return encoder(value)
kind = _ensure_decoded(self.kind... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invert(self):
""" invert the filter """ |
if self.filter is not None:
f = list(self.filter)
f[1] = self.generate_filter_op(invert=True)
self.filter = tuple(f)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(self):
""" create and return the numexpr condition and filter """ |
try:
self.condition = self.terms.prune(ConditionBinOp)
except AttributeError:
raise ValueError("cannot process expression [{expr}], [{slf}] "
"is not a valid condition".format(expr=self.expr,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tostring(self, encoding):
""" quote the string if not encoded else encode and return """ |
if self.kind == 'string':
if encoding is not None:
return self.converted
return '"{converted}"'.format(converted=self.converted)
elif self.kind == 'float':
# python 2 str(float) is not always
# round-trippable so use repr()
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_argmin_with_skipna(skipna, args, kwargs):
""" If 'Series.argmin' is called via the 'numpy' library, the third parameter in its signature is 'out', w... |
skipna, args = process_skipna(skipna, args)
validate_argmin(args, kwargs)
return skipna |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_argmax_with_skipna(skipna, args, kwargs):
""" If 'Series.argmax' is called via the 'numpy' library, the third parameter in its signature is 'out', w... |
skipna, args = process_skipna(skipna, args)
validate_argmax(args, kwargs)
return skipna |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_argsort_with_ascending(ascending, args, kwargs):
""" If 'Categorical.argsort' is called via the 'numpy' library, the first parameter in its signatur... |
if is_integer(ascending) or ascending is None:
args = (ascending,) + args
ascending = True
validate_argsort_kind(args, kwargs, max_fname_arg_count=3)
return ascending |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_clip_with_axis(axis, args, kwargs):
""" If 'NDFrame.clip' is called via the numpy library, the third parameter in its signature is 'out', which can ... |
if isinstance(axis, ndarray):
args = (axis,) + args
axis = None
validate_clip(args, kwargs)
return axis |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_cum_func_with_skipna(skipna, args, kwargs, name):
""" If this function is called via the 'numpy' library, the third parameter in its signature is 'd... |
if not is_bool(skipna):
args = (skipna,) + args
skipna = True
validate_cum_func(args, kwargs, fname=name)
return skipna |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_take_with_convert(convert, args, kwargs):
""" If this function is called via the 'numpy' library, the third parameter in its signature is 'axis', wh... |
if isinstance(convert, ndarray) or convert is None:
args = (convert,) + args
convert = True
validate_take(args, kwargs, max_fname_arg_count=3, method='both')
return convert |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_groupby_func(name, args, kwargs, allowed=None):
""" 'args' and 'kwargs' should be empty, except for allowed kwargs because all of their necessary pa... |
if allowed is None:
allowed = []
kwargs = set(kwargs) - set(allowed)
if len(args) + len(kwargs) > 0:
raise UnsupportedFunctionCall((
"numpy operations are not valid "
"with groupby. Use .groupby(...)."
"{func}() instead".format(func=name))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_resampler_func(method, args, kwargs):
""" 'args' and 'kwargs' should be empty because all of their necessary parameters are explicitly listed in the... |
if len(args) + len(kwargs) > 0:
if method in RESAMPLER_NUMPY_OPS:
raise UnsupportedFunctionCall((
"numpy operations are not valid "
"with resample. Use .resample(...)."
"{func}() instead".format(func=method)))
else:
raise TypeE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_minmax_axis(axis):
""" Ensure that the axis argument passed to min, max, argmin, or argmax is zero or None, as otherwise it will be incorrectly igno... |
ndim = 1 # hard-coded for Index
if axis is None:
return
if axis >= ndim or (axis < 0 and ndim + axis < 0):
raise ValueError("`axis` must be fewer than the number of "
"dimensions ({ndim})".format(ndim=ndim)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_msgpack(path_or_buf, encoding='utf-8', iterator=False, **kwargs):
""" Load msgpack pandas object from the specified file path THIS IS AN EXPERIMENTAL LI... |
path_or_buf, _, _, should_close = get_filepath_or_buffer(path_or_buf)
if iterator:
return Iterator(path_or_buf)
def read(fh):
unpacked_obj = list(unpack(fh, encoding=encoding, **kwargs))
if len(unpacked_obj) == 1:
return unpacked_obj[0]
if should_close:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dtype_for(t):
""" return my dtype mapping, whether number or name """ |
if t in dtype_dict:
return dtype_dict[t]
return np.typeDict.get(t, t) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def c2f(r, i, ctype_name):
""" Convert strings to complex number instance with specified numpy type. """ |
ftype = c2f_dict[ctype_name]
return np.typeDict[ctype_name](ftype(r) + 1j * ftype(i)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(values):
""" convert the numpy values to a list """ |
dtype = values.dtype
if is_categorical_dtype(values):
return values
elif is_object_dtype(dtype):
return values.ravel().tolist()
if needs_i8_conversion(dtype):
values = values.view('i8')
v = values.ravel()
if compressor == 'zlib':
_check_zlib()
# ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pack(o, default=encode, encoding='utf-8', unicode_errors='strict', use_single_float=False, autoreset=1, use_bin_type=1):
""" Pack an object and return the pa... |
return Packer(default=default, encoding=encoding,
unicode_errors=unicode_errors,
use_single_float=use_single_float,
autoreset=autoreset,
use_bin_type=use_bin_type).pack(o) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_json(path_or_buf=None, orient=None, typ='frame', dtype=None, convert_axes=None, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=F... |
if orient == 'table' and dtype:
raise ValueError("cannot pass both dtype and orient='table'")
if orient == 'table' and convert_axes:
raise ValueError("cannot pass both convert_axes and orient='table'")
if dtype is None and orient != 'table':
dtype = True
if convert_axes is Non... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_axes(self):
""" Try to format axes if they are datelike. """ |
if not self.obj.index.is_unique and self.orient in (
'index', 'columns'):
raise ValueError("DataFrame index must be unique for orient="
"'{orient}'.".format(orient=self.orient))
if not self.obj.columns.is_unique and self.orient in (
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _combine_lines(self, lines):
""" Combines a list of JSON objects into one JSON object. """ |
lines = filter(None, map(lambda x: x.strip(), lines))
return '[' + ','.join(lines) + ']' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self):
""" Read the whole JSON input into a pandas object. """ |
if self.lines and self.chunksize:
obj = concat(self)
elif self.lines:
data = to_str(self.data)
obj = self._get_object_parser(
self._combine_lines(data.split('\n'))
)
else:
obj = self._get_object_parser(self.data)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_object_parser(self, json):
""" Parses a json document into a pandas object. """ |
typ = self.typ
dtype = self.dtype
kwargs = {
"orient": self.orient, "dtype": self.dtype,
"convert_axes": self.convert_axes,
"convert_dates": self.convert_dates,
"keep_default_dates": self.keep_default_dates, "numpy": self.numpy,
"preci... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_keys_split(self, decoded):
""" Checks that dict has only the appropriate keys for orient='split'. """ |
bad_keys = set(decoded.keys()).difference(set(self._split_keys))
if bad_keys:
bad_keys = ", ".join(bad_keys)
raise ValueError("JSON data had unexpected key(s): {bad_keys}"
.format(bad_keys=pprint_thing(bad_keys))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convert_axes(self):
""" Try to convert axes. """ |
for axis in self.obj._AXIS_NUMBERS.keys():
new_axis, result = self._try_convert_data(
axis, self.obj._get_axis(axis), use_dtypes=False,
convert_dates=True)
if result:
setattr(self.obj, axis, new_axis) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_converter(self, f, filt=None):
""" Take a conversion function and possibly recreate the frame. """ |
if filt is None:
filt = lambda col, c: True
needs_new_obj = False
new_obj = dict()
for i, (col, c) in enumerate(self.obj.iteritems()):
if filt(col, c):
new_data, result = f(col, c)
if result:
c = new_data
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_array(values, formatter, float_format=None, na_rep='NaN', digits=None, space=None, justify='right', decimal='.', leading_space=None):
""" Format an ar... |
if is_datetime64_dtype(values.dtype):
fmt_klass = Datetime64Formatter
elif is_datetime64tz_dtype(values):
fmt_klass = Datetime64TZFormatter
elif is_timedelta64_dtype(values.dtype):
fmt_klass = Timedelta64Formatter
elif is_extension_array_dtype(values.dtype):
fmt_klass =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_percentiles(percentiles):
""" Outputs rounded and formatted percentiles. Parameters percentiles : list-like, containing floats from interval [0,1] Ret... |
percentiles = np.asarray(percentiles)
# It checks for np.NaN as well
with np.errstate(invalid='ignore'):
if not is_numeric_dtype(percentiles) or not np.all(percentiles >= 0) \
or not np.all(percentiles <= 1):
raise ValueError("percentiles should all be in the interval ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_format_timedelta64(values, nat_rep='NaT', box=False):
""" Return a formatter function for a range of timedeltas. These will all have the same format arg... |
values_int = values.astype(np.int64)
consider_values = values_int != iNaT
one_day_nanos = (86400 * 1e9)
even_days = np.logical_and(consider_values,
values_int % one_day_nanos != 0).sum() == 0
all_sub_day = np.logical_and(
consider_values, np.abs(values_int)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _trim_zeros_complex(str_complexes, na_rep='NaN'):
""" Separates the real and imaginary parts from the complex number, and executes the _trim_zeros_float meth... |
def separate_and_trim(str_complex, na_rep):
num_arr = str_complex.split('+')
return (_trim_zeros_float([num_arr[0]], na_rep) +
['+'] +
_trim_zeros_float([num_arr[1][:-1]], na_rep) +
['j'])
return [''.join(separate_and_trim(x, na_rep)) for x in st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _trim_zeros_float(str_floats, na_rep='NaN'):
""" Trims zeros, leaving just one before the decimal points if need be. """ |
trimmed = str_floats
def _is_number(x):
return (x != na_rep and not x.endswith('inf'))
def _cond(values):
finite = [x for x in values if _is_number(x)]
return (len(finite) > 0 and all(x.endswith('0') for x in finite) and
not (any(('e' in x) or ('E' in x) for x in f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_eng_float_format(accuracy=3, use_eng_prefix=False):
""" Alter default behavior on how float is formatted in DataFrame. Format float in engineering format... |
set_option("display.float_format", EngFormatter(accuracy, use_eng_prefix))
set_option("display.column_space", max(12, accuracy + 9)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_level_lengths(levels, sentinel=''):
"""For each index in each level the function returns lengths of indexes. Parameters levels : list of lists List of va... |
if len(levels) == 0:
return []
control = [True] * len(levels[0])
result = []
for level in levels:
last_index = 0
lengths = {}
for i, key in enumerate(level):
if control[i] and key == sentinel:
pass
else:
control[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buffer_put_lines(buf, lines):
""" Appends lines to a buffer. Parameters buf The buffer to write to lines The lines to append. """ |
if any(isinstance(x, str) for x in lines):
lines = [str(x) for x in lines]
buf.write('\n'.join(lines)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def len(self, text):
""" Calculate display width considering unicode East Asian Width """ |
if not isinstance(text, str):
return len(text)
return sum(self._EAW_MAP.get(east_asian_width(c), self.ambiguous_width)
for c in text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _value_formatter(self, float_format=None, threshold=None):
"""Returns a function to be applied on each value to format it """ |
# the float_format parameter supersedes self.float_format
if float_format is None:
float_format = self.float_format
# we are going to compose different functions, to first convert to
# a string, then replace the decimal symbol, and finally chop according
# to the t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_result_as_array(self):
""" Returns the float values converted into strings using the parameters given at initialisation, as a numpy array """ |
if self.formatter is not None:
return np.array([self.formatter(x) for x in self.values])
if self.fixed_width:
threshold = get_option("display.chop_threshold")
else:
threshold = None
# if we have a fixed_width, we'll need to try different float_form... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_strings(self):
""" we by definition have a TZ """ |
values = self.values.astype(object)
is_dates_only = _is_dates_only(values)
formatter = (self.formatter or
_get_format_datetime64(is_dates_only,
date_format=self.date_format))
fmt_values = [formatter(x) for x in values]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_interval_closed_bounds(interval):
""" Given an Interval or IntervalIndex, return the corresponding interval with closed bounds. """ |
left, right = interval.left, interval.right
if interval.open_left:
left = _get_next_label(left)
if interval.open_right:
right = _get_prev_label(right)
return left, right |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interval_range(start=None, end=None, periods=None, freq=None, name=None, closed='right'):
""" Return a fixed frequency IntervalIndex Parameters start : numer... |
start = com.maybe_box_datetimelike(start)
end = com.maybe_box_datetimelike(end)
endpoint = start if start is not None else end
if freq is None and com._any_none(periods, start, end):
freq = 1 if is_number(endpoint) else 'D'
if com.count_not_none(start, end, periods, freq) != 3:
ra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
""" Create the writer & save """ |
# GH21227 internal compression is not used when file-like passed.
if self.compression and hasattr(self.path_or_buf, 'write'):
msg = ("compression has no effect when passing file-like "
"object as input.")
warnings.warn(msg, RuntimeWarning, stacklevel=2)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delegate_names(delegate, accessors, typ, overwrite=False):
""" Add delegated names to a class using a class decorator. This provides an alternative usage to ... |
def add_delegate_accessors(cls):
cls._add_delegate_accessors(delegate, accessors, typ,
overwrite=overwrite)
return cls
return add_delegate_accessors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_delegate_accessors(cls, delegate, accessors, typ, overwrite=False):
""" Add accessors to cls from the delegate class. Parameters cls : the class to add ... |
def _create_delegator_property(name):
def _getter(self):
return self._delegate_property_get(name)
def _setter(self, new_values):
return self._delegate_property_set(name, new_values)
_getter.__name__ = name
_setter.__name__ = na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _can_use_numexpr(op, op_str, a, b, dtype_check):
""" return a boolean if we WILL be using numexpr """ |
if op_str is not None:
# required min elements (otherwise we are adding overhead)
if np.prod(a.shape) > _MIN_ELEMENTS:
# check for dtype compatibility
dtypes = set()
for o in [a, b]:
if hasattr(o, 'get_dtype_counts'):
s = o.g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(op, op_str, a, b, use_numexpr=True, **eval_kwargs):
""" evaluate and return the expression of the op on a and b Parameters op : the actual operand o... |
use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b)
if use_numexpr:
return _evaluate(op, op_str, a, b, **eval_kwargs)
return _evaluate_standard(op, op_str, a, b) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def where(cond, a, b, use_numexpr=True):
""" evaluate the where condition cond on a and b Parameters cond : a boolean array a : return if cond is True b : return... |
if use_numexpr:
return _where(cond, a, b)
return _where_standard(cond, a, b) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_feather(df, path):
""" Write a DataFrame to the feather-format Parameters df : DataFrame path : string file path, or file-like object """ |
path = _stringify_path(path)
if not isinstance(df, DataFrame):
raise ValueError("feather only support IO with DataFrames")
feather = _try_import()[0]
valid_types = {'string', 'unicode'}
# validate index
# --------------
# validate that we have only a default index
# raise on ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_feather(path, columns=None, use_threads=True):
""" Load a feather-format object from the file path .. versionadded 0.20.0 Parameters path : string file ... |
feather, pyarrow = _try_import()
path = _stringify_path(path)
if LooseVersion(pyarrow.__version__) < LooseVersion('0.11.0'):
int_use_threads = int(use_threads)
if int_use_threads < 1:
int_use_threads = 1
return feather.read_feather(path, columns=columns,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_regular_range(start, end, periods, freq):
""" Generate a range of dates with the spans between dates described by the given `freq` DateOffset. Param... |
if isinstance(freq, Tick):
stride = freq.nanos
if periods is None:
b = Timestamp(start).value
# cannot just use e = Timestamp(end) + 1 because arange breaks when
# stride is too large, see GH10887
e = (b + (Timestamp(end).value - b) // stride * stride... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_range_overflow_safe(endpoint, periods, stride, side='start'):
""" Calculate the second endpoint for passing to np.arange, checking to avoid an inte... |
# GH#14187 raise instead of incorrectly wrapping around
assert side in ['start', 'end']
i64max = np.uint64(np.iinfo(np.int64).max)
msg = ('Cannot generate range with {side}={endpoint} and '
'periods={periods}'
.format(side=side, endpoint=endpoint, periods=periods))
with np.e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_locale(new_locale, lc_var=locale.LC_ALL):
""" Context manager for temporarily setting a locale. Parameters new_locale : str or tuple A string of the form... |
current_locale = locale.getlocale()
try:
locale.setlocale(lc_var, new_locale)
normalized_locale = locale.getlocale()
if all(x is not None for x in normalized_locale):
yield '.'.join(normalized_locale)
else:
yield new_locale
finally:
locale.se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_set_locale(lc, lc_var=locale.LC_ALL):
""" Check to see if we can set a locale, and subsequently get the locale, without raising an Exception. Parameters ... |
try:
with set_locale(lc, lc_var=lc_var):
pass
except (ValueError, locale.Error):
# horrible name for a Exception subclass
return False
else:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _valid_locales(locales, normalize):
""" Return a list of normalized locales that do not throw an ``Exception`` when set. Parameters locales : str A string wh... |
if normalize:
normalizer = lambda x: locale.normalize(x.strip())
else:
normalizer = lambda x: x.strip()
return list(filter(can_set_locale, map(normalizer, locales))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_locales(prefix=None, normalize=True, locale_getter=_default_locale_getter):
""" Get all the locales that are available on the system. Parameters prefix :... |
try:
raw_locales = locale_getter()
except Exception:
return None
try:
# raw_locales is "\n" separated list of locales
# it may contain non-decodable parts, so split
# extract what we can and then rejoin.
raw_locales = raw_locales.split(b'\n')
out_loc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_float(arr):
""" Ensure that an array object has a float dtype if possible. Parameters arr : array-like The array whose data type we want to enforce as... |
if issubclass(arr.dtype.type, (np.integer, np.bool_)):
arr = arr.astype(float)
return arr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_int64_or_float64(arr, copy=False):
""" Ensure that an dtype array of some integer dtype has an int64 dtype if possible If it's not possible, potential... |
try:
return arr.astype('int64', copy=copy, casting='safe')
except TypeError:
return arr.astype('float64', copy=copy) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def classes_and_not_datetimelike(*klasses):
""" evaluate if the tipo is a subclass of the klasses and not a datetimelike """ |
return lambda tipo: (issubclass(tipo, klasses) and
not issubclass(tipo, (np.datetime64, np.timedelta64))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_sparse(arr):
""" Check whether an array-like is a 1-D pandas sparse array. Check that the one-dimensional array-like is a pandas sparse array. Returns Tru... |
from pandas.core.arrays.sparse import SparseDtype
dtype = getattr(arr, 'dtype', arr)
return isinstance(dtype, SparseDtype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_scipy_sparse(arr):
""" Check whether an array-like is a scipy.sparse.spmatrix instance. Parameters arr : array-like The array-like to check. Returns -----... |
global _is_scipy_sparse
if _is_scipy_sparse is None:
try:
from scipy.sparse import issparse as _is_scipy_sparse
except ImportError:
_is_scipy_sparse = lambda _: False
return _is_scipy_sparse(arr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_offsetlike(arr_or_obj):
""" Check if obj or all elements of list-like is DateOffset Parameters arr_or_obj : object Returns ------- boolean Whether the obj... |
if isinstance(arr_or_obj, ABCDateOffset):
return True
elif (is_list_like(arr_or_obj) and len(arr_or_obj) and
is_object_dtype(arr_or_obj)):
return all(isinstance(x, ABCDateOffset) for x in arr_or_obj)
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_period(arr):
""" Check whether an array-like is a periodical index. .. deprecated:: 0.24.0 Parameters arr : array-like The array-like to check. Returns --... |
warnings.warn("'is_period' is deprecated and will be removed in a future "
"version. Use 'is_period_dtype' or is_period_arraylike' "
"instead.", FutureWarning, stacklevel=2)
return isinstance(arr, ABCPeriodIndex) or is_period_arraylike(arr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_string_dtype(arr_or_dtype):
""" Check whether the provided array or dtype is of the string dtype. Parameters arr_or_dtype : array-like The array or dtype ... |
# TODO: gh-15585: consider making the checks stricter.
def condition(dtype):
return dtype.kind in ('O', 'S', 'U') and not is_period_dtype(dtype)
return _is_dtype(arr_or_dtype, condition) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_period_arraylike(arr):
""" Check whether an array-like is a periodical array-like or PeriodIndex. Parameters arr : array-like The array-like to check. Ret... |
if isinstance(arr, (ABCPeriodIndex, ABCPeriodArray)):
return True
elif isinstance(arr, (np.ndarray, ABCSeries)):
return is_period_dtype(arr.dtype)
return getattr(arr, 'inferred_type', None) == 'period' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_datetime_arraylike(arr):
""" Check whether an array-like is a datetime array-like or DatetimeIndex. Parameters arr : array-like The array-like to check. R... |
if isinstance(arr, ABCDatetimeIndex):
return True
elif isinstance(arr, (np.ndarray, ABCSeries)):
return (is_object_dtype(arr.dtype)
and lib.infer_dtype(arr, skipna=False) == 'datetime')
return getattr(arr, 'inferred_type', None) == 'datetime' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_datetimelike(arr):
""" Check whether an array-like is a datetime-like array-like. Acceptable datetime-like objects are (but not limited to) datetime indic... |
return (is_datetime64_dtype(arr) or is_datetime64tz_dtype(arr) or
is_timedelta64_dtype(arr) or
isinstance(arr, ABCPeriodIndex)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_dtype_equal(source, target):
""" Check if two dtypes are equal. Parameters source : The first dtype to compare target : The second dtype to compare Return... |
try:
source = _get_dtype(source)
target = _get_dtype(target)
return source == target
except (TypeError, AttributeError):
# invalid comparison
# object == category will hit this
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_dtype_union_equal(source, target):
""" Check whether two arrays have compatible dtypes to do a union. numpy types are checked with ``is_dtype_equal``. Ext... |
source = _get_dtype(source)
target = _get_dtype(target)
if is_categorical_dtype(source) and is_categorical_dtype(target):
# ordered False for both
return source.ordered is target.ordered
return is_dtype_equal(source, target) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_numeric_v_string_like(a, b):
""" Check if we are comparing a string-like object to a numeric ndarray. NumPy doesn't like to compare such objects, especial... |
is_a_array = isinstance(a, np.ndarray)
is_b_array = isinstance(b, np.ndarray)
is_a_numeric_array = is_a_array and is_numeric_dtype(a)
is_b_numeric_array = is_b_array and is_numeric_dtype(b)
is_a_string_array = is_a_array and is_string_like_dtype(a)
is_b_string_array = is_b_array and is_string... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_datetimelike_v_numeric(a, b):
""" Check if we are comparing a datetime-like object to a numeric object. By "numeric," we mean an object that is either of ... |
if not hasattr(a, 'dtype'):
a = np.asarray(a)
if not hasattr(b, 'dtype'):
b = np.asarray(b)
def is_numeric(x):
"""
Check if an object has a numeric dtype (i.e. integer or float).
"""
return is_integer_dtype(x) or is_float_dtype(x)
is_datetimelike = nee... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_datetimelike_v_object(a, b):
""" Check if we are comparing a datetime-like object to an object instance. Parameters a : array-like, scalar The first objec... |
if not hasattr(a, 'dtype'):
a = np.asarray(a)
if not hasattr(b, 'dtype'):
b = np.asarray(b)
is_datetimelike = needs_i8_conversion
return ((is_datetimelike(a) and is_object_dtype(b)) or
(is_datetimelike(b) and is_object_dtype(a))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def needs_i8_conversion(arr_or_dtype):
""" Check whether the array or dtype should be converted to int64. An array-like or dtype "needs" such a conversion if the... |
if arr_or_dtype is None:
return False
return (is_datetime_or_timedelta_dtype(arr_or_dtype) or
is_datetime64tz_dtype(arr_or_dtype) or
is_period_dtype(arr_or_dtype)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_bool_dtype(arr_or_dtype):
""" Check whether the provided array or dtype is of a boolean dtype. Parameters arr_or_dtype : array-like The array or dtype to ... |
if arr_or_dtype is None:
return False
try:
dtype = _get_dtype(arr_or_dtype)
except TypeError:
return False
if isinstance(arr_or_dtype, CategoricalDtype):
arr_or_dtype = arr_or_dtype.categories
# now we use the special definition for Index
if isinstance(arr_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_extension_type(arr):
""" Check whether an array-like is of a pandas extension class instance. Extension classes include categoricals, pandas sparse object... |
if is_categorical(arr):
return True
elif is_sparse(arr):
return True
elif is_datetime64tz_dtype(arr):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_extension_array_dtype(arr_or_dtype):
""" Check if an object is a pandas extension array type. See the :ref:`Use Guide <extending.extension-types>` for mor... |
dtype = getattr(arr_or_dtype, 'dtype', arr_or_dtype)
return (isinstance(dtype, ExtensionDtype) or
registry.find(dtype) is not None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_dtype(arr_or_dtype):
""" Get the dtype instance associated with an array or dtype object. Parameters arr_or_dtype : array-like The array-like or dtype o... |
if arr_or_dtype is None:
raise TypeError("Cannot deduce dtype from null object")
# fastpath
elif isinstance(arr_or_dtype, np.dtype):
return arr_or_dtype
elif isinstance(arr_or_dtype, type):
return np.dtype(arr_or_dtype)
# if we have an array-like
elif hasattr(arr_or_d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infer_dtype_from_object(dtype):
""" Get a numpy dtype.type-style object for a dtype object. This methods also includes handling of the datetime64[ns] and dat... |
if isinstance(dtype, type) and issubclass(dtype, np.generic):
# Type object from a dtype
return dtype
elif isinstance(dtype, (np.dtype, PandasExtensionDtype, ExtensionDtype)):
# dtype object
try:
_validate_date_like_dtype(dtype)
except TypeError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_date_like_dtype(dtype):
""" Check whether the dtype is a date-like dtype. Raises an error if invalid. Parameters dtype : dtype, type The dtype to c... |
try:
typ = np.datetime_data(dtype)[0]
except ValueError as e:
raise TypeError('{error}'.format(error=e))
if typ != 'generic' and typ != 'ns':
msg = '{name!r} is too specific of a frequency, try passing {type!r}'
raise ValueError(msg.format(name=dtype.name, type=dtype.type._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pandas_dtype(dtype):
""" Convert input into a pandas only dtype object or a numpy dtype object. Parameters dtype : object to be converted Returns ------- np.... |
# short-circuit
if isinstance(dtype, np.ndarray):
return dtype.dtype
elif isinstance(dtype, (np.dtype, PandasExtensionDtype, ExtensionDtype)):
return dtype
# registered extension types
result = registry.find(dtype)
if result is not None:
return result
# try a numpy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _groupby_and_merge(by, on, left, right, _merge_pieces, check_duplicates=True):
""" groupby & merge; we are always performing a left-by type operation Paramet... |
pieces = []
if not isinstance(by, (list, tuple)):
by = [by]
lby = left.groupby(by, sort=False)
# if we can groupby the rhs
# then we can get vastly better perf
try:
# we will check & remove duplicates if indicated
if check_duplicates:
if on is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_asof(left, right, on=None, left_on=None, right_on=None, left_index=False, right_index=False, by=None, left_by=None, right_by=None, suffixes=('_x', '_y')... |
op = _AsOfMerge(left, right,
on=on, left_on=left_on, right_on=right_on,
left_index=left_index, right_index=right_index,
by=by, left_by=left_by, right_by=right_by,
suffixes=suffixes,
how='asof', tolerance=tolerance,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _maybe_restore_index_levels(self, result):
""" Restore index levels specified as `on` parameters Here we check for cases where `self.left_on` and `self.right... |
names_to_restore = []
for name, left_key, right_key in zip(self.join_names,
self.left_on,
self.right_on):
if (self.orig_left._is_level_reference(left_key) and
self.orig_right._is_le... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_join_index(self, index, other_index, indexer, other_indexer, how='left'):
""" Create a join index by rearranging one index to match another Parameter... |
join_index = index.take(indexer)
if (self.how in (how, 'outer') and
not isinstance(other_index, MultiIndex)):
# if final index requires values in other_index but not target
# index, indexer may hold missing (-1) values, causing Index.take
# to take th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_dtype(cls, dtype):
"""Check if we match 'dtype'. Parameters dtype : object The object to check. Returns ------- is_dtype : bool Notes ----- The default im... |
dtype = getattr(dtype, 'dtype', dtype)
if isinstance(dtype, (ABCSeries, ABCIndexClass,
ABCDataFrame, np.dtype)):
# https://github.com/pandas-dev/pandas/issues/22960
# avoid passing data to `construct_from_string`. This could
# cause a F... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True):
""" Test if pattern or regex is contained within a string of a Series or Index. Return boo... |
if regex:
if not case:
flags |= re.IGNORECASE
regex = re.compile(pat, flags=flags)
if regex.groups > 0:
warnings.warn("This pattern has match groups. To actually get the"
" groups, use str.extract.", UserWarning,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_startswith(arr, pat, na=np.nan):
""" Test if the start of each string element matches a pattern. Equivalent to :meth:`str.startswith`. Parameters pat : s... |
f = lambda x: x.startswith(pat)
return _na_map(f, arr, na, dtype=bool) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_endswith(arr, pat, na=np.nan):
""" Test if the end of each string element matches a pattern. Equivalent to :meth:`str.endswith`. Parameters pat : str Cha... |
f = lambda x: x.endswith(pat)
return _na_map(f, arr, na, dtype=bool) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_repeat(arr, repeats):
""" Duplicate each string in the Series or Index. Parameters repeats : int or sequence of int Same value for all (int) or different... |
if is_scalar(repeats):
def scalar_rep(x):
try:
return bytes.__mul__(x, repeats)
except TypeError:
return str.__mul__(x, repeats)
return _na_map(scalar_rep, arr)
else:
def rep(x, r):
try:
return bytes._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_match(arr, pat, case=True, flags=0, na=np.nan):
""" Determine if each string matches a regular expression. Parameters pat : str Character sequence or reg... |
if not case:
flags |= re.IGNORECASE
regex = re.compile(pat, flags=flags)
dtype = bool
f = lambda x: bool(regex.match(x))
return _na_map(f, arr, na, dtype=dtype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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):
if not isinstance(x, str):
return empty_row
m = regex.search(x)
if m:
return [np.nan if item is None else item for item in m.gr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_extract(arr, pat, flags=0, expand=True):
r""" Extract capture groups in the regex `pat` as columns in a DataFrame. For each subject string in the Series,... |
if not isinstance(expand, bool):
raise ValueError("expand must be True or False")
if expand:
return _str_extract_frame(arr._orig, pat, flags=flags)
else:
result, name = _str_extract_noexpand(arr._parent, pat, flags=flags)
return arr._wrap_result(result, name=name, expand=exp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.