Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def maybe_infer_dtype_type(element): tipo = None if hasattr(element, 'dtype'): tipo = element.dtype elif is_list_like(element): element = np.asarray(element) tipo = element.dtype return tipo
[ "Try to infer an object's dtype, for use in arithmetic ops\n\n Uses `element.dtype` if that's available.\n Objects implementing the iterator protocol are cast to a NumPy array,\n and from there the array's type is used.\n\n Parameters\n ----------\n element : object\n Possibly has a `.dtype...
Please provide a description of the function:def maybe_upcast(values, fill_value=np.nan, dtype=None, copy=False): if is_extension_type(values): if copy: values = values.copy() else: if dtype is None: dtype = values.dtype new_dtype, fill_value = maybe_promote...
[ " provide explicit type promotion and coercion\n\n Parameters\n ----------\n values : the ndarray that we want to maybe upcast\n fill_value : what we want to fill with\n dtype : if None, then use the dtype of the values, else coerce to this type\n copy : if True always make a copy even if no upcas...
Please provide a description of the function:def invalidate_string_dtypes(dtype_set): non_string_dtypes = dtype_set - {np.dtype('S').type, np.dtype('<U').type} if non_string_dtypes != dtype_set: raise TypeError("string dtypes are not allowed, use 'object' instead")
[ "Change string like dtypes to object for\n ``DataFrame.select_dtypes()``.\n " ]
Please provide a description of the function:def coerce_indexer_dtype(indexer, categories): length = len(categories) if length < _int8_max: return ensure_int8(indexer) elif length < _int16_max: return ensure_int16(indexer) elif length < _int32_max: return ensure_int32(indexe...
[ " coerce the indexer input array to the smallest dtype possible " ]
Please provide a description of the function:def coerce_to_dtypes(result, dtypes): if len(result) != len(dtypes): raise AssertionError("_coerce_to_dtypes requires equal len arrays") def conv(r, dtype): try: if isna(r): pass elif dtype == _NS_DTYPE: ...
[ "\n given a dtypes and a result set, coerce the result elements to the\n dtypes\n " ]
Please provide a description of the function:def astype_nansafe(arr, dtype, copy=True, skipna=False): # dispatch on extension dtype if needed if is_extension_array_dtype(dtype): return dtype.construct_array_type()._from_sequence( arr, dtype=dtype, copy=copy) if not isinstance(dtyp...
[ "\n Cast the elements of an array to a given dtype a nan-safe manner.\n\n Parameters\n ----------\n arr : ndarray\n dtype : np.dtype\n copy : bool, default True\n If False, a view will be attempted but may fail, if\n e.g. the item sizes don't align.\n skipna: bool, default False\n...
Please provide a description of the function:def maybe_convert_objects(values, convert_dates=True, convert_numeric=True, convert_timedeltas=True, copy=True): # if we have passed in a list or scalar if isinstance(values, (list, tuple)): values = np.array(values, dtype=np.o...
[ " if we have an object dtype, try to coerce dates and/or numbers " ]
Please provide a description of the function:def soft_convert_objects(values, datetime=True, numeric=True, timedelta=True, coerce=False, copy=True): conversion_count = sum((datetime, numeric, timedelta)) if conversion_count == 0: raise ValueError('At least one of datetime,...
[ " if we have an object dtype, try to coerce dates and/or numbers " ]
Please provide a description of the function:def maybe_infer_to_datetimelike(value, convert_dates=False): # TODO: why not timedelta? if isinstance(value, (ABCDatetimeIndex, ABCPeriodIndex, ABCDatetimeArray, ABCPeriodArray)): return value elif isinstance(value, ABCSeri...
[ "\n we might have a array (or single object) that is datetime like,\n and no dtype is passed don't change the value unless we find a\n datetime/timedelta set\n\n this is pretty strict in that a datetime/timedelta is REQUIRED\n in addition to possible nulls/string likes\n\n Parameters\n --------...
Please provide a description of the function:def maybe_cast_to_datetime(value, dtype, errors='raise'): from pandas.core.tools.timedeltas import to_timedelta from pandas.core.tools.datetimes import to_datetime if dtype is not None: if isinstance(dtype, str): dtype = np.dtype(dtype) ...
[ " try to cast the array/value to a datetimelike dtype, converting float\n nan to iNaT\n " ]
Please provide a description of the function:def find_common_type(types): if len(types) == 0: raise ValueError('no types given') first = types[0] # workaround for find_common_type([np.dtype('datetime64[ns]')] * 2) # => object if all(is_dtype_equal(first, t) for t in types[1:]): ...
[ "\n Find a common data type among the given dtypes.\n\n Parameters\n ----------\n types : list of dtypes\n\n Returns\n -------\n pandas extension or numpy dtype\n\n See Also\n --------\n numpy.find_common_type\n\n " ]
Please provide a description of the function:def cast_scalar_to_array(shape, value, dtype=None): if dtype is None: dtype, fill_value = infer_dtype_from_scalar(value) else: fill_value = value values = np.empty(shape, dtype=dtype) values.fill(fill_value) return values
[ "\n create np.ndarray of specified shape and dtype, filled with values\n\n Parameters\n ----------\n shape : tuple\n value : scalar value\n dtype : np.dtype, optional\n dtype to coerce\n\n Returns\n -------\n ndarray of shape, filled with value, of specified / inferred dtype\n\n ...
Please provide a description of the function:def construct_1d_arraylike_from_scalar(value, length, dtype): if is_datetime64tz_dtype(dtype): from pandas import DatetimeIndex subarr = DatetimeIndex([value] * length, dtype=dtype) elif is_categorical_dtype(dtype): from pandas import Cat...
[ "\n create a np.ndarray / pandas type of specified shape and dtype\n filled with values\n\n Parameters\n ----------\n value : scalar value\n length : int\n dtype : pandas_dtype / np.dtype\n\n Returns\n -------\n np.ndarray / pandas type of length, filled with value\n\n " ]
Please provide a description of the function:def construct_1d_object_array_from_listlike(values): # numpy will try to interpret nested lists as further dimensions, hence # making a 1D array that contains list-likes is a bit tricky: result = np.empty(len(values), dtype='object') result[:] = values ...
[ "\n Transform any list-like object in a 1-dimensional numpy array of object\n dtype.\n\n Parameters\n ----------\n values : any iterable which has a len()\n\n Raises\n ------\n TypeError\n * If `values` does not have a len()\n\n Returns\n -------\n 1-dimensional numpy array o...
Please provide a description of the function:def construct_1d_ndarray_preserving_na(values, dtype=None, copy=False): subarr = np.array(values, dtype=dtype, copy=copy) if dtype is not None and dtype.kind in ("U", "S"): # GH-21083 # We can't just return np.array(subarr, dtype='str') since ...
[ "\n Construct a new ndarray, coercing `values` to `dtype`, preserving NA.\n\n Parameters\n ----------\n values : Sequence\n dtype : numpy.dtype, optional\n copy : bool, default False\n Note that copies may still be made with ``copy=False`` if casting\n is required.\n\n Returns\n ...
Please provide a description of the function:def maybe_cast_to_integer_array(arr, dtype, copy=False): try: if not hasattr(arr, "astype"): casted = np.array(arr, dtype=dtype, copy=copy) else: casted = arr.astype(dtype, copy=copy) except OverflowError: raise O...
[ "\n Takes any dtype and returns the casted version, raising for when data is\n incompatible with integer/unsigned integer dtypes.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n arr : array-like\n The array to cast.\n dtype : str, np.dtype\n The integer dtype to cast th...
Please provide a description of the function:def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs): import matplotlib.pyplot as plt kwargs.setdefault('edgecolors', 'none') def plot_group(group, ax): xvals = group[x].values yvals = group[y]...
[ "\n Make a scatter plot from two DataFrame columns\n\n Parameters\n ----------\n data : DataFrame\n x : Column name for the x-axis values\n y : Column name for the y-axis values\n ax : Matplotlib axis object\n figsize : A tuple (width, height) in inches\n grid : Setting this to True will ...
Please provide a description of the function:def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, **kwds): _raise_if_no_mpl() _converter._WARN = Fa...
[ "\n Make a histogram of the DataFrame's.\n\n A `histogram`_ is a representation of the distribution of data.\n This function calls :meth:`matplotlib.pyplot.hist`, on each series in\n the DataFrame, resulting in one histogram per column.\n\n .. _histogram: https://en.wikipedia.org/wiki/Histogram\n\n ...
Please provide a description of the function:def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, figsize=None, bins=10, **kwds): import matplotlib.pyplot as plt if by is None: if kwds.get('layout', None) is not ...
[ "\n Draw histogram of the input series using matplotlib.\n\n Parameters\n ----------\n by : object, optional\n If passed, then used to form histograms for separate groups\n ax : matplotlib axis object\n If not passed, uses gca()\n grid : bool, default True\n Whether to show ax...
Please provide a description of the function:def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None, layout=None, sharex=False, sharey=False, rot=90, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, **kwargs): _raise_if_n...
[ "\n Grouped histogram\n\n Parameters\n ----------\n data : Series/DataFrame\n column : object, optional\n by : object, optional\n ax : axes, optional\n bins : int, default 50\n figsize : tuple, optional\n layout : optional\n sharex : bool, default False\n sharey : bool, default F...
Please provide a description of the function:def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None, rot=0, grid=True, ax=None, figsize=None, layout=None, sharex=False, sharey=True, **kwds): _raise_if_no_mpl() _converter._WARN = Fals...
[ "\n Make box plots from DataFrameGroupBy data.\n\n Parameters\n ----------\n grouped : Grouped DataFrame\n subplots : bool\n * ``False`` - no subplots will be used\n * ``True`` - create a subplot for each group\n column : column name or list of names, or vector\n Can be any va...
Please provide a description of the function:def _has_plotted_object(self, ax): return (len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0)
[ "check whether ax has data" ]
Please provide a description of the function:def result(self): if self.subplots: if self.layout is not None and not is_list_like(self.ax): return self.axes.reshape(*self.layout) else: return self.axes else: sec_true = isinstanc...
[ "\n Return result axes\n " ]
Please provide a description of the function:def _post_plot_logic_common(self, ax, data): def get_label(i): try: return pprint_thing(data.index[i]) except Exception: return '' if self.orientation == 'vertical' or self.orientation is None...
[ "Common post process for each axes" ]
Please provide a description of the function:def _adorn_subplots(self): if len(self.axes) > 0: all_axes = self._get_subplots() nrows, ncols = self._get_axes_layout() _handle_shared_axes(axarr=all_axes, nplots=len(all_axes), naxes=nrows...
[ "Common post process unrelated to data" ]
Please provide a description of the function:def _apply_axis_properties(self, axis, rot=None, fontsize=None): if rot is not None or fontsize is not None: # rot=0 is a valid setting, hence the explicit None check labels = axis.get_majorticklabels() + axis.get_minorticklabels() ...
[ " Tick creation within matplotlib is reasonably expensive and is\n internally deferred until accessed as Ticks are created/destroyed\n multiple times per draw. It's therefore beneficial for us to avoid\n accessing unless we will act on the Tick.\n " ]
Please provide a description of the function:def _get_ax_layer(cls, ax, primary=True): if primary: return getattr(ax, 'left_ax', ax) else: return getattr(ax, 'right_ax', ax)
[ "get left (primary) or right (secondary) axes" ]
Please provide a description of the function:def _apply_style_colors(self, colors, kwds, col_num, label): style = None if self.style is not None: if isinstance(self.style, list): try: style = self.style[col_num] except IndexError: ...
[ "\n Manage style and color based on column number and its label.\n Returns tuple of appropriate style and kwds which \"color\" may be added.\n " ]
Please provide a description of the function:def _parse_errorbars(self, label, err): if err is None: return None def match_labels(data, e): e = e.reindex(data.index) return e # key-matched DataFrame if isinstance(err, ABCDataFrame): ...
[ "\n Look for error keyword arguments and return the actual errorbar data\n or return the error DataFrame/dict\n\n Error bars can be specified in several ways:\n Series: the user provides a pandas.Series object of the same\n length as the data\n ndarray: ...
Please provide a description of the function:def _make_plot_keywords(self, kwds, y): # y is required for KdePlot kwds['bottom'] = self.bottom kwds['bins'] = self.bins return kwds
[ "merge BoxPlot/KdePlot properties to passed kwds" ]
Please provide a description of the function:def line(self, x=None, y=None, **kwds): return self(kind='line', x=x, y=y, **kwds)
[ "\n Plot DataFrame columns as lines.\n\n This function is useful to plot lines using DataFrame's values\n as coordinates.\n\n Parameters\n ----------\n x : int or str, optional\n Columns to use for the horizontal axis.\n Either the location or the labe...
Please provide a description of the function:def bar(self, x=None, y=None, **kwds): return self(kind='bar', x=x, y=y, **kwds)
[ "\n Vertical bar plot.\n\n A bar plot is a plot that presents categorical data with\n rectangular bars with lengths proportional to the values that they\n represent. A bar plot shows comparisons among discrete categories. One\n axis of the plot shows the specific categories being ...
Please provide a description of the function:def barh(self, x=None, y=None, **kwds): return self(kind='barh', x=x, y=y, **kwds)
[ "\n Make a horizontal bar plot.\n\n A horizontal bar plot is a plot that presents quantitative data with\n rectangular bars with lengths proportional to the values that they\n represent. A bar plot shows comparisons among discrete categories. One\n axis of the plot shows the speci...
Please provide a description of the function:def hist(self, by=None, bins=10, **kwds): return self(kind='hist', by=by, bins=bins, **kwds)
[ "\n Draw one histogram of the DataFrame's columns.\n\n A histogram is a representation of the distribution of data.\n This function groups the values of all given Series in the DataFrame\n into bins and draws all bins in one :class:`matplotlib.axes.Axes`.\n This is useful when the...
Please provide a description of the function:def area(self, x=None, y=None, **kwds): return self(kind='area', x=x, y=y, **kwds)
[ "\n Draw a stacked area plot.\n\n An area plot displays quantitative data visually.\n This function wraps the matplotlib area function.\n\n Parameters\n ----------\n x : label or position, optional\n Coordinates for the X axis. By default uses the index.\n ...
Please provide a description of the function:def scatter(self, x, y, s=None, c=None, **kwds): return self(kind='scatter', x=x, y=y, c=c, s=s, **kwds)
[ "\n Create a scatter plot with varying marker point size and color.\n\n The coordinates of each point are defined by two dataframe columns and\n filled circles are used to represent each point. This kind of plot is\n useful to see complex correlations between two variables. Points could\...
Please provide a description of the function:def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwds): if reduce_C_function is not None: kwds['reduce_C_function'] = reduce_C_function if gridsize is not None: kwds['gridsize'] = gridsize...
[ "\n Generate a hexagonal binning plot.\n\n Generate a hexagonal binning plot of `x` versus `y`. If `C` is `None`\n (the default), this is a histogram of the number of occurrences\n of the observations at ``(x[i], y[i])``.\n\n If `C` is specified, specifies values at given coordina...
Please provide a description of the function:def _get_objs_combined_axis(objs, intersect=False, axis=0, sort=True): obs_idxes = [obj._get_axis(axis) for obj in objs if hasattr(obj, '_get_axis')] if obs_idxes: return _get_combined_index(obs_idxes, intersect=intersect, sort=sort)
[ "\n Extract combined index: return intersection or union (depending on the\n value of \"intersect\") of indexes on given axis, or None if all objects\n lack indexes (e.g. they are numpy arrays).\n\n Parameters\n ----------\n objs : list of objects\n Each object will only be considered if it...
Please provide a description of the function:def _get_distinct_objs(objs): ids = set() res = [] for obj in objs: if not id(obj) in ids: ids.add(id(obj)) res.append(obj) return res
[ "\n Return a list with distinct elements of \"objs\" (different ids).\n Preserves order.\n " ]
Please provide a description of the function:def _get_combined_index(indexes, intersect=False, sort=False): # TODO: handle index names! indexes = _get_distinct_objs(indexes) if len(indexes) == 0: index = Index([]) elif len(indexes) == 1: index = indexes[0] elif intersect: ...
[ "\n Return the union or intersection of indexes.\n\n Parameters\n ----------\n indexes : list of Index or list objects\n When intersect=True, do not accept list of lists.\n intersect : bool, default False\n If True, calculate the intersection between indexes. Otherwise,\n calcula...
Please provide a description of the function:def _union_indexes(indexes, sort=True): if len(indexes) == 0: raise AssertionError('Must have at least 1 Index to union') if len(indexes) == 1: result = indexes[0] if isinstance(result, list): result = Index(sorted(result)) ...
[ "\n Return the union of indexes.\n\n The behavior of sort and names is not consistent.\n\n Parameters\n ----------\n indexes : list of Index or list objects\n sort : bool, default True\n Whether the result index should come out sorted or not.\n\n Returns\n -------\n Index\n ", ...
Please provide a description of the function:def _sanitize_and_check(indexes): kinds = list({type(index) for index in indexes}) if list in kinds: if len(kinds) > 1: indexes = [Index(com.try_sort(x)) if not isinstance(x, Index) else x for x ...
[ "\n Verify the type of indexes and convert lists to Index.\n\n Cases:\n\n - [list, list, ...]: Return ([list, list, ...], 'list')\n - [list, Index, ...]: Return _sanitize_and_check([Index, Index, ...])\n Lists are sorted and converted to Index.\n - [Index, Index, ...]: Return ([Index, Index, ....
Please provide a description of the function:def _get_consensus_names(indexes): # find the non-none names, need to tupleify to make # the set hashable, then reverse on return consensus_names = {tuple(i.names) for i in indexes if com._any_not_none(*i.names)} if len(consensus_...
[ "\n Give a consensus 'names' to indexes.\n\n If there's exactly one non-empty 'names', return this,\n otherwise, return empty.\n\n Parameters\n ----------\n indexes : list of Index objects\n\n Returns\n -------\n list\n A list representing the consensus 'names' found.\n " ]
Please provide a description of the function:def _all_indexes_same(indexes): first = indexes[0] for index in indexes[1:]: if not first.equals(index): return False return True
[ "\n Determine if all indexes contain the same elements.\n\n Parameters\n ----------\n indexes : list of Index objects\n\n Returns\n -------\n bool\n True if all indexes contain the same elements, False otherwise.\n " ]
Please provide a description of the function:def _convert_params(sql, params): args = [sql] if params is not None: if hasattr(params, 'keys'): # test if params is a mapping args += [params] else: args += [list(params)] return args
[ "Convert SQL and params args to DBAPI2.0 compliant format." ]
Please provide a description of the function:def _process_parse_dates_argument(parse_dates): # handle non-list entries for parse_dates gracefully if parse_dates is True or parse_dates is None or parse_dates is False: parse_dates = [] elif not hasattr(parse_dates, '__iter__'): parse_dat...
[ "Process parse_dates argument for read_sql functions" ]
Please provide a description of the function:def _parse_date_columns(data_frame, parse_dates): parse_dates = _process_parse_dates_argument(parse_dates) # we want to coerce datetime64_tz dtypes for now to UTC # we could in theory do a 'nice' conversion from a FixedOffset tz # GH11216 for col_na...
[ "\n Force non-datetime columns to be read as such.\n Supports both string formatted and integer timestamp columns.\n " ]
Please provide a description of the function:def _wrap_result(data, columns, index_col=None, coerce_float=True, parse_dates=None): frame = DataFrame.from_records(data, columns=columns, coerce_float=coerce_float) frame = _parse_date_columns(frame, parse_...
[ "Wrap result set of query in a DataFrame." ]
Please provide a description of the function:def execute(sql, con, cur=None, params=None): if cur is None: pandas_sql = pandasSQL_builder(con) else: pandas_sql = pandasSQL_builder(cur, is_cursor=True) args = _convert_params(sql, params) return pandas_sql.execute(*args)
[ "\n Execute the given SQL query using the provided connection object.\n\n Parameters\n ----------\n sql : string\n SQL query to be executed.\n con : SQLAlchemy connectable(engine/connection) or sqlite3 connection\n Using SQLAlchemy makes it possible to use any DB supported by the\n ...
Please provide a description of the function:def read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None): con = _engine_builder(con) if not _is_sqlalchemy_connectable(con): raise NotImplem...
[ "\n Read SQL database table into a DataFrame.\n\n Given a table name and a SQLAlchemy connectable, returns a DataFrame.\n This function does not support DBAPI connections.\n\n Parameters\n ----------\n table_name : str\n Name of SQL table in database.\n con : SQLAlchemy connectable or st...
Please provide a description of the function:def read_sql_query(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None): pandas_sql = pandasSQL_builder(con) return pandas_sql.read_query( sql, index_col=index_col, params=params, coerce_float=coe...
[ "Read SQL query into a DataFrame.\n\n Returns a DataFrame corresponding to the result set of the query\n string. Optionally provide an `index_col` parameter to use one of the\n columns as the index, otherwise default integer index will be used.\n\n Parameters\n ----------\n sql : string SQL query ...
Please provide a description of the function:def read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None): pandas_sql = pandasSQL_builder(con) if isinstance(pandas_sql, SQLiteDatabase): return pandas_sql.read_query( ...
[ "\n Read SQL query or database table into a DataFrame.\n\n This function is a convenience wrapper around ``read_sql_table`` and\n ``read_sql_query`` (for backward compatibility). It will delegate\n to the specific function depending on the provided input. A SQL query\n will be routed to ``read_sql_qu...
Please provide a description of the function:def to_sql(frame, name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None): if if_exists not in ('fail', 'replace', 'append'): raise ValueError("'{0}' is not valid for if_exists".format(if_ex...
[ "\n Write records stored in a DataFrame to a SQL database.\n\n Parameters\n ----------\n frame : DataFrame, Series\n name : string\n Name of SQL table.\n con : SQLAlchemy connectable(engine/connection) or database string URI\n or sqlite3 DBAPI2 connection\n Using SQLAlchemy ma...
Please provide a description of the function:def has_table(table_name, con, schema=None): pandas_sql = pandasSQL_builder(con, schema=schema) return pandas_sql.has_table(table_name)
[ "\n Check if DataBase has named table.\n\n Parameters\n ----------\n table_name: string\n Name of SQL table.\n con: SQLAlchemy connectable(engine/connection) or sqlite3 DBAPI2 connection\n Using SQLAlchemy makes it possible to use any DB supported by that\n library.\n If a...
Please provide a description of the function:def _engine_builder(con): global _SQLALCHEMY_INSTALLED if isinstance(con, str): try: import sqlalchemy except ImportError: _SQLALCHEMY_INSTALLED = False else: con = sqlalchemy.create_engine(con) ...
[ "\n Returns a SQLAlchemy engine from a URI (if con is a string)\n else it just return con without modifying it.\n " ]
Please provide a description of the function:def pandasSQL_builder(con, schema=None, meta=None, is_cursor=False): # When support for DBAPI connections is removed, # is_cursor should not be necessary. con = _engine_builder(con) if _is_sqlalchemy_connectable(con): return...
[ "\n Convenience function to return the correct PandasSQL subclass based on the\n provided parameters.\n " ]
Please provide a description of the function:def get_schema(frame, name, keys=None, con=None, dtype=None): pandas_sql = pandasSQL_builder(con=con) return pandas_sql._create_sql_schema(frame, name, keys=keys, dtype=dtype)
[ "\n Get the SQL db table schema for the given frame.\n\n Parameters\n ----------\n frame : DataFrame\n name : string\n name of SQL table\n keys : string or sequence, default: None\n columns to use a primary key\n con: an open SQL database connection object or a SQLAlchemy connecta...
Please provide a description of the function:def _execute_insert(self, conn, keys, data_iter): data = [dict(zip(keys, row)) for row in data_iter] conn.execute(self.table.insert(), data)
[ "Execute SQL statement inserting data\n\n Parameters\n ----------\n conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection\n keys : list of str\n Column names\n data_iter : generator of list\n Each item contains a list of values to be inserted\n ...
Please provide a description of the function:def _query_iterator(self, result, chunksize, columns, coerce_float=True, parse_dates=None): while True: data = result.fetchmany(chunksize) if not data: break else: s...
[ "Return generator through chunked result set." ]
Please provide a description of the function:def _harmonize_columns(self, parse_dates=None): parse_dates = _process_parse_dates_argument(parse_dates) for sql_col in self.table.columns: col_name = sql_col.name try: df_col = self.frame[col_name] ...
[ "\n Make the DataFrame's column types align with the SQL table\n column types.\n Need to work around limited NA value support. Floats are always\n fine, ints must always be floats if there are Null values.\n Booleans are hard because converting bool column with None replaces\n ...
Please provide a description of the function:def read_table(self, table_name, index_col=None, coerce_float=True, parse_dates=None, columns=None, schema=None, chunksize=None): table = SQLTable(table_name, self, index=index_col, schema=schema) return table.re...
[ "Read SQL database table into a DataFrame.\n\n Parameters\n ----------\n table_name : string\n Name of SQL table in database.\n index_col : string, optional, default: None\n Column to set as index.\n coerce_float : boolean, default True\n Attempts ...
Please provide a description of the function:def _query_iterator(result, chunksize, columns, index_col=None, coerce_float=True, parse_dates=None): while True: data = result.fetchmany(chunksize) if not data: break else: ...
[ "Return generator through chunked result set" ]
Please provide a description of the function:def read_query(self, sql, index_col=None, coerce_float=True, parse_dates=None, params=None, chunksize=None): args = _convert_params(sql, params) result = self.execute(*args) columns = result.keys() if chunksize is...
[ "Read SQL query into a DataFrame.\n\n Parameters\n ----------\n sql : string\n SQL query to be executed.\n index_col : string, optional, default: None\n Column name to use as index for the returned DataFrame object.\n coerce_float : boolean, default True\n ...
Please provide a description of the function:def to_sql(self, frame, name, if_exists='fail', index=True, index_label=None, schema=None, chunksize=None, dtype=None, method=None): if dtype and not is_dict_like(dtype): dtype = {col_name: dtype for col_name in fram...
[ "\n Write records stored in a DataFrame to a SQL database.\n\n Parameters\n ----------\n frame : DataFrame\n name : string\n Name of SQL table.\n if_exists : {'fail', 'replace', 'append'}, default 'fail'\n - fail: If table exists, do nothing.\n ...
Please provide a description of the function:def _create_table_setup(self): column_names_and_types = self._get_column_names_and_types( self._sql_type_name ) pat = re.compile(r'\s+') column_names = [col_name for col_name, _, _ in column_names_and_types] if an...
[ "\n Return a list of SQL statements that creates a table reflecting the\n structure of a DataFrame. The first entry will be a CREATE TABLE\n statement while the rest will be CREATE INDEX statements.\n " ]
Please provide a description of the function:def _query_iterator(cursor, chunksize, columns, index_col=None, coerce_float=True, parse_dates=None): while True: data = cursor.fetchmany(chunksize) if type(data) == tuple: data = list(data) ...
[ "Return generator through chunked result set" ]
Please provide a description of the function:def to_sql(self, frame, name, if_exists='fail', index=True, index_label=None, schema=None, chunksize=None, dtype=None, method=None): if dtype and not is_dict_like(dtype): dtype = {col_name: dtype for col_name in fram...
[ "\n Write records stored in a DataFrame to a SQL database.\n\n Parameters\n ----------\n frame: DataFrame\n name: string\n Name of SQL table.\n if_exists: {'fail', 'replace', 'append'}, default 'fail'\n fail: If table exists, do nothing.\n r...
Please provide a description of the function:def _maybe_to_categorical(array): if isinstance(array, (ABCSeries, ABCCategoricalIndex)): return array._values elif isinstance(array, np.ndarray): return Categorical(array) return array
[ "\n Coerce to a categorical if a series is given.\n\n Internal use ONLY.\n " ]
Please provide a description of the function:def contains(cat, key, container): hash(key) # get location of key in categories. # If a KeyError, the key isn't in categories, so logically # can't be in container either. try: loc = cat.categories.get_loc(key) except KeyError: ...
[ "\n Helper for membership check for ``key`` in ``cat``.\n\n This is a helper method for :method:`__contains__`\n and :class:`CategoricalIndex.__contains__`.\n\n Returns True if ``key`` is in ``cat.categories`` and the\n location of ``key`` in ``categories`` is in ``container``.\n\n Parameters\n ...
Please provide a description of the function:def _get_codes_for_values(values, categories): from pandas.core.algorithms import _get_data_algo, _hashtables dtype_equal = is_dtype_equal(values.dtype, categories.dtype) if dtype_equal: # To prevent erroneous dtype coercion in _get_data_algo, retri...
[ "\n utility routine to turn values into codes given the specified categories\n " ]
Please provide a description of the function:def _recode_for_categories(codes, old_categories, new_categories): from pandas.core.algorithms import take_1d if len(old_categories) == 0: # All null anyway, so just retain the nulls return codes.copy() elif new_categories.equals(old_categor...
[ "\n Convert a set of codes for to a new set of categories\n\n Parameters\n ----------\n codes : array\n old_categories, new_categories : Index\n\n Returns\n -------\n new_codes : array\n\n Examples\n --------\n >>> old_cat = pd.Index(['b', 'a', 'c'])\n >>> new_cat = pd.Index(['a'...
Please provide a description of the function:def _factorize_from_iterable(values): from pandas.core.indexes.category import CategoricalIndex if not is_list_like(values): raise TypeError("Input must be list-like") if is_categorical(values): if isinstance(values, (ABCCategoricalIndex, A...
[ "\n Factorize an input `values` into `categories` and `codes`. Preserves\n categorical dtype in `categories`.\n\n *This is an internal function*\n\n Parameters\n ----------\n values : list-like\n\n Returns\n -------\n codes : ndarray\n categories : Index\n If `values` has a cate...
Please provide a description of the function:def _factorize_from_iterables(iterables): if len(iterables) == 0: # For consistency, it should return a list of 2 lists. return [[], []] return map(list, lzip(*[_factorize_from_iterable(it) for it in iterables]))
[ "\n A higher-level wrapper over `_factorize_from_iterable`.\n\n *This is an internal function*\n\n Parameters\n ----------\n iterables : list-like of list-likes\n\n Returns\n -------\n codes_list : list of ndarrays\n categories_list : list of Indexes\n\n Notes\n -----\n See `_fac...
Please provide a description of the function:def copy(self): return self._constructor(values=self._codes.copy(), dtype=self.dtype, fastpath=True)
[ "\n Copy constructor.\n " ]
Please provide a description of the function:def astype(self, dtype, copy=True): if is_categorical_dtype(dtype): # GH 10696/18593 dtype = self.dtype.update_dtype(dtype) self = self.copy() if copy else self if dtype == self.dtype: return se...
[ "\n Coerce this type to another dtype\n\n Parameters\n ----------\n dtype : numpy dtype or pandas type\n copy : bool, default True\n By default, astype always returns a newly allocated object.\n If copy is set to False and dtype is categorical, the original\n...
Please provide a description of the function:def _from_inferred_categories(cls, inferred_categories, inferred_codes, dtype, true_values=None): from pandas import Index, to_numeric, to_datetime, to_timedelta cats = Index(inferred_categories) known_categ...
[ "\n Construct a Categorical from inferred values.\n\n For inferred categories (`dtype` is None) the categories are sorted.\n For explicit `dtype`, the `inferred_categories` are cast to the\n appropriate type.\n\n Parameters\n ----------\n inferred_categories : Index\...
Please provide a description of the function:def from_codes(cls, codes, categories=None, ordered=None, dtype=None): dtype = CategoricalDtype._from_values_or_dtype(categories=categories, ordered=ordered, ...
[ "\n Make a Categorical type from codes and categories or dtype.\n\n This constructor is useful if you already have codes and\n categories/dtype and so do not need the (computation intensive)\n factorization step, which is usually done on the constructor.\n\n If your data does not ...
Please provide a description of the function:def _get_codes(self): v = self._codes.view() v.flags.writeable = False return v
[ "\n Get the codes.\n\n Returns\n -------\n codes : integer array view\n A non writable view of the `codes` array.\n " ]
Please provide a description of the function:def _set_categories(self, categories, fastpath=False): if fastpath: new_dtype = CategoricalDtype._from_fastpath(categories, self.ordered) else: new_dtype = CategoricalDt...
[ "\n Sets new categories inplace\n\n Parameters\n ----------\n fastpath : bool, default False\n Don't perform validation of the categories for uniqueness or nulls\n\n Examples\n --------\n >>> c = pd.Categorical(['a', 'b'])\n >>> c\n [a, b]\n ...
Please provide a description of the function:def _set_dtype(self, dtype): codes = _recode_for_categories(self.codes, self.categories, dtype.categories) return type(self)(codes, dtype=dtype, fastpath=True)
[ "\n Internal method for directly updating the CategoricalDtype\n\n Parameters\n ----------\n dtype : CategoricalDtype\n\n Notes\n -----\n We don't do any validation here. It's assumed that the dtype is\n a (valid) instance of `CategoricalDtype`.\n " ]
Please provide a description of the function:def set_ordered(self, value, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') new_dtype = CategoricalDtype(self.categories, ordered=value) cat = self if inplace else self.copy() cat._dtype = new_dtype if not i...
[ "\n Set the ordered attribute to the boolean value.\n\n Parameters\n ----------\n value : bool\n Set whether this categorical is ordered (True) or not (False).\n inplace : bool, default False\n Whether or not to set the ordered attribute in-place or return\n ...
Please provide a description of the function:def as_ordered(self, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') return self.set_ordered(True, inplace=inplace)
[ "\n Set the Categorical to be ordered.\n\n Parameters\n ----------\n inplace : bool, default False\n Whether or not to set the ordered attribute in-place or return\n a copy of this categorical with ordered set to True.\n " ]
Please provide a description of the function:def as_unordered(self, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') return self.set_ordered(False, inplace=inplace)
[ "\n Set the Categorical to be unordered.\n\n Parameters\n ----------\n inplace : bool, default False\n Whether or not to set the ordered attribute in-place or return\n a copy of this categorical with ordered set to False.\n " ]
Please provide a description of the function:def set_categories(self, new_categories, ordered=None, rename=False, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') if ordered is None: ordered = self.dtype.ordered new_dtype = Categorical...
[ "\n Set the categories to the specified new_categories.\n\n `new_categories` can include new categories (which will result in\n unused categories) or remove old categories (which results in values\n set to NaN). If `rename==True`, the categories will simple be renamed\n (less or m...
Please provide a description of the function:def rename_categories(self, new_categories, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') cat = self if inplace else self.copy() if isinstance(new_categories, ABCSeries): msg = ("Treating Series 'new_categorie...
[ "\n Rename categories.\n\n Parameters\n ----------\n new_categories : list-like, dict-like or callable\n\n * list-like: all items must be unique and the number of items in\n the new categories must match the existing number of categories.\n\n * dict-like: ...
Please provide a description of the function:def reorder_categories(self, new_categories, ordered=None, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') if set(self.dtype.categories) != set(new_categories): raise ValueError("items in new_categories are not the same ...
[ "\n Reorder categories as specified in new_categories.\n\n `new_categories` need to include all old categories and no new category\n items.\n\n Parameters\n ----------\n new_categories : Index-like\n The categories in new order.\n ordered : bool, optional\n...
Please provide a description of the function:def add_categories(self, new_categories, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') if not is_list_like(new_categories): new_categories = [new_categories] already_included = set(new_categories) & set(self.dt...
[ "\n Add new categories.\n\n `new_categories` will be included at the last/highest place in the\n categories and will be unused directly after this call.\n\n Parameters\n ----------\n new_categories : category or list-like of category\n The new categories to be inc...
Please provide a description of the function:def remove_categories(self, removals, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') if not is_list_like(removals): removals = [removals] removal_set = set(list(removals)) not_included = removal_set - s...
[ "\n Remove the specified categories.\n\n `removals` must be included in the old categories. Values which were in\n the removed categories will be set to NaN\n\n Parameters\n ----------\n removals : category or list of categories\n The categories which should be re...
Please provide a description of the function:def remove_unused_categories(self, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') cat = self if inplace else self.copy() idx, inv = np.unique(cat._codes, return_inverse=True) if idx.size != 0 and idx[0] == -1: # n...
[ "\n Remove categories which are not used.\n\n Parameters\n ----------\n inplace : bool, default False\n Whether or not to drop unused categories inplace or return a copy of\n this categorical with unused categories dropped.\n\n Returns\n -------\n ...
Please provide a description of the function:def map(self, mapper): new_categories = self.categories.map(mapper) try: return self.from_codes(self._codes.copy(), categories=new_categories, ordered=self.ordered) ...
[ "\n Map categories using input correspondence (dict, Series, or function).\n\n Maps the categories to new categories. If the mapping correspondence is\n one-to-one the result is a :class:`~pandas.Categorical` which has the\n same order property as the original, otherwise a :class:`~panda...
Please provide a description of the function:def shift(self, periods, fill_value=None): # since categoricals always have ndim == 1, an axis parameter # doesn't make any sense here. codes = self.codes if codes.ndim > 1: raise NotImplementedError("Categorical with ndim...
[ "\n Shift Categorical by desired number of periods.\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n fill_value : object, optional\n The scalar value to use for newly introduced missing values.\n\n ...
Please provide a description of the function:def memory_usage(self, deep=False): return self._codes.nbytes + self.dtype.categories.memory_usage( deep=deep)
[ "\n Memory usage of my values\n\n Parameters\n ----------\n deep : bool\n Introspect the data deeply, interrogate\n `object` dtypes for system-level memory consumption\n\n Returns\n -------\n bytes used\n\n Notes\n -----\n M...
Please provide a description of the function:def value_counts(self, dropna=True): from numpy import bincount from pandas import Series, CategoricalIndex code, cat = self._codes, self.categories ncat, mask = len(cat), 0 <= code ix, clean = np.arange(ncat), mask.all() ...
[ "\n Return a Series containing counts of each category.\n\n Every category will have an entry, even those with a count of 0.\n\n Parameters\n ----------\n dropna : bool, default True\n Don't include counts of NaN.\n\n Returns\n -------\n counts : Se...
Please provide a description of the function:def get_values(self): # if we are a datetime and period index, return Index to keep metadata if is_datetimelike(self.categories): return self.categories.take(self._codes, fill_value=np.nan) elif is_integer_dtype(self.categories) a...
[ "\n Return the values.\n\n For internal compatibility with pandas formatting.\n\n Returns\n -------\n numpy.array\n A numpy array of the same dtype as categorical.categories.dtype or\n Index if datetime / periods.\n " ]
Please provide a description of the function:def sort_values(self, inplace=False, ascending=True, na_position='last'): inplace = validate_bool_kwarg(inplace, 'inplace') if na_position not in ['last', 'first']: msg = 'invalid na_position: {na_position!r}' raise ValueError...
[ "\n Sort the Categorical by category value returning a new\n Categorical by default.\n\n While an ordering is applied to the category values, sorting in this\n context refers more to organizing and grouping together based on\n matching category values. Thus, this function can be c...
Please provide a description of the function:def _values_for_rank(self): from pandas import Series if self.ordered: values = self.codes mask = values == -1 if mask.any(): values = values.astype('float64') values[mask] = np.nan ...
[ "\n For correctly ranking ordered categorical data. See GH#15420\n\n Ordered categorical data should be ranked on the basis of\n codes with -1 translated to NaN.\n\n Returns\n -------\n numpy.array\n\n " ]
Please provide a description of the function:def fillna(self, value=None, method=None, limit=None): value, method = validate_fillna_kwargs( value, method, validate_scalar_dict_value=False ) if value is None: value = np.nan if limit is not None: ...
[ "\n Fill NA/NaN values using the specified method.\n\n Parameters\n ----------\n value : scalar, dict, Series\n If a scalar value is passed it is used to fill all missing values.\n Alternatively, a Series or dict can be used to fill in different\n values ...
Please provide a description of the function:def take_nd(self, indexer, allow_fill=None, fill_value=None): indexer = np.asarray(indexer, dtype=np.intp) if allow_fill is None: if (indexer < 0).any(): warn(_take_msg, FutureWarning, stacklevel=2) allow_f...
[ "\n Take elements from the Categorical.\n\n Parameters\n ----------\n indexer : sequence of int\n The indices in `self` to take. The meaning of negative values in\n `indexer` depends on the value of `allow_fill`.\n allow_fill : bool, default None\n ...
Please provide a description of the function:def _slice(self, slicer): # only allow 1 dimensional slicing, but can # in a 2-d case be passd (slice(None),....) if isinstance(slicer, tuple) and len(slicer) == 2: if not com.is_null_slice(slicer[0]): raise Asser...
[ "\n Return a slice of myself.\n\n For internal compatibility with numpy arrays.\n " ]
Please provide a description of the function:def _tidy_repr(self, max_vals=10, footer=True): num = max_vals // 2 head = self[:num]._get_repr(length=False, footer=False) tail = self[-(max_vals - num):]._get_repr(length=False, footer=False) result = '{head}, ..., {tail}'.format(h...
[ " a short repr displaying only max_vals and an optional (but default\n footer)\n " ]