Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _add_delta(self, delta): new_values = super()._add_delta(delta) return type(self)._from_sequence(new_values, tz=self.tz, freq='infer')
[ "\n Add a timedelta-like, Tick, or TimedeltaIndex-like object\n to self, yielding a new DatetimeArray\n\n Parameters\n ----------\n other : {timedelta, np.timedelta64, Tick,\n TimedeltaIndex, ndarray[timedelta64]}\n\n Returns\n -------\n result...
Please provide a description of the function:def tz_convert(self, tz): tz = timezones.maybe_get_tz(tz) if self.tz is None: # tz naive, use tz_localize raise TypeError('Cannot convert tz-naive timestamps, use ' 'tz_localize to localize') ...
[ "\n Convert tz-aware Datetime Array/Index from one time zone to another.\n\n Parameters\n ----------\n tz : str, pytz.timezone, dateutil.tz.tzfile or None\n Time zone for time. Corresponding timestamps would be converted\n to this time zone of the Datetime Array/Ind...
Please provide a description of the function:def tz_localize(self, tz, ambiguous='raise', nonexistent='raise', errors=None): if errors is not None: warnings.warn("The errors argument is deprecated and will be " "removed in a future release. Use ...
[ "\n Localize tz-naive Datetime Array/Index to tz-aware\n Datetime Array/Index.\n\n This method takes a time zone (tz) naive Datetime Array/Index object\n and makes this time zone aware. It does not move the time to another\n time zone.\n Time zone localization helps to swit...
Please provide a description of the function:def normalize(self): if self.tz is None or timezones.is_utc(self.tz): not_null = ~self.isna() DAY_NS = ccalendar.DAY_SECONDS * 1000000000 new_values = self.asi8.copy() adjustment = (new_values[not_null] % DAY_N...
[ "\n Convert times to midnight.\n\n The time component of the date-time is converted to midnight i.e.\n 00:00:00. This is useful in cases, when the time does not matter.\n Length is unaltered. The timezones are unaffected.\n\n This method is available on Series with datetime values...
Please provide a description of the function:def to_period(self, freq=None): from pandas.core.arrays import PeriodArray if self.tz is not None: warnings.warn("Converting to PeriodArray/Index representation " "will drop timezone information.", UserWarning) ...
[ "\n Cast to PeriodArray/Index at a particular frequency.\n\n Converts DatetimeArray/Index to PeriodArray/Index.\n\n Parameters\n ----------\n freq : str or Offset, optional\n One of pandas' :ref:`offset strings <timeseries.offset_aliases>`\n or an Offset obje...
Please provide a description of the function:def to_perioddelta(self, freq): # TODO: consider privatizing (discussion in GH#23113) from pandas.core.arrays.timedeltas import TimedeltaArray i8delta = self.asi8 - self.to_period(freq).to_timestamp().asi8 m8delta = i8delta.view('m8[n...
[ "\n Calculate TimedeltaArray of difference between index\n values and index converted to PeriodArray at specified\n freq. Used for vectorized offsets\n\n Parameters\n ----------\n freq : Period frequency\n\n Returns\n -------\n TimedeltaArray/Index\n ...
Please provide a description of the function:def month_name(self, locale=None): if self.tz is not None and not timezones.is_utc(self.tz): values = self._local_timestamps() else: values = self.asi8 result = fields.get_date_name_field(values, 'month_name', ...
[ "\n Return the month names of the DateTimeIndex with specified locale.\n\n .. versionadded:: 0.23.0\n\n Parameters\n ----------\n locale : str, optional\n Locale determining the language in which to return the month name.\n Default is English locale.\n\n ...
Please provide a description of the function:def time(self): # If the Timestamps have a timezone that is not UTC, # convert them into their i8 representation while # keeping their timezone and not using UTC if self.tz is not None and not timezones.is_utc(self.tz): ti...
[ "\n Returns numpy array of datetime.time. The time part of the Timestamps.\n " ]
Please provide a description of the function:def to_julian_date(self): # http://mysite.verizon.net/aesir_research/date/jdalg2.htm year = np.asarray(self.year) month = np.asarray(self.month) day = np.asarray(self.day) testarr = month < 3 year[testarr] -= 1 ...
[ "\n Convert Datetime Array to float64 ndarray of Julian Dates.\n 0 Julian date is noon January 1, 4713 BC.\n http://en.wikipedia.org/wiki/Julian_day\n " ]
Please provide a description of the function:def get_api_items(api_doc_fd): current_module = 'pandas' previous_line = current_section = current_subsection = '' position = None for line in api_doc_fd: line = line.strip() if len(line) == len(previous_line): if set(line) ==...
[ "\n Yield information about all public API items.\n\n Parse api.rst file from the documentation, and extract all the functions,\n methods, classes, attributes... This should include all pandas public API.\n\n Parameters\n ----------\n api_doc_fd : file descriptor\n A file descriptor of the ...
Please provide a description of the function:def get_validation_data(doc): errs = [] wrns = [] if not doc.raw_doc: errs.append(error('GL08')) return errs, wrns, '' if doc.start_blank_lines != 1: errs.append(error('GL01')) if doc.end_blank_lines != 1: errs.appen...
[ "\n Validate the docstring.\n\n Parameters\n ----------\n doc : Docstring\n A Docstring object with the given function name.\n\n Returns\n -------\n tuple\n errors : list of tuple\n Errors occurred during validation.\n warnings : list of tuple\n Warnin...
Please provide a description of the function:def validate_one(func_name): doc = Docstring(func_name) errs, wrns, examples_errs = get_validation_data(doc) return {'type': doc.type, 'docstring': doc.clean_doc, 'deprecated': doc.deprecated, 'file': doc.source_file_name,...
[ "\n Validate the docstring for the given func_name\n\n Parameters\n ----------\n func_name : function\n Function whose docstring will be evaluated (e.g. pandas.read_csv).\n\n Returns\n -------\n dict\n A dictionary containing all the information obtained from validating\n t...
Please provide a description of the function:def validate_all(prefix, ignore_deprecated=False): 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...
[ "\n Execute the validation of all docstrings, and return a dict with the\n results.\n\n Parameters\n ----------\n prefix : str or None\n If provided, only the docstrings that start with this pattern will be\n validated. If None, all docstrings will be validated.\n ignore_deprecated: ...
Please provide a description of the function:def _load_obj(name): 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...
[ "\n Import Python object from its name as string.\n\n Parameters\n ----------\n name : str\n Object name to import (e.g. pandas.Series.str.upper)\n\n Returns\n -------\n object\n Python object that can be a class, method, function...\n\n ...
Please provide a description of the function:def _to_original_callable(obj): while True: if inspect.isfunction(obj) or inspect.isclass(obj): f = inspect.getfile(obj) if f.startswith('<') and f.endswith('>'): return None ret...
[ "\n Find the Python object that contains the source code of the object.\n\n This is useful to find the place in the source code (file and line\n number) where a docstring is defined. It does not currently work for\n all cases, but it should help find some (properties...).\n " ]
Please provide a description of the function:def source_file_name(self): try: fname = inspect.getsourcefile(self.code_obj) except TypeError: # In some cases the object is something complex like a cython # object that can't be easily introspected. An it's bett...
[ "\n File name where the object is implemented (e.g. pandas/core/frame.py).\n " ]
Please provide a description of the function: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 Whet...
[]
Please provide a description of the function:def _value_with_fmt(self, val): 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): ...
[ "Convert numpy types to Python types for the Excel writers.\n\n Parameters\n ----------\n val : object\n Value to be written into cells\n\n Returns\n -------\n Tuple with the first element being the converted value and the second\n being an optional fo...
Please provide a description of the function:def check_extension(cls, ext): 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(...
[ "checks that path's extension against the Writer's supported\n extensions. If it isn't supported, raises UnsupportedFiletypeError." ]
Please provide a description of the function: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...
[ "\n Parse specified sheet(s) into a DataFrame\n\n Equivalent to read_excel(ExcelFile, ...) See the read_excel\n docstring for more info on accepted parameters\n " ]
Please provide a description of the function:def _validate_where(w): 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
[ "\n Validate that the where statement is of the right type.\n\n The type may either be String, Expr, or list-like of Exprs.\n\n Parameters\n ----------\n w : String term expression, Expr, or list-like of Exprs.\n\n Returns\n -------\n where : The original where clause if the check was succes...
Please provide a description of the function:def maybe_expression(s): 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)
[ " loose checking if s is a pytables-acceptable expression " ]
Please provide a description of the function:def conform(self, rhs): if not is_list_like(rhs): rhs = [rhs] if isinstance(rhs, np.ndarray): rhs = rhs.ravel() return rhs
[ " inplace conform rhs " ]
Please provide a description of the function:def generate(self, v): val = v.tostring(self.encoding) return "({lhs} {op} {val})".format(lhs=self.lhs, op=self.op, val=val)
[ " create and return the op string for this TermValue " ]
Please provide a description of the function:def convert_value(self, v): def stringify(value): if self.encoding is not None: encoder = partial(pprint_thing_encoded, encoding=self.encoding) else: encoder = pprint_...
[ " convert the expression that is in the term to something that is\n accepted by pytables " ]
Please provide a description of the function:def invert(self): if self.filter is not None: f = list(self.filter) f[1] = self.generate_filter_op(invert=True) self.filter = tuple(f) return self
[ " invert the filter " ]
Please provide a description of the function:def evaluate(self): try: self.condition = self.terms.prune(ConditionBinOp) except AttributeError: raise ValueError("cannot process expression [{expr}], [{slf}] " "is not a valid condition".format(...
[ " create and return the numexpr condition and filter " ]
Please provide a description of the function:def tostring(self, encoding): if self.kind == 'string': if encoding is not None: return self.converted return '"{converted}"'.format(converted=self.converted) elif self.kind == 'float': # python 2 s...
[ " quote the string if not encoded\n else encode and return " ]
Please provide a description of the function:def _ensure_decoded(s): if isinstance(s, (np.bytes_, bytes)): s = s.decode(pd.get_option('display.encoding')) return s
[ " if we have bytes, decode them to unicode " ]
Please provide a description of the function:def _result_type_many(*arrays_and_dtypes): try: return np.result_type(*arrays_and_dtypes) except ValueError: # we have > NPY_MAXARGS terms in our expression return reduce(np.result_type, arrays_and_dtypes)
[ " wrapper around numpy.result_type which overcomes the NPY_MAXARGS (32)\n argument limit " ]
Please provide a description of the function:def validate_argmin_with_skipna(skipna, args, kwargs): skipna, args = process_skipna(skipna, args) validate_argmin(args, kwargs) return skipna
[ "\n If 'Series.argmin' is called via the 'numpy' library,\n the third parameter in its signature is 'out', which\n takes either an ndarray or 'None', so check if the\n 'skipna' parameter is either an instance of ndarray or\n is None, since 'skipna' itself should be a boolean\n " ]
Please provide a description of the function:def validate_argmax_with_skipna(skipna, args, kwargs): skipna, args = process_skipna(skipna, args) validate_argmax(args, kwargs) return skipna
[ "\n If 'Series.argmax' is called via the 'numpy' library,\n the third parameter in its signature is 'out', which\n takes either an ndarray or 'None', so check if the\n 'skipna' parameter is either an instance of ndarray or\n is None, since 'skipna' itself should be a boolean\n " ]
Please provide a description of the function:def validate_argsort_with_ascending(ascending, args, kwargs): 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
[ "\n If 'Categorical.argsort' is called via the 'numpy' library, the\n first parameter in its signature is 'axis', which takes either\n an integer or 'None', so check if the 'ascending' parameter has\n either integer type or is None, since 'ascending' itself should\n be a boolean\n " ]
Please provide a description of the function:def validate_clip_with_axis(axis, args, kwargs): if isinstance(axis, ndarray): args = (axis,) + args axis = None validate_clip(args, kwargs) return axis
[ "\n If 'NDFrame.clip' is called via the numpy library, the third\n parameter in its signature is 'out', which can takes an ndarray,\n so check if the 'axis' parameter is an instance of ndarray, since\n 'axis' itself should either be an integer or None\n " ]
Please provide a description of the function:def validate_cum_func_with_skipna(skipna, args, kwargs, name): if not is_bool(skipna): args = (skipna,) + args skipna = True validate_cum_func(args, kwargs, fname=name) return skipna
[ "\n If this function is called via the 'numpy' library, the third\n parameter in its signature is 'dtype', which takes either a\n 'numpy' dtype or 'None', so check if the 'skipna' parameter is\n a boolean or not\n " ]
Please provide a description of the function:def validate_take_with_convert(convert, args, kwargs): 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
[ "\n If this function is called via the 'numpy' library, the third\n parameter in its signature is 'axis', which takes either an\n ndarray or 'None', so check if the 'convert' parameter is either\n an instance of ndarray or is None\n " ]
Please provide a description of the function:def validate_groupby_func(name, args, kwargs, allowed=None): if allowed is None: allowed = [] kwargs = set(kwargs) - set(allowed) if len(args) + len(kwargs) > 0: raise UnsupportedFunctionCall(( "numpy operations are not valid " ...
[ "\n 'args' and 'kwargs' should be empty, except for allowed\n kwargs because all of\n their necessary parameters are explicitly listed in\n the function signature\n " ]
Please provide a description of the function:def validate_resampler_func(method, args, kwargs): if len(args) + len(kwargs) > 0: if method in RESAMPLER_NUMPY_OPS: raise UnsupportedFunctionCall(( "numpy operations are not valid " "with resample. Use .resample(....
[ "\n 'args' and 'kwargs' should be empty because all of\n their necessary parameters are explicitly listed in\n the function signature\n " ]
Please provide a description of the function:def validate_minmax_axis(axis): 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 ({ndi...
[ "\n Ensure that the axis argument passed to min, max, argmin, or argmax is\n zero or None, as otherwise it will be incorrectly ignored.\n\n Parameters\n ----------\n axis : int or None\n\n Raises\n ------\n ValueError\n " ]
Please provide a description of the function:def to_msgpack(path_or_buf, *args, **kwargs): global compressor compressor = kwargs.pop('compress', None) append = kwargs.pop('append', None) if append: mode = 'a+b' else: mode = 'wb' def writer(fh): for a in args: ...
[ "\n msgpack (serialize) object to input file path\n\n THIS IS AN EXPERIMENTAL LIBRARY and the storage format\n may not be stable until a future release.\n\n Parameters\n ----------\n path_or_buf : string File path, buffer-like, or None\n if None, return generated string\n args ...
Please provide a description of the function:def read_msgpack(path_or_buf, encoding='utf-8', iterator=False, **kwargs): 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=...
[ "\n Load msgpack pandas object from the specified\n file path\n\n THIS IS AN EXPERIMENTAL LIBRARY and the storage format\n may not be stable until a future release.\n\n Parameters\n ----------\n path_or_buf : string File path, BytesIO like or string\n encoding : Encoding for decoding msgpack...
Please provide a description of the function:def dtype_for(t): if t in dtype_dict: return dtype_dict[t] return np.typeDict.get(t, t)
[ " return my dtype mapping, whether number or name " ]
Please provide a description of the function:def c2f(r, i, ctype_name): ftype = c2f_dict[ctype_name] return np.typeDict[ctype_name](ftype(r) + 1j * ftype(i))
[ "\n Convert strings to complex number instance with specified numpy type.\n " ]
Please provide a description of the function:def convert(values): 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.rave...
[ " convert the numpy values to a list " ]
Please provide a description of the function:def encode(obj): tobj = type(obj) if isinstance(obj, Index): if isinstance(obj, RangeIndex): return {'typ': 'range_index', 'klass': obj.__class__.__name__, 'name': getattr(obj, 'name', None), ...
[ "\n Data encoder\n " ]
Please provide a description of the function:def decode(obj): 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 == 'nat': r...
[ "\n Decoder for deserializing numpy data types.\n " ]
Please provide a description of the function:def pack(o, default=encode, encoding='utf-8', unicode_errors='strict', use_single_float=False, autoreset=1, use_bin_type=1): return Packer(default=default, encoding=encoding, unicode_errors=unicode_errors, use_s...
[ "\n Pack an object and return the packed bytes.\n " ]
Please provide a description of the function: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): return Unpacker(packed, object_hook=object_hook, ...
[ "\n Unpack a packed object, return an iterator\n Note: packed lists will be returned as tuples\n " ]
Please provide a description of the function: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, compr...
[ "\n Convert a JSON string to pandas object.\n\n Parameters\n ----------\n path_or_buf : a valid JSON string or file-like, default: None\n The string could be a URL. Valid URL schemes include http, ftp, s3,\n gcs, and file. For file URLs, a host is expected. For instance, a local\n f...
Please provide a description of the function:def _format_axes(self): 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))...
[ "\n Try to format axes if they are datelike.\n " ]
Please provide a description of the function:def _preprocess_data(self, data): if hasattr(data, 'read') and not self.chunksize: data = data.read() if not hasattr(data, 'read') and self.chunksize: data = StringIO(data) return data
[ "\n At this point, the data either has a `read` attribute (e.g. a file\n object or a StringIO) or is a string that is a JSON document.\n\n If self.chunksize, we prepare the data for the `__next__` method.\n Otherwise, we read it into memory for the `read` method.\n " ]
Please provide a description of the function:def _get_data_from_filepath(self, filepath_or_buffer): data = filepath_or_buffer exists = False if isinstance(data, str): try: exists = os.path.exists(filepath_or_buffer) # gh-5874: if the filepath is ...
[ "\n The function read_json accepts three input types:\n 1. filepath (string-like)\n 2. file-like object (e.g. open file object, StringIO)\n 3. JSON string\n\n This method turns (1) into (2) to simplify the rest of the processing.\n It returns input types (2) and...
Please provide a description of the function:def _combine_lines(self, lines): lines = filter(None, map(lambda x: x.strip(), lines)) return '[' + ','.join(lines) + ']'
[ "\n Combines a list of JSON objects into one JSON object.\n " ]
Please provide a description of the function:def read(self): 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')) ) ...
[ "\n Read the whole JSON input into a pandas object.\n " ]
Please provide a description of the function:def _get_object_parser(self, json): typ = self.typ dtype = self.dtype kwargs = { "orient": self.orient, "dtype": self.dtype, "convert_axes": self.convert_axes, "convert_dates": self.convert_dates, ...
[ "\n Parses a json document into a pandas object.\n " ]
Please provide a description of the function:def check_keys_split(self, decoded): 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}" ...
[ "\n Checks that dict has only the appropriate keys for orient='split'.\n " ]
Please provide a description of the function:def _convert_axes(self): 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: ...
[ "\n Try to convert axes.\n " ]
Please provide a description of the function:def _process_converter(self, f, filt=None): 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): ...
[ "\n Take a conversion function and possibly recreate the frame.\n " ]
Please provide a description of the function:def format_array(values, formatter, float_format=None, na_rep='NaN', digits=None, space=None, justify='right', decimal='.', leading_space=None): if is_datetime64_dtype(values.dtype): fmt_klass = Datetime64Formatter elif...
[ "\n Format an array for printing.\n\n Parameters\n ----------\n values\n formatter\n float_format\n na_rep\n digits\n space\n justify\n decimal\n leading_space : bool, optional\n Whether the array should be formatted with a leading space.\n When an array as a column...
Please provide a description of the function:def format_percentiles(percentiles): 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(perce...
[ "\n Outputs rounded and formatted percentiles.\n\n Parameters\n ----------\n percentiles : list-like, containing floats from interval [0,1]\n\n Returns\n -------\n formatted : list of strings\n\n Notes\n -----\n Rounding precision is chosen so that: (1) if any two elements of\n ``pe...
Please provide a description of the function:def _get_format_timedelta64(values, nat_rep='NaT', box=False): values_int = values.astype(np.int64) consider_values = values_int != iNaT one_day_nanos = (86400 * 1e9) even_days = np.logical_and(consider_values, values_in...
[ "\n Return a formatter function for a range of timedeltas.\n These will all have the same format argument\n\n If box, then show the return in quotes\n " ]
Please provide a description of the function:def _trim_zeros_complex(str_complexes, na_rep='NaN'): 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]...
[ "\n Separates the real and imaginary parts from the complex number, and\n executes the _trim_zeros_float method on each of those.\n " ]
Please provide a description of the function:def _trim_zeros_float(str_floats, na_rep='NaN'): 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...
[ "\n Trims zeros, leaving just one before the decimal points if need be.\n " ]
Please provide a description of the function:def set_eng_float_format(accuracy=3, use_eng_prefix=False): set_option("display.float_format", EngFormatter(accuracy, use_eng_prefix)) set_option("display.column_space", max(12, accuracy + 9))
[ "\n Alter default behavior on how float is formatted in DataFrame.\n Format float in engineering format. By accuracy, we mean the number of\n decimal digits after the floating point.\n\n See also EngFormatter.\n " ]
Please provide a description of the function:def get_level_lengths(levels, sentinel=''): 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 co...
[ "For each index in each level the function returns lengths of indexes.\n\n Parameters\n ----------\n levels : list of lists\n List of values on for level.\n sentinel : string, optional\n Value which states that no new index starts on there.\n\n Returns\n ----------\n Returns list ...
Please provide a description of the function:def buffer_put_lines(buf, lines): if any(isinstance(x, str) for x in lines): lines = [str(x) for x in lines] buf.write('\n'.join(lines))
[ "\n Appends lines to a buffer.\n\n Parameters\n ----------\n buf\n The buffer to write to\n lines\n The lines to append.\n " ]
Please provide a description of the function:def len(self, text): 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)
[ "\n Calculate display width considering unicode East Asian Width\n " ]
Please provide a description of the function:def _to_str_columns(self): 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: stringified = [] for i, c in...
[ "\n Render a DataFrame to a list of columns (as lists of strings).\n " ]
Please provide a description of the function:def to_string(self): 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}' .format(name=type(self.fra...
[ "\n Render a DataFrame to a console-friendly tabular output.\n " ]
Please provide a description of the function:def to_latex(self, column_format=None, longtable=False, encoding=None, multicolumn=False, multicolumn_format=None, multirow=False): from pandas.io.formats.latex import LatexFormatter latex_renderer = LatexFormatter(self, column_form...
[ "\n Render a DataFrame to a LaTeX tabular/longtable environment output.\n " ]
Please provide a description of the function:def to_html(self, classes=None, notebook=False, border=None): from pandas.io.formats.html import HTMLFormatter, NotebookFormatter Klass = NotebookFormatter if notebook else HTMLFormatter html = Klass(self, classes=classes, border=border).rend...
[ "\n Render a DataFrame to a html table.\n\n Parameters\n ----------\n classes : str or list-like\n classes to include in the `class` attribute of the opening\n ``<table>`` tag, in addition to the default \"dataframe\".\n notebook : {True, False}, optional, de...
Please provide a description of the function:def _value_formatter(self, float_format=None, threshold=None): # 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...
[ "Returns a function to be applied on each value to format it\n " ]
Please provide a description of the function:def get_result_as_array(self): 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: threshol...
[ "\n Returns the float values converted into strings using\n the parameters given at initialisation, as a numpy array\n " ]
Please provide a description of the function:def _format_strings(self): 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 in...
[ " we by definition have DO NOT have a TZ " ]
Please provide a description of the function:def _format_strings(self): values = self.values.astype(object) is_dates_only = _is_dates_only(values) formatter = (self.formatter or _get_format_datetime64(is_dates_only, date_...
[ " we by definition have a TZ " ]
Please provide a description of the function:def _get_interval_closed_bounds(interval): 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
[ "\n Given an Interval or IntervalIndex, return the corresponding interval with\n closed bounds.\n " ]
Please provide a description of the function:def _is_valid_endpoint(endpoint): return any([is_number(endpoint), isinstance(endpoint, Timestamp), isinstance(endpoint, Timedelta), endpoint is None])
[ "helper for interval_range to check if start/end are valid types" ]
Please provide a description of the function:def _is_type_compatible(a, b): 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) and is_ts_compat(b)) or ...
[ "helper for interval_range to check type compat of start/end/freq" ]
Please provide a description of the function:def save(self): # 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."...
[ "\n Create the writer & save\n " ]
Please provide a description of the function:def delegate_names(delegate, accessors, typ, overwrite=False): def add_delegate_accessors(cls): cls._add_delegate_accessors(delegate, accessors, typ, overwrite=overwrite) return cls return add_delegate_accesso...
[ "\n Add delegated names to a class using a class decorator. This provides\n an alternative usage to directly calling `_add_delegate_accessors`\n below a class definition.\n\n Parameters\n ----------\n delegate : object\n the class to get methods/properties & doc-strings\n accessors : Se...
Please provide a description of the function:def _dir_additions(self): rv = set() for accessor in self._accessors: try: getattr(self, accessor) rv.add(accessor) except AttributeError: pass return rv
[ "\n Add additional __dir__ for this object.\n " ]
Please provide a description of the function:def _add_delegate_accessors(cls, delegate, accessors, typ, overwrite=False): def _create_delegator_property(name): def _getter(self): return self._delegate_property_get(name) def _set...
[ "\n Add accessors to cls from the delegate class.\n\n Parameters\n ----------\n cls : the class to add the methods/properties to\n delegate : the class to get methods/properties & doc-strings\n accessors : string list of accessors to add\n typ : 'property' or 'method...
Please provide a description of the function:def _evaluate_standard(op, op_str, a, b, **eval_kwargs): if _TEST_MODE: _store_test_result(False) with np.errstate(all='ignore'): return op(a, b)
[ " standard evaluation " ]
Please provide a description of the function:def _can_use_numexpr(op, op_str, a, b, dtype_check): 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() ...
[ " return a boolean if we WILL be using numexpr " ]
Please provide a description of the function:def evaluate(op, op_str, a, b, use_numexpr=True, **eval_kwargs): 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)
[ " evaluate and return the expression of the op on a and b\n\n Parameters\n ----------\n\n op : the actual operand\n op_str: the string version of the op\n a : left operand\n b : right operand\n use_numexpr : whether to try to use numexpr (default True)\n ...
Please provide a description of the function:def where(cond, a, b, use_numexpr=True): if use_numexpr: return _where(cond, a, b) return _where_standard(cond, a, b)
[ " evaluate the where condition cond on a and b\n\n Parameters\n ----------\n\n cond : a boolean array\n a : return if cond is True\n b : return if cond is False\n use_numexpr : whether to try to use numexpr (default True)\n " ]
Please provide a description of the function:def write(self, writer, sheet_name='Sheet1', startrow=0, startcol=0, freeze_panes=None, engine=None): from pandas.io.excel import ExcelWriter from pandas.io.common import _stringify_path if isinstance(writer, ExcelWriter): ...
[ "\n writer : string or ExcelWriter object\n File path or existing ExcelWriter\n sheet_name : string, default 'Sheet1'\n Name of sheet which will contain DataFrame\n startrow :\n upper left cell row to dump data frame\n startcol :\n upper left c...
Please provide a description of the function:def to_feather(df, path): 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 # -----...
[ "\n Write a DataFrame to the feather-format\n\n Parameters\n ----------\n df : DataFrame\n path : string file path, or file-like object\n\n " ]
Please provide a description of the function:def read_feather(path, columns=None, use_threads=True): 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: ...
[ "\n Load a feather-format object from the file path\n\n .. versionadded 0.20.0\n\n Parameters\n ----------\n path : string file path, or file-like object\n columns : sequence, default None\n If not provided, all columns are read\n\n .. versionadded 0.24.0\n nthreads : int, default...
Please provide a description of the function:def generate_regular_range(start, end, periods, freq): 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 ...
[ "\n Generate a range of dates with the spans between dates described by\n the given `freq` DateOffset.\n\n Parameters\n ----------\n start : Timestamp or None\n first point of produced date range\n end : Timestamp or None\n last point of produced date range\n periods : int\n ...
Please provide a description of the function:def _generate_range_overflow_safe(endpoint, periods, stride, side='start'): # 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}={end...
[ "\n Calculate the second endpoint for passing to np.arange, checking\n to avoid an integer overflow. Catch OverflowError and re-raise\n as OutOfBoundsDatetime.\n\n Parameters\n ----------\n endpoint : int\n nanosecond timestamp of the known endpoint of the desired range\n periods : int\...
Please provide a description of the function:def _generate_range_overflow_safe_signed(endpoint, periods, stride, side): assert side in ['start', 'end'] if side == 'end': stride *= -1 with np.errstate(over="raise"): addend = np.int64(periods) * np.int64(stride) try: ...
[ "\n A special case for _generate_range_overflow_safe where `periods * stride`\n can be calculated without overflowing int64 bounds.\n " ]
Please provide a description of the function:def set_locale(new_locale, lc_var=locale.LC_ALL): 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 '....
[ "\n Context manager for temporarily setting a locale.\n\n Parameters\n ----------\n new_locale : str or tuple\n A string of the form <language_country>.<encoding>. For example to set\n the current locale to US English with a UTF8 encoding, you would pass\n \"en_US.UTF-8\".\n lc_v...
Please provide a description of the function:def can_set_locale(lc, lc_var=locale.LC_ALL): 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
[ "\n Check to see if we can set a locale, and subsequently get the locale,\n without raising an Exception.\n\n Parameters\n ----------\n lc : str\n The locale to attempt to set.\n lc_var : int, default `locale.LC_ALL`\n The category of the locale being set.\n\n Returns\n -------...
Please provide a description of the function:def _valid_locales(locales, normalize): if normalize: normalizer = lambda x: locale.normalize(x.strip()) else: normalizer = lambda x: x.strip() return list(filter(can_set_locale, map(normalizer, locales)))
[ "\n Return a list of normalized locales that do not throw an ``Exception``\n when set.\n\n Parameters\n ----------\n locales : str\n A string where each locale is separated by a newline.\n normalize : bool\n Whether to call ``locale.normalize`` on each locale.\n\n Returns\n ---...
Please provide a description of the function:def get_locales(prefix=None, normalize=True, locale_getter=_default_locale_getter): try: raw_locales = locale_getter() except Exception: return None try: # raw_locales is "\n" separated list of locales # it ma...
[ "\n Get all the locales that are available on the system.\n\n Parameters\n ----------\n prefix : str\n If not ``None`` then return only those locales with the prefix\n provided. For example to get all English language locales (those that\n start with ``\"en\"``), pass ``prefix=\"en\...
Please provide a description of the function:def ensure_float(arr): if issubclass(arr.dtype.type, (np.integer, np.bool_)): arr = arr.astype(float) return arr
[ "\n Ensure that an array object has a float dtype if possible.\n\n Parameters\n ----------\n arr : array-like\n The array whose data type we want to enforce as float.\n\n Returns\n -------\n float_arr : The original array cast to the float dtype if\n possible. Otherwise, t...
Please provide a description of the function:def ensure_categorical(arr): if not is_categorical(arr): from pandas import Categorical arr = Categorical(arr) return arr
[ "\n Ensure that an array-like object is a Categorical (if not already).\n\n Parameters\n ----------\n arr : array-like\n The array that we want to convert into a Categorical.\n\n Returns\n -------\n cat_arr : The original array cast as a Categorical. If it already\n is a Cat...
Please provide a description of the function:def ensure_int64_or_float64(arr, copy=False): try: return arr.astype('int64', copy=copy, casting='safe') except TypeError: return arr.astype('float64', copy=copy)
[ "\n Ensure that an dtype array of some integer dtype\n has an int64 dtype if possible\n If it's not possible, potentially because of overflow,\n convert the array to float64 instead.\n\n Parameters\n ----------\n arr : array-like\n The array whose data type we want to enforce.\n cop...
Please provide a description of the function:def classes_and_not_datetimelike(*klasses): return lambda tipo: (issubclass(tipo, klasses) and not issubclass(tipo, (np.datetime64, np.timedelta64)))
[ "\n evaluate if the tipo is a subclass of the klasses\n and not a datetimelike\n " ]