INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Check if the docstrings method can return something. | 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... |
Convert numpy types to Python types for the Excel writers. | 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
-------
Tuple with the first element being the converted value and the second
... |
checks that path s extension against the Writer s supported extensions. If it isn t supported raises UnsupportedFiletypeError. | 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):
... |
Parse specified sheet ( s ) into a DataFrame | def parse(self,
sheet_name=0,
header=0,
names=None,
index_col=None,
usecols=None,
squeeze=False,
converters=None,
true_values=None,
false_values=None,
skiprows=None,
... |
Validate that the where statement is of the right type. | 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 : String term expression, Expr, or list-like of Exprs.
Returns
-------
where : The original where clause if the c... |
loose checking if s is a pytables - acceptable expression | 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) |
inplace conform rhs | 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 |
create and return the op string for this TermValue | 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) |
convert the expression that is in the term to something that is accepted by pytables | 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.encodi... |
invert the filter | 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 |
create and return the numexpr condition and filter | 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 condi... |
quote the string if not encoded else encode and return | 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 == 'flo... |
if we have bytes decode them to unicode | def _ensure_decoded(s):
""" if we have bytes, decode them to unicode """
if isinstance(s, (np.bytes_, bytes)):
s = s.decode(pd.get_option('display.encoding'))
return s |
wrapper around numpy. result_type which overcomes the NPY_MAXARGS ( 32 ) argument limit | def _result_type_many(*arrays_and_dtypes):
""" wrapper around numpy.result_type which overcomes the NPY_MAXARGS (32)
argument limit """
try:
return np.result_type(*arrays_and_dtypes)
except ValueError:
# we have > NPY_MAXARGS terms in our expression
return reduce(np.result_type, ... |
If Series. argmin is called via the numpy library the third parameter in its signature is out which takes either an ndarray or None so check if the skipna parameter is either an instance of ndarray or is None since skipna itself should be a boolean | 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', which
takes either an ndarray or 'None', so check if the
'skipna' parameter is either an instance of ndarray or
is None, since 'skipna' ... |
If Series. argmax is called via the numpy library the third parameter in its signature is out which takes either an ndarray or None so check if the skipna parameter is either an instance of ndarray or is None since skipna itself should be a boolean | 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', which
takes either an ndarray or 'None', so check if the
'skipna' parameter is either an instance of ndarray or
is None, since 'skipna' ... |
If Categorical. argsort is called via the numpy library the first parameter in its signature is axis which takes either an integer or None so check if the ascending parameter has either integer type or is None since ascending itself should be a boolean | def validate_argsort_with_ascending(ascending, args, kwargs):
"""
If 'Categorical.argsort' is called via the 'numpy' library, the
first parameter in its signature is 'axis', which takes either
an integer or 'None', so check if the 'ascending' parameter has
either integer type or is None, since 'asce... |
If NDFrame. clip is called via the numpy library the third parameter in its signature is out which can takes an ndarray so check if the axis parameter is an instance of ndarray since axis itself should either be an integer or None | 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 takes an ndarray,
so check if the 'axis' parameter is an instance of ndarray, since
'axis' itself should either be an integer or None
"... |
If this function is called via the numpy library the third parameter in its signature is dtype which takes either a numpy dtype or None so check if the skipna parameter is a boolean or not | 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 'dtype', which takes either a
'numpy' dtype or 'None', so check if the 'skipna' parameter is
a boolean or not
"""
if not is_bool(skip... |
If this function is called via the numpy library the third parameter in its signature is axis which takes either an ndarray or None so check if the convert parameter is either an instance of ndarray or is None | 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', which takes either an
ndarray or 'None', so check if the 'convert' parameter is either
an instance of ndarray or is None
"""
if isin... |
args and kwargs should be empty except for allowed kwargs because all of their necessary parameters are explicitly listed in the function signature | def validate_groupby_func(name, args, kwargs, allowed=None):
"""
'args' and 'kwargs' should be empty, except for allowed
kwargs because all of
their necessary parameters are explicitly listed in
the function signature
"""
if allowed is None:
allowed = []
kwargs = set(kwargs) - s... |
args and kwargs should be empty because all of their necessary parameters are explicitly listed in the function signature | def validate_resampler_func(method, args, kwargs):
"""
'args' and 'kwargs' should be empty because all of
their necessary parameters are explicitly listed in
the function signature
"""
if len(args) + len(kwargs) > 0:
if method in RESAMPLER_NUMPY_OPS:
raise UnsupportedFunction... |
Ensure that the axis argument passed to min max argmin or argmax is zero or None as otherwise it will be incorrectly ignored. | 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 ignored.
Parameters
----------
axis : int or None
Raises
------
ValueError
"""
ndim = 1 # hard-coded for Index
i... |
msgpack ( serialize ) object to input file path | def to_msgpack(path_or_buf, *args, **kwargs):
"""
msgpack (serialize) object to input file path
THIS IS AN EXPERIMENTAL LIBRARY and the storage format
may not be stable until a future release.
Parameters
----------
path_or_buf : string File path, buffer-like, or None
if N... |
Load msgpack pandas object from the specified file path | 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 LIBRARY and the storage format
may not be stable until a future release.
Parameters
----------
path_or_buf : string File path, ... |
return my dtype mapping whether number or name | 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) |
Convert strings to complex number instance with specified numpy type. | 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)) |
convert the numpy values to a list | 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()... |
Data encoder | def encode(obj):
"""
Data encoder
"""
tobj = type(obj)
if isinstance(obj, Index):
if isinstance(obj, RangeIndex):
return {'typ': 'range_index',
'klass': obj.__class__.__name__,
'name': getattr(obj, 'name', None),
'start'... |
Decoder for deserializing numpy data types. | def decode(obj):
"""
Decoder for deserializing numpy data types.
"""
typ = obj.get('typ')
if typ is None:
return obj
elif typ == 'timestamp':
freq = obj['freq'] if 'freq' in obj else obj['offset']
return Timestamp(obj['value'], tz=obj['tz'], freq=freq)
elif typ == 'n... |
Pack an object and return the packed bytes. | 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 packed bytes.
"""
return Packer(default=default, encoding=encoding,
unicode_errors=unicode_errors,
... |
Unpack a packed object return an iterator Note: packed lists will be returned as tuples | def unpack(packed, object_hook=decode,
list_hook=None, use_list=False, encoding='utf-8',
unicode_errors='strict', object_pairs_hook=None,
max_buffer_size=0, ext_hook=ExtType):
"""
Unpack a packed object, return an iterator
Note: packed lists will be returned as tuples
""... |
Convert a JSON string to pandas object. | 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=False, date_unit=None, encoding=None,
lines=False, chunksize=None, compression='infer'):
"""
Convert a JSON s... |
Try to format axes if they are datelike. | 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(o... |
At this point the data either has a read attribute ( e. g. a file object or a StringIO ) or is a string that is a JSON document. | def _preprocess_data(self, data):
"""
At this point, the data either has a `read` attribute (e.g. a file
object or a StringIO) or is a string that is a JSON document.
If self.chunksize, we prepare the data for the `__next__` method.
Otherwise, we read it into memory for the `rea... |
The function read_json accepts three input types: 1. filepath ( string - like ) 2. file - like object ( e. g. open file object StringIO ) 3. JSON string | def _get_data_from_filepath(self, filepath_or_buffer):
"""
The function read_json accepts three input types:
1. filepath (string-like)
2. file-like object (e.g. open file object, StringIO)
3. JSON string
This method turns (1) into (2) to simplify the rest of ... |
Combines a list of JSON objects into one JSON object. | 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) + ']' |
Read the whole JSON input into a pandas object. | 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.spli... |
Parses a json document into a pandas object. | 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.c... |
Checks that dict has only the appropriate keys for orient = split. | 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 une... |
Try to convert axes. | 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:
... |
Take a conversion function and possibly recreate the frame. | 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()):
... |
Format an array for printing. | def format_array(values, formatter, float_format=None, na_rep='NaN',
digits=None, space=None, justify='right', decimal='.',
leading_space=None):
"""
Format an array for printing.
Parameters
----------
values
formatter
float_format
na_rep
digits
... |
Outputs rounded and formatted percentiles. | def format_percentiles(percentiles):
"""
Outputs rounded and formatted percentiles.
Parameters
----------
percentiles : list-like, containing floats from interval [0,1]
Returns
-------
formatted : list of strings
Notes
-----
Rounding precision is chosen so that: (1) if any... |
Return a formatter function for a range of timedeltas. These will all have the same format argument | 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 argument
If box, then show the return in quotes
"""
values_int = values.astype(np.int64)
consider_values = values_int != iNaT
... |
Separates the real and imaginary parts from the complex number and executes the _trim_zeros_float method on each of those. | 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 method on each of those.
"""
def separate_and_trim(str_complex, na_rep):
num_arr = str_complex.split('+')
return (_trim_zeros_f... |
Trims zeros leaving just one before the decimal points if need be. | 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)]
... |
Alter default behavior on how float is formatted in DataFrame. Format float in engineering format. By accuracy we mean the number of decimal digits after the floating point. | 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. By accuracy, we mean the number of
decimal digits after the floating point.
See also EngFormatter.
"""
set_option("display.floa... |
For each index in each level the function returns lengths of indexes. | 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 values on for level.
sentinel : string, optional
Value which states that no new index starts on there.
Retur... |
Appends lines to a buffer. | 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)) |
Calculate display width considering unicode East Asian Width | 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) |
Render a DataFrame to a list of columns ( as lists of strings ). | def _to_str_columns(self):
"""
Render a DataFrame to a list of columns (as lists of strings).
"""
frame = self.tr_frame
# may include levels names also
str_index = self._get_formatted_index(frame)
if not is_list_like(self.header) and not self.header:
... |
Render a DataFrame to a console - friendly tabular output. | def to_string(self):
"""
Render a DataFrame to a console-friendly tabular output.
"""
from pandas import Series
frame = self.frame
if len(frame.columns) == 0 or len(frame.index) == 0:
info_line = ('Empty {name}\nColumns: {col}\nIndex: {idx}'
... |
Render a DataFrame to a LaTeX tabular/ longtable environment output. | def to_latex(self, column_format=None, longtable=False, encoding=None,
multicolumn=False, multicolumn_format=None, multirow=False):
"""
Render a DataFrame to a LaTeX tabular/longtable environment output.
"""
from pandas.io.formats.latex import LatexFormatter
lat... |
Render a DataFrame to a html table. | def to_html(self, classes=None, notebook=False, border=None):
"""
Render a DataFrame to a html table.
Parameters
----------
classes : str or list-like
classes to include in the `class` attribute of the opening
``<table>`` tag, in addition to the default "... |
Returns a function to be applied on each value to format it | 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 co... |
Returns the float values converted into strings using the parameters given at initialisation as a numpy array | 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... |
we by definition have DO NOT have a TZ | def _format_strings(self):
""" we by definition have DO NOT have a TZ """
values = self.values
if not isinstance(values, DatetimeIndex):
values = DatetimeIndex(values)
if self.formatter is not None and callable(self.formatter):
return [self.formatter(x) for x i... |
we by definition have a TZ | 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... |
Given an Interval or IntervalIndex return the corresponding interval with closed bounds. | 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_pr... |
helper for interval_range to check if start/ end are valid types | def _is_valid_endpoint(endpoint):
"""helper for interval_range to check if start/end are valid types"""
return any([is_number(endpoint),
isinstance(endpoint, Timestamp),
isinstance(endpoint, Timedelta),
endpoint is None]) |
helper for interval_range to check type compat of start/ end/ freq | def _is_type_compatible(a, b):
"""helper for interval_range to check type compat of start/end/freq"""
is_ts_compat = lambda x: isinstance(x, (Timestamp, DateOffset))
is_td_compat = lambda x: isinstance(x, (Timedelta, DateOffset))
return ((is_number(a) and is_number(b)) or
(is_ts_compat(a) an... |
Return a fixed frequency IntervalIndex | def interval_range(start=None, end=None, periods=None, freq=None,
name=None, closed='right'):
"""
Return a fixed frequency IntervalIndex
Parameters
----------
start : numeric or datetime-like, default None
Left bound for generating intervals
end : numeric or datetime-... |
Create the writer & save | 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 inpu... |
Add delegated names to a class using a class decorator. This provides an alternative usage to directly calling _add_delegate_accessors below a class definition. | def delegate_names(delegate, accessors, typ, overwrite=False):
"""
Add delegated names to a class using a class decorator. This provides
an alternative usage to directly calling `_add_delegate_accessors`
below a class definition.
Parameters
----------
delegate : object
the class to... |
Add additional __dir__ for this object. | def _dir_additions(self):
"""
Add additional __dir__ for this object.
"""
rv = set()
for accessor in self._accessors:
try:
getattr(self, accessor)
rv.add(accessor)
except AttributeError:
pass
return r... |
Add accessors to cls from the delegate class. | def _add_delegate_accessors(cls, delegate, accessors, typ,
overwrite=False):
"""
Add accessors to cls from the delegate class.
Parameters
----------
cls : the class to add the methods/properties to
delegate : the class to get methods/prope... |
standard evaluation | def _evaluate_standard(op, op_str, a, b, **eval_kwargs):
""" standard evaluation """
if _TEST_MODE:
_store_test_result(False)
with np.errstate(all='ignore'):
return op(a, b) |
return a boolean if we WILL be using numexpr | 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(... |
evaluate and return the expression of the op on a and b | 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
op_str: the string version of the op
a : left operand
b : right operand... |
evaluate the where condition cond on a and b | 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 cond is False
use_numexpr : whether to try to use numexpr (default True)
"""... |
writer: string or ExcelWriter object File path or existing ExcelWriter sheet_name: string default Sheet1 Name of sheet which will contain DataFrame startrow: upper left cell row to dump data frame startcol: upper left cell column to dump data frame freeze_panes: tuple of integer ( length 2 ) default None Specifies the ... | def write(self, writer, sheet_name='Sheet1', startrow=0,
startcol=0, freeze_panes=None, engine=None):
"""
writer : string or ExcelWriter object
File path or existing ExcelWriter
sheet_name : string, default 'Sheet1'
Name of sheet which will contain DataFrame... |
Write a DataFrame to the feather - format | 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 DataFram... |
Load a feather - format object from the file path | 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 path, or file-like object
columns : sequence, default None
If not provided, all columns are read
.. v... |
Generate a range of dates with the spans between dates described by the given freq DateOffset. | def generate_regular_range(start, end, periods, freq):
"""
Generate a range of dates with the spans between dates described by
the given `freq` DateOffset.
Parameters
----------
start : Timestamp or None
first point of produced date range
end : Timestamp or None
last point o... |
Calculate the second endpoint for passing to np. arange checking to avoid an integer overflow. Catch OverflowError and re - raise as OutOfBoundsDatetime. | def _generate_range_overflow_safe(endpoint, periods, stride, side='start'):
"""
Calculate the second endpoint for passing to np.arange, checking
to avoid an integer overflow. Catch OverflowError and re-raise
as OutOfBoundsDatetime.
Parameters
----------
endpoint : int
nanosecond ti... |
A special case for _generate_range_overflow_safe where periods * stride can be calculated without overflowing int64 bounds. | def _generate_range_overflow_safe_signed(endpoint, periods, stride, side):
"""
A special case for _generate_range_overflow_safe where `periods * stride`
can be calculated without overflowing int64 bounds.
"""
assert side in ['start', 'end']
if side == 'end':
stride *= -1
with np.err... |
Context manager for temporarily setting a locale. | 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 <language_country>.<encoding>. For example to set
the current locale to US English with a UTF8 encoding, you w... |
Check to see if we can set a locale and subsequently get the locale without raising an Exception. | 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
----------
lc : str
The locale to attempt to set.
lc_var : int, default `locale.LC_ALL`
The category of the locale... |
Return a list of normalized locales that do not throw an Exception when set. | def _valid_locales(locales, normalize):
"""
Return a list of normalized locales that do not throw an ``Exception``
when set.
Parameters
----------
locales : str
A string where each locale is separated by a newline.
normalize : bool
Whether to call ``locale.normalize`` on eac... |
Get all the locales that are available on the system. | def get_locales(prefix=None, normalize=True,
locale_getter=_default_locale_getter):
"""
Get all the locales that are available on the system.
Parameters
----------
prefix : str
If not ``None`` then return only those locales with the prefix
provided. For example to ge... |
Ensure that an array object has a float dtype if possible. | 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 float.
Returns
-------
float_arr : The original array cast to the float dtype if
possible... |
Ensure that an array - like object is a Categorical ( if not already ). | def ensure_categorical(arr):
"""
Ensure that an array-like object is a Categorical (if not already).
Parameters
----------
arr : array-like
The array that we want to convert into a Categorical.
Returns
-------
cat_arr : The original array cast as a Categorical. If it already
... |
Ensure that an dtype array of some integer dtype has an int64 dtype if possible If it s not possible potentially because of overflow convert the array to float64 instead. | 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, potentially because of overflow,
convert the array to float64 instead.
Parameters
----------
arr : array-like
The array whose... |
evaluate if the tipo is a subclass of the klasses and not a datetimelike | 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))) |
Check whether an array - like is a 1 - D pandas sparse array. | 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 True if it is a pandas sparse array, not another type of
sparse array.
Parameters
----------
arr : array-like
Array-like... |
Check whether an array - like is a scipy. sparse. spmatrix instance. | 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
-------
boolean
Whether or not the array-like is a scipy.sparse.spmatrix instance.
Notes
-----... |
Check if obj or all elements of list - like is DateOffset | 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 object is a DateOffset or listlike of DatetOffsets
Examples
--------
>>> is_offsetlike(pd.DateOf... |
Check whether an array - like is a periodical index. | 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
-------
boolean
Whether or not the array-like is a periodical index.
Examples
--------... |
Check whether the provided array or dtype is of the string dtype. | 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 to check.
Returns
-------
boolean
Whether or not the array or dtype is of the string dtype.
E... |
Check whether an array - like is a periodical array - like or PeriodIndex. | 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.
Returns
-------
boolean
Whether or not the array-like is a periodical array-like or
PeriodInd... |
Check whether an array - like is a datetime array - like or DatetimeIndex. | 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.
Returns
-------
boolean
Whether or not the array-like is a datetime array-like or
DatetimeI... |
Check whether an array - like is a datetime - like array - like. | 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
indices, periodic indices, and timedelta indices.
Parameters
----------
arr : array-like
The array-like to check.
Returns... |
Check if two dtypes are equal. | 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
Returns
----------
boolean
Whether or not the two dtypes are equal.
Examples
--------
>>> is_dt... |
Check whether two arrays have compatible dtypes to do a union. numpy types are checked with is_dtype_equal. Extension types are checked separately. | 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``. Extension types are
checked separately.
Parameters
----------
source : The first dtype to compare
target : The second dtype to co... |
Check whether the provided array or dtype is of the datetime64 [ ns ] dtype. | def is_datetime64_ns_dtype(arr_or_dtype):
"""
Check whether the provided array or dtype is of the datetime64[ns] dtype.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of the datet... |
Check if we are comparing a string - like object to a numeric ndarray. | 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, especially numeric arrays
and scalar string-likes.
Parameters
----------
a : array-like, scalar
The first object to check.
b ... |
Check if we are comparing a datetime - like object to a numeric object. | 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 an int or float dtype.
Parameters
----------
a : array-like, scalar
The first object to check.
b : array-like, scalar
... |
Check if we are comparing a datetime - like object to an object instance. | 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 object to check.
b : array-like, scalar
The second object to check.
Returns
-------
boolean
... |
Check whether the array or dtype should be converted to int64. | 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 array-like
or dtype is of a datetime-like dtype
Parameters
----------
arr_or_dtype : array-like
The array or dtype to ch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.