text
stringlengths
81
112k
Convert data to array of timestamps. Parameters ---------- data : np.ndarray[object] dayfirst : bool yearfirst : bool utc : bool, default False Whether to convert timezone-aware timestamps to UTC errors : {'raise', 'ignore', 'coerce'} allow_object : bool Whether to retur...
Convert data based on dtype conventions, issuing deprecation warnings or errors where appropriate. Parameters ---------- data : np.ndarray or pd.Index copy : bool Returns ------- data : np.ndarray or pd.Index copy : bool Raises ------ TypeError : PeriodDType data is pa...
If a timezone is inferred from data, check that it is compatible with the user-provided timezone, if any. Parameters ---------- tz : tzinfo or None inferred_tz : tzinfo or None Returns ------- tz : tzinfo or None Raises ------ TypeError : if both timezones are present but ...
Check that a dtype, if passed, represents either a numpy datetime64[ns] dtype or a pandas DatetimeTZDtype. Parameters ---------- dtype : object Returns ------- dtype : None, numpy.dtype, or DatetimeTZDtype Raises ------ ValueError : invalid dtype Notes ----- Unlik...
If the given dtype is a DatetimeTZDtype, extract the implied tzinfo object from it and check that it does not conflict with the given tz. Parameters ---------- dtype : dtype, str tz : None, tzinfo Returns ------- tz : consensus tzinfo Raises ------ ValueError : on tzin...
If a timezone is not explicitly given via `tz`, see if one can be inferred from the `start` and `end` endpoints. If more than one of these inputs provides a timezone, require that they all agree. Parameters ---------- start : Timestamp end : Timestamp tz : tzinfo or None Returns -...
Localize a start or end Timestamp to the timezone of the corresponding start or end Timestamp Parameters ---------- ts : start or end Timestamp to potentially localize is_none : argument that should be None is_not_none : argument that should not be None freq : Tick, DateOffset, or None ...
subtract DatetimeArray/Index or ndarray[datetime64] def _sub_datetime_arraylike(self, other): """subtract DatetimeArray/Index or ndarray[datetime64]""" if len(self) != len(other): raise ValueError("cannot add indices of unequal length") if isinstance(other, np.ndarray): ...
Add a timedelta-like, Tick, or TimedeltaIndex-like object to self, yielding a new DatetimeArray Parameters ---------- other : {timedelta, np.timedelta64, Tick, TimedeltaIndex, ndarray[timedelta64]} Returns ------- result : DatetimeArray def _ad...
Convert tz-aware Datetime Array/Index from one time zone to another. Parameters ---------- tz : str, pytz.timezone, dateutil.tz.tzfile or None Time zone for time. Corresponding timestamps would be converted to this time zone of the Datetime Array/Index. A `tz` of None wi...
Localize tz-naive Datetime Array/Index to tz-aware Datetime Array/Index. This method takes a time zone (tz) naive Datetime Array/Index object and makes this time zone aware. It does not move the time to another time zone. Time zone localization helps to switch from time zone awa...
Convert times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected. This method is available on Series with datetime values under the ``...
Cast to PeriodArray/Index at a particular frequency. Converts DatetimeArray/Index to PeriodArray/Index. Parameters ---------- freq : str or Offset, optional One of pandas' :ref:`offset strings <timeseries.offset_aliases>` or an Offset object. Will be inferred by...
Calculate TimedeltaArray of difference between index values and index converted to PeriodArray at specified freq. Used for vectorized offsets Parameters ---------- freq : Period frequency Returns ------- TimedeltaArray/Index def to_perioddelta(self, fre...
Return the month names of the DateTimeIndex with specified locale. .. versionadded:: 0.23.0 Parameters ---------- locale : str, optional Locale determining the language in which to return the month name. Default is English locale. Returns ------...
Returns numpy array of datetime.time. The time part of the Timestamps. def time(self): """ Returns numpy array of datetime.time. The time part of the Timestamps. """ # If the Timestamps have a timezone that is not UTC, # convert them into their i8 representation while # ...
Convert Datetime Array to float64 ndarray of Julian Dates. 0 Julian date is noon January 1, 4713 BC. http://en.wikipedia.org/wiki/Julian_day def to_julian_date(self): """ Convert Datetime Array to float64 ndarray of Julian Dates. 0 Julian date is noon January 1, 4713 BC. ...
Yield information about all public API items. Parse api.rst file from the documentation, and extract all the functions, methods, classes, attributes... This should include all pandas public API. Parameters ---------- api_doc_fd : file descriptor A file descriptor of the API documentation p...
Validate the docstring. Parameters ---------- doc : Docstring A Docstring object with the given function name. Returns ------- tuple errors : list of tuple Errors occurred during validation. warnings : list of tuple Warnings occurred during valid...
Validate the docstring for the given func_name Parameters ---------- func_name : function Function whose docstring will be evaluated (e.g. pandas.read_csv). Returns ------- dict A dictionary containing all the information obtained from validating the docstring. def val...
Execute the validation of all docstrings, and return a dict with the results. Parameters ---------- prefix : str or None If provided, only the docstrings that start with this pattern will be validated. If None, all docstrings will be validated. ignore_deprecated: bool, default False...
Import Python object from its name as string. Parameters ---------- name : str Object name to import (e.g. pandas.Series.str.upper) Returns ------- object Python object that can be a class, method, function... Examples -------- ...
Find the Python object that contains the source code of the object. This is useful to find the place in the source code (file and line number) where a docstring is defined. It does not currently work for all cases, but it should help find some (properties...). def _to_original_callable(obj): ...
File name where the object is implemented (e.g. pandas/core/frame.py). def source_file_name(self): """ File name where the object is implemented (e.g. pandas/core/frame.py). """ try: fname = inspect.getsourcefile(self.code_obj) except TypeError: # In some...
Check if the docstrings method can return something. Bare returns, returns valued None and returns from nested functions are disconsidered. Returns ------- bool Whether the docstrings method can return something. def method_returns_something(self): ''' ...
Convert numpy types to Python types for the Excel writers. Parameters ---------- val : object Value to be written into cells Returns ------- Tuple with the first element being the converted value and the second being an optional format def _valu...
checks that path's extension against the Writer's supported extensions. If it isn't supported, raises UnsupportedFiletypeError. def check_extension(cls, ext): """checks that path's extension against the Writer's supported extensions. If it isn't supported, raises UnsupportedFiletypeError.""" ...
Parse specified sheet(s) into a DataFrame Equivalent to read_excel(ExcelFile, ...) See the read_excel docstring for more info on accepted parameters def parse(self, sheet_name=0, header=0, names=None, index_col=None, usecols=None, ...
Validate that the where statement is of the right type. The type may either be String, Expr, or list-like of Exprs. Parameters ---------- w : String term expression, Expr, or list-like of Exprs. Returns ------- where : The original where clause if the check was successful. Raises ...
loose checking if s is a pytables-acceptable expression def maybe_expression(s): """ loose checking if s is a pytables-acceptable expression """ if not isinstance(s, str): return False ops = ExprVisitor.binary_ops + ExprVisitor.unary_ops + ('=',) # make sure we have an op at least return a...
inplace conform rhs def conform(self, rhs): """ inplace conform rhs """ if not is_list_like(rhs): rhs = [rhs] if isinstance(rhs, np.ndarray): rhs = rhs.ravel() return rhs
create and return the op string for this TermValue def generate(self, v): """ create and return the op string for this TermValue """ val = v.tostring(self.encoding) return "({lhs} {op} {val})".format(lhs=self.lhs, op=self.op, val=val)
convert the expression that is in the term to something that is accepted by pytables def convert_value(self, v): """ convert the expression that is in the term to something that is accepted by pytables """ def stringify(value): if self.encoding is not None: ...
invert the filter def invert(self): """ invert the filter """ if self.filter is not None: f = list(self.filter) f[1] = self.generate_filter_op(invert=True) self.filter = tuple(f) return self
create and return the numexpr condition and filter def evaluate(self): """ create and return the numexpr condition and filter """ try: self.condition = self.terms.prune(ConditionBinOp) except AttributeError: raise ValueError("cannot process expression [{expr}], [{slf}] ...
quote the string if not encoded else encode and return def tostring(self, encoding): """ quote the string if not encoded else encode and return """ if self.kind == 'string': if encoding is not None: return self.converted return '"{converte...
if we have bytes, decode them to unicode def _ensure_decoded(s): """ if we have bytes, decode them to unicode """ if isinstance(s, (np.bytes_, bytes)): s = s.decode(pd.get_option('display.encoding')) return s
wrapper around numpy.result_type which overcomes the NPY_MAXARGS (32) argument limit def _result_type_many(*arrays_and_dtypes): """ wrapper around numpy.result_type which overcomes the NPY_MAXARGS (32) argument limit """ try: return np.result_type(*arrays_and_dtypes) except ValueError: ...
If 'Series.argmin' is called via the 'numpy' library, the third parameter in its signature is 'out', which takes either an ndarray or 'None', so check if the 'skipna' parameter is either an instance of ndarray or is None, since 'skipna' itself should be a boolean def validate_argmin_with_skipna(skipna,...
If 'Series.argmax' is called via the 'numpy' library, the third parameter in its signature is 'out', which takes either an ndarray or 'None', so check if the 'skipna' parameter is either an instance of ndarray or is None, since 'skipna' itself should be a boolean def validate_argmax_with_skipna(skipna,...
If 'Categorical.argsort' is called via the 'numpy' library, the first parameter in its signature is 'axis', which takes either an integer or 'None', so check if the 'ascending' parameter has either integer type or is None, since 'ascending' itself should be a boolean def validate_argsort_with_ascending...
If 'NDFrame.clip' is called via the numpy library, the third parameter in its signature is 'out', which can takes an ndarray, so check if the 'axis' parameter is an instance of ndarray, since 'axis' itself should either be an integer or None def validate_clip_with_axis(axis, args, kwargs): """ If '...
If this function is called via the 'numpy' library, the third parameter in its signature is 'dtype', which takes either a 'numpy' dtype or 'None', so check if the 'skipna' parameter is a boolean or not def validate_cum_func_with_skipna(skipna, args, kwargs, name): """ If this function is called via...
If this function is called via the 'numpy' library, the third parameter in its signature is 'axis', which takes either an ndarray or 'None', so check if the 'convert' parameter is either an instance of ndarray or is None def validate_take_with_convert(convert, args, kwargs): """ If this function is...
'args' and 'kwargs' should be empty, except for allowed kwargs because all of their necessary parameters are explicitly listed in the function signature def validate_groupby_func(name, args, kwargs, allowed=None): """ 'args' and 'kwargs' should be empty, except for allowed kwargs because all of...
'args' and 'kwargs' should be empty because all of their necessary parameters are explicitly listed in the function signature def validate_resampler_func(method, args, kwargs): """ 'args' and 'kwargs' should be empty because all of their necessary parameters are explicitly listed in the functio...
Ensure that the axis argument passed to min, max, argmin, or argmax is zero or None, as otherwise it will be incorrectly ignored. Parameters ---------- axis : int or None Raises ------ ValueError def validate_minmax_axis(axis): """ Ensure that the axis argument passed to min, max,...
msgpack (serialize) object to input file path THIS IS AN EXPERIMENTAL LIBRARY and the storage format may not be stable until a future release. Parameters ---------- path_or_buf : string File path, buffer-like, or None if None, return generated string args : an object or objec...
Load msgpack pandas object from the specified file path THIS IS AN EXPERIMENTAL LIBRARY and the storage format may not be stable until a future release. Parameters ---------- path_or_buf : string File path, BytesIO like or string encoding : Encoding for decoding msgpack str type iterat...
return my dtype mapping, whether number or name def dtype_for(t): """ return my dtype mapping, whether number or name """ if t in dtype_dict: return dtype_dict[t] return np.typeDict.get(t, t)
Convert strings to complex number instance with specified numpy type. def c2f(r, i, ctype_name): """ Convert strings to complex number instance with specified numpy type. """ ftype = c2f_dict[ctype_name] return np.typeDict[ctype_name](ftype(r) + 1j * ftype(i))
convert the numpy values to a list def convert(values): """ convert the numpy values to a list """ dtype = values.dtype if is_categorical_dtype(values): return values elif is_object_dtype(dtype): return values.ravel().tolist() if needs_i8_conversion(dtype): values = valu...
Data encoder def encode(obj): """ Data encoder """ tobj = type(obj) if isinstance(obj, Index): if isinstance(obj, RangeIndex): return {'typ': 'range_index', 'klass': obj.__class__.__name__, 'name': getattr(obj, 'name', None), ...
Decoder for deserializing numpy data types. def decode(obj): """ Decoder for deserializing numpy data types. """ typ = obj.get('typ') if typ is None: return obj elif typ == 'timestamp': freq = obj['freq'] if 'freq' in obj else obj['offset'] return Timestamp(obj['value']...
Pack an object and return the packed bytes. def pack(o, default=encode, encoding='utf-8', unicode_errors='strict', use_single_float=False, autoreset=1, use_bin_type=1): """ Pack an object and return the packed bytes. """ return Packer(default=default, encoding=encoding, ...
Unpack a packed object, return an iterator Note: packed lists will be returned as tuples def unpack(packed, object_hook=decode, list_hook=None, use_list=False, encoding='utf-8', unicode_errors='strict', object_pairs_hook=None, max_buffer_size=0, ext_hook=ExtType): """ Unpac...
Convert a JSON string to pandas object. Parameters ---------- path_or_buf : a valid JSON string or file-like, default: None The string could be a URL. Valid URL schemes include http, ftp, s3, gcs, and file. For file URLs, a host is expected. For instance, a local file could be ``fil...
Try to format axes if they are datelike. def _format_axes(self): """ Try to format axes if they are datelike. """ if not self.obj.index.is_unique and self.orient in ( 'index', 'columns'): raise ValueError("DataFrame index must be unique for orient=" ...
At this point, the data either has a `read` attribute (e.g. a file object or a StringIO) or is a string that is a JSON document. If self.chunksize, we prepare the data for the `__next__` method. Otherwise, we read it into memory for the `read` method. def _preprocess_data(self, data): ...
The function read_json accepts three input types: 1. filepath (string-like) 2. file-like object (e.g. open file object, StringIO) 3. JSON string This method turns (1) into (2) to simplify the rest of the processing. It returns input types (2) and (3) unchanged. def ...
Combines a list of JSON objects into one JSON object. def _combine_lines(self, lines): """ Combines a list of JSON objects into one JSON object. """ lines = filter(None, map(lambda x: x.strip(), lines)) return '[' + ','.join(lines) + ']'
Read the whole JSON input into a pandas object. def read(self): """ Read the whole JSON input into a pandas object. """ if self.lines and self.chunksize: obj = concat(self) elif self.lines: data = to_str(self.data) obj = self._get_object_pars...
Parses a json document into a pandas object. def _get_object_parser(self, json): """ Parses a json document into a pandas object. """ typ = self.typ dtype = self.dtype kwargs = { "orient": self.orient, "dtype": self.dtype, "convert_axes": self.con...
Checks that dict has only the appropriate keys for orient='split'. def check_keys_split(self, decoded): """ Checks that dict has only the appropriate keys for orient='split'. """ bad_keys = set(decoded.keys()).difference(set(self._split_keys)) if bad_keys: bad_keys =...
Try to convert axes. def _convert_axes(self): """ Try to convert axes. """ for axis in self.obj._AXIS_NUMBERS.keys(): new_axis, result = self._try_convert_data( axis, self.obj._get_axis(axis), use_dtypes=False, convert_dates=True) ...
Take a conversion function and possibly recreate the frame. def _process_converter(self, f, filt=None): """ Take a conversion function and possibly recreate the frame. """ if filt is None: filt = lambda col, c: True needs_new_obj = False new_obj = dict() ...
Format an array for printing. Parameters ---------- values formatter float_format na_rep digits space justify decimal leading_space : bool, optional Whether the array should be formatted with a leading space. When an array as a column of a Series or DataFrame...
Outputs rounded and formatted percentiles. Parameters ---------- percentiles : list-like, containing floats from interval [0,1] Returns ------- formatted : list of strings Notes ----- Rounding precision is chosen so that: (1) if any two elements of ``percentiles`` differ, they...
Return a formatter function for a range of timedeltas. These will all have the same format argument If box, then show the return in quotes def _get_format_timedelta64(values, nat_rep='NaT', box=False): """ Return a formatter function for a range of timedeltas. These will all have the same format a...
Separates the real and imaginary parts from the complex number, and executes the _trim_zeros_float method on each of those. def _trim_zeros_complex(str_complexes, na_rep='NaN'): """ Separates the real and imaginary parts from the complex number, and executes the _trim_zeros_float method on each of thos...
Trims zeros, leaving just one before the decimal points if need be. def _trim_zeros_float(str_floats, na_rep='NaN'): """ Trims zeros, leaving just one before the decimal points if need be. """ trimmed = str_floats def _is_number(x): return (x != na_rep and not x.endswith('inf')) def _...
Alter default behavior on how float is formatted in DataFrame. Format float in engineering format. By accuracy, we mean the number of decimal digits after the floating point. See also EngFormatter. def set_eng_float_format(accuracy=3, use_eng_prefix=False): """ Alter default behavior on how float ...
For each index in each level the function returns lengths of indexes. Parameters ---------- levels : list of lists List of values on for level. sentinel : string, optional Value which states that no new index starts on there. Returns ---------- Returns list of maps. For eac...
Appends lines to a buffer. Parameters ---------- buf The buffer to write to lines The lines to append. def buffer_put_lines(buf, lines): """ Appends lines to a buffer. Parameters ---------- buf The buffer to write to lines The lines to append. ...
Calculate display width considering unicode East Asian Width def len(self, text): """ Calculate display width considering unicode East Asian Width """ if not isinstance(text, str): return len(text) return sum(self._EAW_MAP.get(east_asian_width(c), self.ambiguous_wid...
Render a DataFrame to a list of columns (as lists of strings). def _to_str_columns(self): """ Render a DataFrame to a list of columns (as lists of strings). """ frame = self.tr_frame # may include levels names also str_index = self._get_formatted_index(frame) i...
Render a DataFrame to a console-friendly tabular output. def to_string(self): """ Render a DataFrame to a console-friendly tabular output. """ from pandas import Series frame = self.frame if len(frame.columns) == 0 or len(frame.index) == 0: info_line = ('Em...
Render a DataFrame to a LaTeX tabular/longtable environment output. def to_latex(self, column_format=None, longtable=False, encoding=None, multicolumn=False, multicolumn_format=None, multirow=False): """ Render a DataFrame to a LaTeX tabular/longtable environment output. """ ...
Render a DataFrame to a html table. Parameters ---------- classes : str or list-like classes to include in the `class` attribute of the opening ``<table>`` tag, in addition to the default "dataframe". notebook : {True, False}, optional, default False ...
Returns a function to be applied on each value to format it def _value_formatter(self, float_format=None, threshold=None): """Returns a function to be applied on each value to format it """ # the float_format parameter supersedes self.float_format if float_format is None: f...
Returns the float values converted into strings using the parameters given at initialisation, as a numpy array def get_result_as_array(self): """ Returns the float values converted into strings using the parameters given at initialisation, as a numpy array """ if self.f...
we by definition have DO NOT have a TZ def _format_strings(self): """ we by definition have DO NOT have a TZ """ values = self.values if not isinstance(values, DatetimeIndex): values = DatetimeIndex(values) if self.formatter is not None and callable(self.formatter): ...
we by definition have a TZ def _format_strings(self): """ we by definition have a TZ """ values = self.values.astype(object) is_dates_only = _is_dates_only(values) formatter = (self.formatter or _get_format_datetime64(is_dates_only, ...
Given an Interval or IntervalIndex, return the corresponding interval with closed bounds. def _get_interval_closed_bounds(interval): """ Given an Interval or IntervalIndex, return the corresponding interval with closed bounds. """ left, right = interval.left, interval.right if interval.open...
helper for interval_range to check if start/end are valid types def _is_valid_endpoint(endpoint): """helper for interval_range to check if start/end are valid types""" return any([is_number(endpoint), isinstance(endpoint, Timestamp), isinstance(endpoint, Timedelta), ...
helper for interval_range to check type compat of start/end/freq def _is_type_compatible(a, b): """helper for interval_range to check type compat of start/end/freq""" is_ts_compat = lambda x: isinstance(x, (Timestamp, DateOffset)) is_td_compat = lambda x: isinstance(x, (Timedelta, DateOffset)) return (...
Return a fixed frequency IntervalIndex Parameters ---------- start : numeric or datetime-like, default None Left bound for generating intervals end : numeric or datetime-like, default None Right bound for generating intervals periods : integer, default None Number of periods...
Create the writer & save def save(self): """ Create the writer & save """ # GH21227 internal compression is not used when file-like passed. if self.compression and hasattr(self.path_or_buf, 'write'): msg = ("compression has no effect when passing file-like " ...
Add delegated names to a class using a class decorator. This provides an alternative usage to directly calling `_add_delegate_accessors` below a class definition. Parameters ---------- delegate : object the class to get methods/properties & doc-strings accessors : Sequence[str] ...
Add additional __dir__ for this object. def _dir_additions(self): """ Add additional __dir__ for this object. """ rv = set() for accessor in self._accessors: try: getattr(self, accessor) rv.add(accessor) except AttributeErr...
Add accessors to cls from the delegate class. Parameters ---------- cls : the class to add the methods/properties to delegate : the class to get methods/properties & doc-strings accessors : string list of accessors to add typ : 'property' or 'method' overwrite : ...
standard evaluation def _evaluate_standard(op, op_str, a, b, **eval_kwargs): """ standard evaluation """ if _TEST_MODE: _store_test_result(False) with np.errstate(all='ignore'): return op(a, b)
return a boolean if we WILL be using numexpr def _can_use_numexpr(op, op_str, a, b, dtype_check): """ return a boolean if we WILL be using numexpr """ if op_str is not None: # required min elements (otherwise we are adding overhead) if np.prod(a.shape) > _MIN_ELEMENTS: # check for...
evaluate and return the expression of the op on a and b Parameters ---------- op : the actual operand op_str: the string version of the op a : left operand b : right operand use_numexpr : whether to try to use numexpr (default True) def evaluate(op, ...
evaluate the where condition cond on a and b Parameters ---------- cond : a boolean array a : return if cond is True b : return if cond is False use_numexpr : whether to try to use numexpr (default True) def where(cond, a, b, use_numexpr=True): """ evaluate t...
writer : string or ExcelWriter object File path or existing ExcelWriter sheet_name : string, default 'Sheet1' Name of sheet which will contain DataFrame startrow : upper left cell row to dump data frame startcol : upper left cell column to dump dat...
Write a DataFrame to the feather-format Parameters ---------- df : DataFrame path : string file path, or file-like object def to_feather(df, path): """ Write a DataFrame to the feather-format Parameters ---------- df : DataFrame path : string file path, or file-like object ...
Load a feather-format object from the file path .. versionadded 0.20.0 Parameters ---------- path : string file path, or file-like object columns : sequence, default None If not provided, all columns are read .. versionadded 0.24.0 nthreads : int, default 1 Number of C...
Generate a range of dates with the spans between dates described by the given `freq` DateOffset. Parameters ---------- start : Timestamp or None first point of produced date range end : Timestamp or None last point of produced date range periods : int number of periods i...
Calculate the second endpoint for passing to np.arange, checking to avoid an integer overflow. Catch OverflowError and re-raise as OutOfBoundsDatetime. Parameters ---------- endpoint : int nanosecond timestamp of the known endpoint of the desired range periods : int number of p...