Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def html(self): ret_code = self._sphinx_build('html') zip_fname = os.path.join(BUILD_PATH, 'html', 'pandas.zip') if os.path.exists(zip_fname): os.remove(zip_fname) if self.single_doc_html is not None: self._op...
[ "\n Build HTML documentation.\n " ]
Please provide a description of the function:def latex(self, force=False): if sys.platform == 'win32': sys.stderr.write('latex build has not been tested on windows\n') else: ret_code = self._sphinx_build('latex') os.chdir(os.path.join(BUILD_PATH, 'latex')) ...
[ "\n Build PDF documentation.\n " ]
Please provide a description of the function:def clean(): shutil.rmtree(BUILD_PATH, ignore_errors=True) shutil.rmtree(os.path.join(SOURCE_PATH, 'reference', 'api'), ignore_errors=True)
[ "\n Clean documentation generated files.\n " ]
Please provide a description of the function:def zip_html(self): zip_fname = os.path.join(BUILD_PATH, 'html', 'pandas.zip') if os.path.exists(zip_fname): os.remove(zip_fname) dirname = os.path.join(BUILD_PATH, 'html') fnames = os.listdir(dirname) os.chdir(dir...
[ "\n Compress HTML documentation into a zip file.\n " ]
Please provide a description of the function:def write_result(self, buf): # string representation of the columns if len(self.frame.columns) == 0 or len(self.frame.index) == 0: info_line = ('Empty {name}\nColumns: {col}\nIndex: {idx}' .format(name=type(self....
[ "\n Render a DataFrame to a LaTeX tabular/longtable environment output.\n " ]
Please provide a description of the function:def _format_multicolumn(self, row, ilevels): r row2 = list(row[:ilevels]) ncol = 1 coltext = '' def append_col(): # write multicolumn if needed if ncol > 1: row2.append('\\multicolumn{{{ncol:d}}...
[ "\n Combine columns belonging to a group to a single multicolumn entry\n according to self.multicolumn_format\n\n e.g.:\n a & & & b & c &\n will become\n \\multicolumn{3}{l}{a} & b & \\multicolumn{2}{l}{c}\n " ]
Please provide a description of the function:def _format_multirow(self, row, ilevels, i, rows): r for j in range(ilevels): if row[j].strip(): nrow = 1 for r in rows[i + 1:]: if not r[j].strip(): nrow += 1 ...
[ "\n Check following rows, whether row should be a multirow\n\n e.g.: becomes:\n a & 0 & \\multirow{2}{*}{a} & 0 &\n & 1 & & 1 &\n b & 0 & \\cline{1-2}\n b & 0 &\n " ]
Please provide a description of the function:def _print_cline(self, buf, i, icol): for cl in self.clinebuf: if cl[0] == i: buf.write('\\cline{{{cl:d}-{icol:d}}}\n' .format(cl=cl[1], icol=icol)) # remove entries that have been written to buff...
[ "\n Print clines after multirow-blocks are finished\n " ]
Please provide a description of the function:def _validate_integer(name, val, min_val=0): msg = "'{name:s}' must be an integer >={min_val:d}".format(name=name, min_val=min_val) if val is not None: if is_float(val): if int(v...
[ "\n Checks whether the 'name' parameter for parsing is either\n an integer OR float that can SAFELY be cast to an integer\n without losing accuracy. Raises a ValueError if that is\n not the case.\n\n Parameters\n ----------\n name : string\n Parameter name (used for error reporting)\n ...
Please provide a description of the function:def _validate_names(names): if names is not None: if len(names) != len(set(names)): msg = ("Duplicate names specified. This " "will raise an error in the future.") warnings.warn(msg, UserWarning, stacklevel=3) ...
[ "\n Check if the `names` parameter contains duplicates.\n\n If duplicates are found, we issue a warning before returning.\n\n Parameters\n ----------\n names : array-like or None\n An array containing a list of the names used for the output DataFrame.\n\n Returns\n -------\n names : a...
Please provide a description of the function:def _read(filepath_or_buffer: FilePathOrBuffer, kwds): encoding = kwds.get('encoding', None) if encoding is not None: encoding = re.sub('_', '-', encoding).lower() kwds['encoding'] = encoding compression = kwds.get('compression', 'infer') ...
[ "Generic reader of line files." ]
Please provide a description of the function:def read_fwf(filepath_or_buffer: FilePathOrBuffer, colspecs='infer', widths=None, infer_nrows=100, **kwds): r # Check input arguments. if colspecs is None and widths is None: raise ValueError("Must spe...
[ "\n Read a table of fixed-width formatted lines into DataFrame.\n\n Also supports optionally iterating or breaking of the file\n into chunks.\n\n Additional help can be found in the `online docs for IO Tools\n <http://pandas.pydata.org/pandas-docs/stable/io.html>`_.\n\n Parameters\n ----------\...
Please provide a description of the function:def _is_potential_multi_index(columns): return (len(columns) and not isinstance(columns, MultiIndex) and all(isinstance(c, tuple) for c in columns))
[ "\n Check whether or not the `columns` parameter\n could be converted into a MultiIndex.\n\n Parameters\n ----------\n columns : array-like\n Object which may or may not be convertible into a MultiIndex\n\n Returns\n -------\n boolean : Whether or not columns could become a MultiIndex...
Please provide a description of the function:def _evaluate_usecols(usecols, names): if callable(usecols): return {i for i, name in enumerate(names) if usecols(name)} return usecols
[ "\n Check whether or not the 'usecols' parameter\n is a callable. If so, enumerates the 'names'\n parameter and returns a set of indices for\n each entry in 'names' that evaluates to True.\n If not a callable, returns 'usecols'.\n " ]
Please provide a description of the function:def _validate_usecols_names(usecols, names): missing = [c for c in usecols if c not in names] if len(missing) > 0: raise ValueError( "Usecols do not match columns, " "columns expected but not found: {missing}".format(missing=missi...
[ "\n Validates that all usecols are present in a given\n list of names. If not, raise a ValueError that\n shows what usecols are missing.\n\n Parameters\n ----------\n usecols : iterable of usecols\n The columns to validate are present in names.\n names : iterable of names\n The co...
Please provide a description of the function:def _validate_usecols_arg(usecols): msg = ("'usecols' must either be list-like of all strings, all unicode, " "all integers or a callable.") if usecols is not None: if callable(usecols): return usecols, None if not is_list...
[ "\n Validate the 'usecols' parameter.\n\n Checks whether or not the 'usecols' parameter contains all integers\n (column selection by index), strings (column by name) or is a callable.\n Raises a ValueError if that is not the case.\n\n Parameters\n ----------\n usecols : list-like, callable, or ...
Please provide a description of the function:def _validate_parse_dates_arg(parse_dates): msg = ("Only booleans, lists, and " "dictionaries are accepted " "for the 'parse_dates' parameter") if parse_dates is not None: if is_scalar(parse_dates): if not lib.is_bool(p...
[ "\n Check whether or not the 'parse_dates' parameter\n is a non-boolean scalar. Raises a ValueError if\n that is the case.\n " ]
Please provide a description of the function:def _stringify_na_values(na_values): result = [] for x in na_values: result.append(str(x)) result.append(x) try: v = float(x) # we are like 999 here if v == int(v): v = int(v) ...
[ " return a stringified and numeric for these values " ]
Please provide a description of the function:def _get_na_values(col, na_values, na_fvalues, keep_default_na): if isinstance(na_values, dict): if col in na_values: return na_values[col], na_fvalues[col] else: if keep_default_na: return _NA_VALUES, set() ...
[ "\n Get the NaN values for a given column.\n\n Parameters\n ----------\n col : str\n The name of the column.\n na_values : array-like, dict\n The object listing the NaN values as strings.\n na_fvalues : array-like, dict\n The object listing the NaN values as floats.\n keep_...
Please provide a description of the function:def _extract_multi_indexer_columns(self, header, index_names, col_names, passed_names=False): if len(header) < 2: return header[0], index_names, col_names, passed_names # the names are the tuples of...
[ " extract and return the names, index_names, col_names\n header is a list-of-lists returned from the parsers " ]
Please provide a description of the function:def _infer_types(self, values, na_values, try_num_bool=True): na_count = 0 if issubclass(values.dtype.type, (np.number, np.bool_)): mask = algorithms.isin(values, list(na_values)) na_count = mask.sum() if na_count ...
[ "\n Infer types of values, possibly casting\n\n Parameters\n ----------\n values : ndarray\n na_values : set\n try_num_bool : bool, default try\n try to cast values to numeric (first preference) or boolean\n\n Returns:\n --------\n converted :...
Please provide a description of the function:def _cast_types(self, values, cast_type, column): if is_categorical_dtype(cast_type): known_cats = (isinstance(cast_type, CategoricalDtype) and cast_type.categories is not None) if not is_object_dtype(value...
[ "\n Cast values to specified type\n\n Parameters\n ----------\n values : ndarray\n cast_type : string or np.dtype\n dtype to cast values to\n column : string\n column name - used only for error reporting\n\n Returns\n -------\n conv...
Please provide a description of the function:def _handle_usecols(self, columns, usecols_key): if self.usecols is not None: if callable(self.usecols): col_indices = _evaluate_usecols(self.usecols, usecols_key) elif any(isinstance(u, str) for u in self.usecols): ...
[ "\n Sets self._col_indices\n\n usecols_key is used if there are string usecols.\n " ]
Please provide a description of the function:def _check_for_bom(self, first_row): # first_row will be a list, so we need to check # that that list is not empty before proceeding. if not first_row: return first_row # The first element of this row is the one that coul...
[ "\n Checks whether the file begins with the BOM character.\n If it does, remove it. In addition, if there is quoting\n in the field subsequent to the BOM, remove it as well\n because it technically takes place at the beginning of\n the name, not the middle of it.\n " ]
Please provide a description of the function:def _alert_malformed(self, msg, row_num): if self.error_bad_lines: raise ParserError(msg) elif self.warn_bad_lines: base = 'Skipping line {row_num}: '.format(row_num=row_num) sys.stderr.write(base + msg + '\n')
[ "\n Alert a user about a malformed row.\n\n If `self.error_bad_lines` is True, the alert will be `ParserError`.\n If `self.warn_bad_lines` is True, the alert will be printed out.\n\n Parameters\n ----------\n msg : The error message to display.\n row_num : The row nu...
Please provide a description of the function:def _next_iter_line(self, row_num): try: return next(self.data) except csv.Error as e: if self.warn_bad_lines or self.error_bad_lines: msg = str(e) if 'NULL byte' in msg: m...
[ "\n Wrapper around iterating through `self.data` (CSV source).\n\n When a CSV error is raised, we check for specific\n error messages that allow us to customize the\n error message displayed to the user.\n\n Parameters\n ----------\n row_num : The row number of the l...
Please provide a description of the function:def _remove_empty_lines(self, lines): ret = [] for l in lines: # Remove empty lines and lines with only one whitespace value if (len(l) > 1 or len(l) == 1 and (not isinstance(l[0], str) or l[0].strip())): ...
[ "\n Iterate through the lines and remove any that are\n either empty or contain only one whitespace value\n\n Parameters\n ----------\n lines : array-like\n The array of lines that we are to filter.\n\n Returns\n -------\n filtered_lines : array-lik...
Please provide a description of the function:def _get_index_name(self, columns): orig_names = list(columns) columns = list(columns) try: line = self._next_line() except StopIteration: line = None try: next_line = self._next_line() ...
[ "\n Try several cases to get lines:\n\n 0) There are headers on row 0 and row 1 and their\n total summed lengths equals the length of the next line.\n Treat row 0 as columns and row 1 as indices\n 1) Look for implicit index: there are more columns\n on row 1 than row 0. If ...
Please provide a description of the function:def get_rows(self, infer_nrows, skiprows=None): if skiprows is None: skiprows = set() buffer_rows = [] detect_rows = [] for i, row in enumerate(self.f): if i not in skiprows: detect_rows.append(...
[ "\n Read rows from self.f, skipping as specified.\n\n We distinguish buffer_rows (the first <= infer_nrows\n lines) from the rows returned to detect_colspecs\n because it's simpler to leave the other locations\n with skiprows logic alone than to modify them to\n deal with t...
Please provide a description of the function:def linkcode_resolve(domain, info): if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.spli...
[ "\n Determine the URL corresponding to Python object\n " ]
Please provide a description of the function:def process_class_docstrings(app, what, name, obj, options, lines): if what == "class": joined = '\n'.join(lines) templates = [ , ] for template in templates: if template in joined: ...
[ "\n For those classes for which we use ::\n\n :template: autosummary/class_without_autosummary.rst\n\n the documented attributes/methods have to be listed in the class\n docstring. However, if one of those lists is empty, we use 'None',\n which then generates warnings in sphinx / ugly html output.\n ...
Please provide a description of the function:def pack(o, stream, **kwargs): packer = Packer(**kwargs) stream.write(packer.pack(o))
[ "\n Pack object `o` and write it to `stream`\n\n See :class:`Packer` for options.\n " ]
Please provide a description of the function:def get_mgr_concatenation_plan(mgr, indexers): # Calculate post-reindex shape , save for item axis which will be separate # for each block anyway. mgr_shape = list(mgr.shape) for ax, indexer in indexers.items(): mgr_shape[ax] = len(indexer) m...
[ "\n Construct concatenation plan for given block manager and indexers.\n\n Parameters\n ----------\n mgr : BlockManager\n indexers : dict of {axis: indexer}\n\n Returns\n -------\n plan : list of (BlockPlacement, JoinUnit) tuples\n\n " ]
Please provide a description of the function:def concatenate_join_units(join_units, concat_axis, copy): if concat_axis == 0 and len(join_units) > 1: # Concatenating join units along ax0 is handled in _merge_blocks. raise AssertionError("Concatenating join units along axis0") empty_dtype, u...
[ "\n Concatenate values from several join units along selected axis.\n " ]
Please provide a description of the function:def get_empty_dtype_and_na(join_units): if len(join_units) == 1: blk = join_units[0].block if blk is None: return np.float64, np.nan if is_uniform_reindex(join_units): # XXX: integrate property empty_dtype = join_unit...
[ "\n Return dtype and N/A values to use when concatenating specified units.\n\n Returned N/A value may be None which means there was no casting involved.\n\n Returns\n -------\n dtype\n na\n " ]
Please provide a description of the function:def is_uniform_join_units(join_units): return ( # all blocks need to have the same type all(type(ju.block) is type(join_units[0].block) for ju in join_units) and # noqa # no blocks that would get missing values (can lead to type upcasts) ...
[ "\n Check if the join units consist of blocks of uniform type that can\n be concatenated using Block.concat_same_type instead of the generic\n concatenate_join_units (which uses `_concat._concat_compat`).\n\n " ]
Please provide a description of the function:def trim_join_unit(join_unit, length): if 0 not in join_unit.indexers: extra_indexers = join_unit.indexers if join_unit.block is None: extra_block = None else: extra_block = join_unit.block.getitem_block(slice(length...
[ "\n Reduce join_unit's shape along item axis to length.\n\n Extra items that didn't fit are returned as a separate block.\n " ]
Please provide a description of the function:def combine_concat_plans(plans, concat_axis): if len(plans) == 1: for p in plans[0]: yield p[0], [p[1]] elif concat_axis == 0: offset = 0 for plan in plans: last_plc = None for plc, unit in plan: ...
[ "\n Combine multiple concatenation plans into one.\n\n existing_plan is updated in-place.\n " ]
Please provide a description of the function:def use(self, key, value): old_value = self[key] try: self[key] = value yield self finally: self[key] = old_value
[ "\n Temporarily set a parameter value using the with statement.\n Aliasing allowed.\n " ]
Please provide a description of the function:def _stata_elapsed_date_to_datetime_vec(dates, fmt): MIN_YEAR, MAX_YEAR = Timestamp.min.year, Timestamp.max.year MAX_DAY_DELTA = (Timestamp.max - datetime.datetime(1960, 1, 1)).days MIN_DAY_DELTA = (Timestamp.min - datetime.datetime(1960, 1, 1)).days MIN...
[ "\n Convert from SIF to datetime. http://www.stata.com/help.cgi?datetime\n\n Parameters\n ----------\n dates : Series\n The Stata Internal Format date to convert to datetime according to fmt\n fmt : str\n The format to convert to. Can be, tc, td, tw, tm, tq, th, ty\n Returns\n\n ...
Please provide a description of the function:def _datetime_to_stata_elapsed_vec(dates, fmt): index = dates.index NS_PER_DAY = 24 * 3600 * 1000 * 1000 * 1000 US_PER_DAY = NS_PER_DAY / 1000 def parse_dates_safe(dates, delta=False, year=False, days=False): d = {} if is_datetime64_dtyp...
[ "\n Convert from datetime to SIF. http://www.stata.com/help.cgi?datetime\n\n Parameters\n ----------\n dates : Series\n Series or array containing datetime.datetime or datetime64[ns] to\n convert to the Stata Internal Format given by fmt\n fmt : str\n The format to convert to. Ca...
Please provide a description of the function:def _cast_to_stata_types(data): ws = '' # original, if small, if large conversion_data = ((np.bool, np.int8, np.int8), (np.uint8, np.int8, np.int16), (np.uint16, np.int16, np.int32), ...
[ "Checks the dtypes of the columns of a pandas DataFrame for\n compatibility with the data types and ranges supported by Stata, and\n converts if necessary.\n\n Parameters\n ----------\n data : DataFrame\n The DataFrame to check and convert\n\n Notes\n -----\n Numeric columns in Stata ...
Please provide a description of the function:def _dtype_to_stata_type(dtype, column): # TODO: expand to handle datetime to integer conversion if dtype.type == np.object_: # try to coerce it to the biggest string # not memory efficient, what else could we # do? itemsize = max_len_st...
[ "\n Convert dtype types to stata types. Returns the byte of the given ordinal.\n See TYPE_MAP and comments for an explanation. This is also explained in\n the dta spec.\n 1 - 244 are strings of this length\n Pandas Stata\n 251 - for int8 byte\n 252 - for int16 i...
Please provide a description of the function:def _dtype_to_default_stata_fmt(dtype, column, dta_version=114, force_strl=False): # TODO: Refactor to combine type with format # TODO: expand this to handle a default datetime format? if dta_version < 117: max_str_len...
[ "\n Map numpy dtype to stata's default format for this type. Not terribly\n important since users can change this in Stata. Semantics are\n\n object -> \"%DDs\" where DD is the length of the string. If not a string,\n raise ValueError\n float64 -> \"%10.0g\"\n float32 -> \"%9.0g\"\n ...
Please provide a description of the function:def _pad_bytes_new(name, length): if isinstance(name, str): name = bytes(name, 'utf-8') return name + b'\x00' * (length - len(name))
[ "\n Takes a bytes instance and pads it with null bytes until it's length chars.\n " ]
Please provide a description of the function:def generate_value_label(self, byteorder, encoding): self._encoding = encoding bio = BytesIO() null_string = '\x00' null_byte = b'\x00' # len bio.write(struct.pack(byteorder + 'i', self.len)) # labname ...
[ "\n Parameters\n ----------\n byteorder : str\n Byte order of the output\n encoding : str\n File encoding\n\n Returns\n -------\n value_label : bytes\n Bytes containing the formatted value label\n " ]
Please provide a description of the function:def _setup_dtype(self): if self._dtype is not None: return self._dtype dtype = [] # Convert struct data types to numpy data type for i, typ in enumerate(self.typlist): if typ in self.NUMPY_TYPE_MAP: d...
[ "Map between numpy and state dtypes" ]
Please provide a description of the function:def _do_convert_categoricals(self, data, value_label_dict, lbllist, order_categoricals): value_labels = list(value_label_dict.keys()) cat_converted_data = [] for col, label in zip(data, lbllist): i...
[ "\n Converts categorical columns to Categorical type.\n ", "\nValue labels for column {col} are not unique. These cannot be converted to\npandas categoricals.\n\nEither read the file with `convert_categoricals` set to False or use the\nlow level interface in `StataReader` to separately read the valu...
Please provide a description of the function:def _write(self, to_write): self._file.write(to_write.encode(self._encoding or self._default_encoding))
[ "\n Helper to call encode before writing to file for Python 3 compat.\n " ]
Please provide a description of the function:def _prepare_categoricals(self, data): is_cat = [is_categorical_dtype(data[col]) for col in data] self._is_col_cat = is_cat self._value_labels = [] if not any(is_cat): return data get_base_missing_value = StataMi...
[ "Check for categorical columns, retain categorical information for\n Stata file and convert categorical data to int" ]
Please provide a description of the function:def _replace_nans(self, data): # return data for c in data: dtype = data[c].dtype if dtype in (np.float32, np.float64): if dtype == np.float32: replacement = self.MISSING_VALUES['f'] ...
[ "Checks floating point data columns for nans, and replaces these with\n the generic Stata for missing value (.)" ]
Please provide a description of the function:def _check_column_names(self, data): converted_names = {} columns = list(data.columns) original_columns = columns[:] duplicate_var_id = 0 for j, name in enumerate(columns): orig_name = name if not isin...
[ "\n Checks column names to ensure that they are valid Stata column names.\n This includes checks for:\n * Non-string names\n * Stata keywords\n * Variables that start with numbers\n * Variables with names that are too long\n\n When an illegal variable...
Please provide a description of the function:def _close(self): # Some file-like objects might not support flush try: self._file.flush() except AttributeError: pass if self._own_file: self._file.close()
[ "\n Close the file if it was created by the writer.\n\n If a buffer or file-like object was passed in, for example a GzipFile,\n then leave this file open for the caller to close. In either case,\n attempt to flush the file contents to ensure they are written to disk\n (if support...
Please provide a description of the function:def generate_table(self): gso_table = self._gso_table gso_df = self.df columns = list(gso_df.columns) selected = gso_df[self.columns] col_index = [(col, columns.index(col)) for col in self.columns] keys = np.empty(sel...
[ "\n Generates the GSO lookup table for the DataFRame\n\n Returns\n -------\n gso_table : OrderedDict\n Ordered dictionary using the string found as keys\n and their lookup position (v,o) as values\n gso_df : DataFrame\n DataFrame where strl columns...
Please provide a description of the function:def generate_blob(self, gso_table): # Format information # Length includes null term # 117 # GSOvvvvooootllllxxxxxxxxxxxxxxx...x # 3 u4 u4 u1 u4 string + null term # # 118, 119 # GSOvvvvooooooootlll...
[ "\n Generates the binary blob of GSOs that is written to the dta file.\n\n Parameters\n ----------\n gso_table : OrderedDict\n Ordered dictionary (str, vo)\n\n Returns\n -------\n gso : bytes\n Binary content of dta file to be placed between str...
Please provide a description of the function:def _tag(val, tag): if isinstance(val, str): val = bytes(val, 'utf-8') return (bytes('<' + tag + '>', 'utf-8') + val + bytes('</' + tag + '>', 'utf-8'))
[ "Surround val with <tag></tag>" ]
Please provide a description of the function:def _write_header(self, data_label=None, time_stamp=None): byteorder = self._byteorder self._file.write(bytes('<stata_dta>', 'utf-8')) bio = BytesIO() # ds_format - 117 bio.write(self._tag(bytes('117', 'utf-8'), 'release')) ...
[ "Write the file header" ]
Please provide a description of the function:def _write_map(self): if self._map is None: self._map = OrderedDict((('stata_data', 0), ('map', self._file.tell()), ('variable_types', 0), ...
[ "Called twice during file write. The first populates the values in\n the map with 0s. The second call writes the final map locations when\n all blocks have been written." ]
Please provide a description of the function:def _update_strl_names(self): # Update convert_strl if names changed for orig, new in self._converted_names.items(): if orig in self._convert_strl: idx = self._convert_strl.index(orig) self._convert_strl[id...
[ "Update column names for conversion to strl if they might have been\n changed to comply with Stata naming rules" ]
Please provide a description of the function:def _convert_strls(self, data): convert_cols = [ col for i, col in enumerate(data) if self.typlist[i] == 32768 or col in self._convert_strl] if convert_cols: ssw = StataStrLWriter(data, convert_cols) t...
[ "Convert columns to StrLs if either very large or in the\n convert_strl variable" ]
Please provide a description of the function:def register(explicit=True): # Renamed in pandas.plotting.__init__ global _WARN if explicit: _WARN = False pairs = get_pairs() for type_, cls in pairs: converter = cls() if type_ in units.registry: previous = uni...
[ "\n Register Pandas Formatters and Converters with matplotlib\n\n This function modifies the global ``matplotlib.units.registry``\n dictionary. Pandas adds custom converters for\n\n * pd.Timestamp\n * pd.Period\n * np.datetime64\n * datetime.datetime\n * datetime.date\n * datetime.time\n\...
Please provide a description of the function:def deregister(): # Renamed in pandas.plotting.__init__ for type_, cls in get_pairs(): # We use type to catch our classes directly, no inheritance if type(units.registry.get(type_)) is cls: units.registry.pop(type_) # restore the...
[ "\n Remove pandas' formatters and converters\n\n Removes the custom converters added by :func:`register`. This\n attempts to set the state of the registry back to the state before\n pandas registered its own units. Converters for pandas' own types like\n Timestamp and Period are removed completely. C...
Please provide a description of the function:def _dt_to_float_ordinal(dt): if (isinstance(dt, (np.ndarray, Index, ABCSeries) ) and is_datetime64_ns_dtype(dt)): base = dates.epoch2num(dt.asi8 / 1.0E9) else: base = dates.date2num(dt) return base
[ "\n Convert :mod:`datetime` to the Gregorian date as UTC float days,\n preserving hours, minutes, seconds and microseconds. Return value\n is a :func:`float`.\n " ]
Please provide a description of the function:def _get_default_annual_spacing(nyears): if nyears < 11: (min_spacing, maj_spacing) = (1, 1) elif nyears < 20: (min_spacing, maj_spacing) = (1, 2) elif nyears < 50: (min_spacing, maj_spacing) = (1, 5) elif nyears < 100: (m...
[ "\n Returns a default spacing between consecutive ticks for annual data.\n " ]
Please provide a description of the function:def period_break(dates, period): current = getattr(dates, period) previous = getattr(dates - 1 * dates.freq, period) return np.nonzero(current - previous)[0]
[ "\n Returns the indices where the given period changes.\n\n Parameters\n ----------\n dates : PeriodIndex\n Array of intervals to monitor.\n period : string\n Name of the period to monitor.\n " ]
Please provide a description of the function:def has_level_label(label_flags, vmin): if label_flags.size == 0 or (label_flags.size == 1 and label_flags[0] == 0 and vmin % 1 > 0.0): return False else: return True
[ "\n Returns true if the ``label_flags`` indicate there is at least one label\n for this level.\n\n if the minimum view limit is not an exact integer, then the first tick\n label won't be shown, so we must adjust for that.\n " ]
Please provide a description of the function:def axisinfo(unit, axis): tz = unit majloc = PandasAutoDateLocator(tz=tz) majfmt = PandasAutoDateFormatter(majloc, tz=tz) datemin = pydt.date(2000, 1, 1) datemax = pydt.date(2010, 1, 1) return units.AxisInfo(majloc=m...
[ "\n Return the :class:`~matplotlib.units.AxisInfo` for *unit*.\n\n *unit* is a tzinfo instance or None.\n The *axis* argument is required but not used.\n " ]
Please provide a description of the function:def get_locator(self, dmin, dmax): 'Pick the best locator based on a distance.' _check_implicitly_registered() delta = relativedelta(dmax, dmin) num_days = (delta.years * 12.0 + delta.months) * 31.0 + delta.days num_sec = (delta.hours...
[]
Please provide a description of the function:def autoscale(self): dmin, dmax = self.datalim_to_dt() if dmin > dmax: dmax, dmin = dmin, dmax # We need to cap at the endpoints of valid datetime # TODO(wesm): unused? # delta = relativedelta(dmax, dmin) ...
[ "\n Set the view limits to include the data range.\n " ]
Please provide a description of the function:def _get_default_locs(self, vmin, vmax): "Returns the default locations of ticks." if self.plot_obj.date_axis_info is None: self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq) locator = self.plot_obj.date_axis_info ...
[]
Please provide a description of the function:def autoscale(self): # requires matplotlib >= 0.98.0 (vmin, vmax) = self.axis.get_data_interval() locs = self._get_default_locs(vmin, vmax) (vmin, vmax) = locs[[0, -1]] if vmin == vmax: vmin -= 1 vmax ...
[ "\n Sets the view limits to the nearest multiples of base that contain the\n data.\n " ]
Please provide a description of the function:def _set_default_format(self, vmin, vmax): "Returns the default ticks spacing." if self.plot_obj.date_axis_info is None: self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq) info = self.plot_obj.date_axis_info if sel...
[]
Please provide a description of the function:def set_locs(self, locs): 'Sets the locations of the ticks' # don't actually use the locs. This is just needed to work with # matplotlib. Force to use vmin, vmax _check_implicitly_registered() self.locs = locs (vmin, vmax) = ...
[]
Please provide a description of the function:def set_default_names(data): if com._all_not_none(*data.index.names): nms = data.index.names if len(nms) == 1 and data.index.name == 'index': warnings.warn("Index name of 'index' is not round-trippable") elif len(nms) > 1 and any(...
[ "Sets index names to 'index' for regular, or 'level_x' for Multi" ]
Please provide a description of the function:def convert_json_field_to_pandas_type(field): typ = field['type'] if typ == 'string': return 'object' elif typ == 'integer': return 'int64' elif typ == 'number': return 'float64' elif typ == 'boolean': return 'bool' ...
[ "\n Converts a JSON field descriptor into its corresponding NumPy / pandas type\n\n Parameters\n ----------\n field\n A JSON field descriptor\n\n Returns\n -------\n dtype\n\n Raises\n -----\n ValueError\n If the type of the provided field is unknown or currently unsuppor...
Please provide a description of the function:def build_table_schema(data, index=True, primary_key=None, version=True): if index is True: data = set_default_names(data) schema = {} fields = [] if index: if data.index.nlevels > 1: for level in data.index.levels: ...
[ "\n Create a Table schema from ``data``.\n\n Parameters\n ----------\n data : Series, DataFrame\n index : bool, default True\n Whether to include ``data.index`` in the schema.\n primary_key : bool or None, default True\n column names to designate as the primary key.\n The defa...
Please provide a description of the function:def parse_table_schema(json, precise_float): table = loads(json, precise_float=precise_float) col_order = [field['name'] for field in table['schema']['fields']] df = DataFrame(table['data'], columns=col_order)[col_order] dtypes = {field['name']: convert...
[ "\n Builds a DataFrame from a given schema\n\n Parameters\n ----------\n json :\n A JSON table schema\n precise_float : boolean\n Flag controlling precision when decoding string to double values, as\n dictated by ``read_json``\n\n Returns\n -------\n df : DataFrame\n\n ...
Please provide a description of the function:def get_op_result_name(left, right): # `left` is always a pd.Series when called from within ops if isinstance(right, (ABCSeries, pd.Index)): name = _maybe_match_name(left, right) else: name = left.name return name
[ "\n Find the appropriate name to pin to an operation result. This result\n should always be either an Index or a Series.\n\n Parameters\n ----------\n left : {Series, Index}\n right : object\n\n Returns\n -------\n name : object\n Usually a string\n " ]
Please provide a description of the function:def _maybe_match_name(a, b): a_has = hasattr(a, 'name') b_has = hasattr(b, 'name') if a_has and b_has: if a.name == b.name: return a.name else: # TODO: what if they both have np.nan for their names? return ...
[ "\n Try to find a name to attach to the result of an operation between\n a and b. If only one of these has a `name` attribute, return that\n name. Otherwise return a consensus name if they match of None if\n they have different names.\n\n Parameters\n ----------\n a : object\n b : object\n...
Please provide a description of the function:def maybe_upcast_for_op(obj): if type(obj) is datetime.timedelta: # GH#22390 cast up to Timedelta to rely on Timedelta # implementation; otherwise operation against numeric-dtype # raises TypeError return pd.Timedelta(obj) elif i...
[ "\n Cast non-pandas objects to pandas types to unify behavior of arithmetic\n and comparison operations.\n\n Parameters\n ----------\n obj: object\n\n Returns\n -------\n out : object\n\n Notes\n -----\n Be careful to call this *after* determining the `name` attribute to be\n att...
Please provide a description of the function:def make_invalid_op(name): def invalid_op(self, other=None): raise TypeError("cannot perform {name} with this index type: " "{typ}".format(name=name, typ=type(self).__name__)) invalid_op.__name__ = name return invalid_op
[ "\n Return a binary method that always raises a TypeError.\n\n Parameters\n ----------\n name : str\n\n Returns\n -------\n invalid_op : function\n " ]
Please provide a description of the function:def _gen_eval_kwargs(name): kwargs = {} # Series and Panel appear to only pass __add__, __radd__, ... # but DataFrame gets both these dunder names _and_ non-dunder names # add, radd, ... name = name.replace('__', '') if name.startswith('r'): ...
[ "\n Find the keyword arguments to pass to numexpr for the given operation.\n\n Parameters\n ----------\n name : str\n\n Returns\n -------\n eval_kwargs : dict\n\n Examples\n --------\n >>> _gen_eval_kwargs(\"__add__\")\n {}\n\n >>> _gen_eval_kwargs(\"rtruediv\")\n {'reversed':...
Please provide a description of the function:def _gen_fill_zeros(name): name = name.strip('__') if 'div' in name: # truediv, floordiv, div, and reversed variants fill_value = np.inf elif 'mod' in name: # mod, rmod fill_value = np.nan else: fill_value = None ...
[ "\n Find the appropriate fill value to use when filling in undefined values\n in the results of the given operation caused by operating on\n (generally dividing by) zero.\n\n Parameters\n ----------\n name : str\n\n Returns\n -------\n fill_value : {None, np.nan, np.inf}\n " ]
Please provide a description of the function:def _get_opstr(op, cls): # numexpr is available for non-sparse classes subtyp = getattr(cls, '_subtyp', '') use_numexpr = 'sparse' not in subtyp if not use_numexpr: # if we're not using numexpr, then don't pass a str_rep return None ...
[ "\n Find the operation string, if any, to pass to numexpr for this\n operation.\n\n Parameters\n ----------\n op : binary operator\n cls : class\n\n Returns\n -------\n op_str : string or None\n " ]
Please provide a description of the function:def _get_op_name(op, special): opname = op.__name__.strip('_') if special: opname = '__{opname}__'.format(opname=opname) return opname
[ "\n Find the name to attach to this method according to conventions\n for special and non-special methods.\n\n Parameters\n ----------\n op : binary operator\n special : bool\n\n Returns\n -------\n op_name : str\n " ]
Please provide a description of the function:def _make_flex_doc(op_name, typ): op_name = op_name.replace('__', '') op_desc = _op_descriptions[op_name] if op_desc['reversed']: equiv = 'other ' + op_desc['op'] + ' ' + typ else: equiv = typ + ' ' + op_desc['op'] + ' other' if typ...
[ "\n Make the appropriate substitutions for the given operation and class-typ\n into either _flex_doc_SERIES or _flex_doc_FRAME to return the docstring\n to attach to a generated method.\n\n Parameters\n ----------\n op_name : str {'__add__', '__sub__', ... '__eq__', '__ne__', ...}\n typ : str {...
Please provide a description of the function:def fill_binop(left, right, fill_value): # TODO: can we make a no-copy implementation? if fill_value is not None: left_mask = isna(left) right_mask = isna(right) left = left.copy() right = right.copy() # one but not both ...
[ "\n If a non-None fill_value is given, replace null entries in left and right\n with this value, but only in positions where _one_ of left/right is null,\n not both.\n\n Parameters\n ----------\n left : array-like\n right : array-like\n fill_value : object\n\n Returns\n -------\n le...
Please provide a description of the function:def mask_cmp_op(x, y, op, allowed_types): # TODO: Can we make the allowed_types arg unnecessary? xrav = x.ravel() result = np.empty(x.size, dtype=bool) if isinstance(y, allowed_types): yrav = y.ravel() mask = notna(xrav) & notna(yrav) ...
[ "\n Apply the function `op` to only non-null points in x and y.\n\n Parameters\n ----------\n x : array-like\n y : array-like\n op : binary operation\n allowed_types : class or tuple of classes\n\n Returns\n -------\n result : ndarray[bool]\n " ]
Please provide a description of the function:def masked_arith_op(x, y, op): # For Series `x` is 1D so ravel() is a no-op; calling it anyway makes # the logic valid for both Series and DataFrame ops. xrav = x.ravel() assert isinstance(x, (np.ndarray, ABCSeries)), type(x) if isinstance(y, (np.nda...
[ "\n If the given arithmetic operation fails, attempt it again on\n only the non-null elements of the input array(s).\n\n Parameters\n ----------\n x : np.ndarray\n y : np.ndarray, Series, Index\n op : binary operator\n " ]
Please provide a description of the function:def invalid_comparison(left, right, op): if op is operator.eq: res_values = np.zeros(left.shape, dtype=bool) elif op is operator.ne: res_values = np.ones(left.shape, dtype=bool) else: raise TypeError("Invalid comparison between dtype=...
[ "\n If a comparison has mismatched types and is not necessarily meaningful,\n follow python3 conventions by:\n\n - returning all-False for equality\n - returning all-True for inequality\n - raising TypeError otherwise\n\n Parameters\n ----------\n left : array-like\n right : s...
Please provide a description of the function:def should_series_dispatch(left, right, op): if left._is_mixed_type or right._is_mixed_type: return True if not len(left.columns) or not len(right.columns): # ensure obj.dtypes[0] exists for each obj return False ldtype = left.dtype...
[ "\n Identify cases where a DataFrame operation should dispatch to its\n Series counterpart.\n\n Parameters\n ----------\n left : DataFrame\n right : DataFrame\n op : binary operator\n\n Returns\n -------\n override : bool\n " ]
Please provide a description of the function:def dispatch_to_series(left, right, func, str_rep=None, axis=None): # Note: we use iloc to access columns for compat with cases # with non-unique columns. import pandas.core.computation.expressions as expressions right = lib.item_from_zerodim(righ...
[ "\n Evaluate the frame operation func(left, right) by evaluating\n column-by-column, dispatching to the Series implementation.\n\n Parameters\n ----------\n left : DataFrame\n right : scalar or DataFrame\n func : arithmetic or comparison operator\n str_rep : str or None, default None\n ax...
Please provide a description of the function:def dispatch_to_index_op(op, left, right, index_class): left_idx = index_class(left) # avoid accidentally allowing integer add/sub. For datetime64[tz] dtypes, # left_idx may inherit a freq from a cached DatetimeIndex. # See discussion in GH#19147. ...
[ "\n Wrap Series left in the given index_class to delegate the operation op\n to the index implementation. DatetimeIndex and TimedeltaIndex perform\n type checking, timezone handling, overflow checks, etc.\n\n Parameters\n ----------\n op : binary operator (operator.add, operator.sub, ...)\n le...
Please provide a description of the function:def dispatch_to_extension_op(op, left, right): # The op calls will raise TypeError if the op is not defined # on the ExtensionArray # unbox Series and Index to arrays if isinstance(left, (ABCSeries, ABCIndexClass)): new_left = left._values ...
[ "\n Assume that left or right is a Series backed by an ExtensionArray,\n apply the operator defined by op.\n " ]
Please provide a description of the function:def _get_method_wrappers(cls): if issubclass(cls, ABCSparseSeries): # Be sure to catch this before ABCSeries and ABCSparseArray, # as they will both come see SparseSeries as a subclass arith_flex = _flex_method_SERIES comp_flex = _fle...
[ "\n Find the appropriate operation-wrappers to use when defining flex/special\n arithmetic, boolean, and comparison operations with the given class.\n\n Parameters\n ----------\n cls : class\n\n Returns\n -------\n arith_flex : function or None\n comp_flex : function or None\n arith_sp...
Please provide a description of the function:def add_special_arithmetic_methods(cls): _, _, arith_method, comp_method, bool_method = _get_method_wrappers(cls) new_methods = _create_methods(cls, arith_method, comp_method, bool_method, special=True) # inplace operators (...
[ "\n Adds the full suite of special arithmetic methods (``__add__``,\n ``__sub__``, etc.) to the class.\n\n Parameters\n ----------\n cls : class\n special methods will be defined and pinned to this class\n ", "\n return an inplace wrapper for this method\n " ]
Please provide a description of the function:def add_flex_arithmetic_methods(cls): flex_arith_method, flex_comp_method, _, _, _ = _get_method_wrappers(cls) new_methods = _create_methods(cls, flex_arith_method, flex_comp_method, bool_method=None, ...
[ "\n Adds the full suite of flex arithmetic methods (``pow``, ``mul``, ``add``)\n to the class.\n\n Parameters\n ----------\n cls : class\n flex methods will be defined and pinned to this class\n " ]
Please provide a description of the function:def _align_method_SERIES(left, right, align_asobject=False): # ToDo: Different from _align_method_FRAME, list, tuple and ndarray # are not coerced here # because Series has inconsistencies described in #13637 if isinstance(right, ABCSeries): # ...
[ " align lhs and rhs Series " ]
Please provide a description of the function:def _construct_result(left, result, index, name, dtype=None): out = left._constructor(result, index=index, dtype=dtype) out = out.__finalize__(left) out.name = name return out
[ "\n If the raw op result has a non-None name (e.g. it is an Index object) and\n the name argument is None, then passing name to the constructor will\n not be enough; we still need to override the name attribute.\n " ]
Please provide a description of the function:def _construct_divmod_result(left, result, index, name, dtype=None): return ( _construct_result(left, result[0], index=index, name=name, dtype=dtype), _construct_result(left, result[1], index=index, name=name, ...
[ "divmod returns a tuple of like indexed series instead of a single series.\n " ]