From 1c6b957597fad5915b47d57834940dd98ecc4469 Mon Sep 17 00:00:00 2001 From: MomIsBestFriend <> Date: Sat, 21 Dec 2019 16:54:59 +0200 Subject: [PATCH 1/2] TYP --- pandas/core/indexers.py | 5 +- pandas/core/indexes/accessors.py | 13 ++-- pandas/core/indexes/api.py | 2 - pandas/core/indexes/base.py | 10 ++- pandas/core/indexes/category.py | 4 +- pandas/core/indexes/datetimelike.py | 11 +-- pandas/core/indexes/datetimes.py | 55 ++++++++++----- pandas/core/indexes/frozen.py | 8 ++- pandas/core/indexes/interval.py | 102 +++++++++++++++++----------- pandas/core/indexes/multi.py | 41 +++++------ pandas/core/indexes/numeric.py | 30 ++++---- pandas/io/formats/console.py | 17 +++-- 12 files changed, 175 insertions(+), 123 deletions(-) diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py index 209f889e809c3..ac1b0ab766a03 100644 --- a/pandas/core/indexers.py +++ b/pandas/core/indexers.py @@ -144,8 +144,9 @@ def validate_indices(indices: np.ndarray, n: int) -> None: if len(indices): min_idx = indices.min() if min_idx < -1: - msg = f"'indices' contains values less than allowed ({min_idx} < -1)" - raise ValueError(msg) + raise ValueError( + f"'indices' contains values less than allowed ({min_idx} < -1)" + ) max_idx = indices.max() if max_idx >= n: diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index ae27aad3dda08..db774a03c02f8 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -26,8 +26,7 @@ class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin): def __init__(self, data, orig): if not isinstance(data, ABCSeries): raise TypeError( - f"cannot convert an object of type {type(data)} to a " - "datetimelike index" + f"cannot convert an object of type {type(data)} to a datetimelike index" ) self._parent = data @@ -91,9 +90,8 @@ def _delegate_property_get(self, name): def _delegate_property_set(self, name, value, *args, **kwargs): raise ValueError( - "modifications to a property of a datetimelike " - "object are not supported. Change values on the " - "original." + "modifications to a property of a datetimelike object are not supported. " + "Change values on the original." ) def _delegate_method(self, name, *args, **kwargs): @@ -222,7 +220,7 @@ def to_pytimedelta(self): Returns ------- - a : numpy.ndarray + numpy.ndarray Array of 1D containing data with `datetime.timedelta` type. See Also @@ -314,8 +312,7 @@ def __new__(cls, data): if not isinstance(data, ABCSeries): raise TypeError( - f"cannot convert an object of type {type(data)} to a " - "datetimelike index" + f"cannot convert an object of type {type(data)} to a datetimelike index" ) orig = data if is_categorical_dtype(data) else None diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index e99ae96f35315..1904456848396 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -124,7 +124,6 @@ def _get_combined_index( ------- Index """ - # TODO: handle index names! indexes = _get_distinct_objs(indexes) if len(indexes) == 0: @@ -273,7 +272,6 @@ def get_consensus_names(indexes): list A list representing the consensus 'names' found. """ - # 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)} diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5abd049b9564c..ce7a238daeca9 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -804,11 +804,10 @@ def _assert_take_fillable( # only fill if we are passing a non-None fill_value if allow_fill and fill_value is not None: if (indices < -1).any(): - msg = ( + raise ValueError( "When allow_fill=True and fill_value is not None, " "all indices must be >= -1" ) - raise ValueError(msg) taken = algos.take( values, indices, allow_fill=allow_fill, fill_value=na_value ) @@ -1324,8 +1323,7 @@ def set_names(self, names, level=None, inplace=False): raise ValueError("Level must be None for non-MultiIndex") if level is not None and not is_list_like(level) and is_list_like(names): - msg = "Names must be a string when a single level is provided." - raise TypeError(msg) + raise TypeError("Names must be a string when a single level is provided.") if not is_list_like(names) and level is None and self.nlevels > 1: raise TypeError("Must pass list-like as `names`.") @@ -1421,8 +1419,8 @@ def _validate_index_level(self, level): if isinstance(level, int): if level < 0 and level != -1: raise IndexError( - f"Too many levels: Index has only 1 level," - f" {level} is not a valid level number" + "Too many levels: Index has only 1 level, " + f"{level} is not a valid level number" ) elif level > 0: raise IndexError( diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 44478d00da9cf..d35117b8db86e 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -715,9 +715,7 @@ def _convert_list_indexer(self, keyarr, kind=None): indexer = self.categories.get_indexer(np.asarray(keyarr)) if (indexer == -1).any(): raise KeyError( - "a list-indexer must only " - "include values that are " - "in the categories" + "a list-indexer must only include values that are in the categories" ) return self.get_indexer(keyarr) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 50dbddec5c8b2..3bf6dce00a031 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -2,7 +2,7 @@ Base and utility classes for tseries type pandas objects. """ import operator -from typing import Set +from typing import List, Set import numpy as np @@ -73,7 +73,7 @@ def method(self, other): class DatetimeIndexOpsMixin(ExtensionOpsMixin): """ - common ops mixin to support a unified interface datetimelike Index + Common ops mixin to support a unified interface datetimelike Index. """ _data: ExtensionArray @@ -336,7 +336,7 @@ def _convert_tolerance(self, tolerance, target): raise ValueError("list-like tolerance size must match target index size") return tolerance - def tolist(self): + def tolist(self) -> List: """ Return a list of the underlying data. """ @@ -661,11 +661,12 @@ def _summary(self, name=None): Parameters ---------- name : str - name to use in the summary representation + Name to use in the summary representation. Returns ------- - String with a summarized representation of the index + str + Summarized representation of the index. """ formatter = self._formatter_func if len(self) > 0: diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 523c434cb7377..1fd962dd24656 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -45,9 +45,10 @@ def _new_DatetimeIndex(cls, d): - """ This is called upon unpickling, rather than the default which doesn't - have arguments and breaks __new__ """ - + """ + This is called upon unpickling, rather than the default which doesn't + have arguments and breaks __new__ + """ if "data" in d and not isinstance(d["data"], DatetimeIndex): # Avoid need to verify integrity by calling simple_new directly data = d.pop("data") @@ -100,9 +101,9 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin): Parameters ---------- - data : array-like (1-dimensional), optional + data : array-like (1-dimensional), optional Optional datetime-like data to construct index with. - copy : bool + copy : bool Make a copy of input ndarray. freq : str or pandas offset object, optional One of pandas date offset strings or corresponding objects. The string @@ -273,7 +274,7 @@ def __new__( @classmethod def _simple_new(cls, values, name=None, freq=None, tz=None, dtype=None): """ - we require the we have a dtype compat for the values + We require the we have a dtype compat for the values if we are passed a non-dtype compat, then coerce using the constructor """ if isinstance(values, DatetimeArray): @@ -345,7 +346,13 @@ def tz(self, value): @cache_readonly def _is_dates_only(self) -> bool: - """Return a boolean if we are only dates (and don't have a timezone)""" + """ + Return a boolean if we are only dates (and don't have a timezone) + + Returns + ------- + bool + """ from pandas.io.formats.format import _is_dates_only return _is_dates_only(self.values) and self.tz is None @@ -360,7 +367,9 @@ def __reduce__(self): return _new_DatetimeIndex, (type(self), d), None def __setstate__(self, state): - """Necessary for making this object picklable""" + """ + Necessary for making this object picklable. + """ if isinstance(state, dict): super().__setstate__(state) @@ -393,7 +402,9 @@ def __setstate__(self, state): _unpickle_compat = __setstate__ def _convert_for_op(self, value): - """ Convert value to be insertable to ndarray """ + """ + Convert value to be insertable to ndarray. + """ if self._has_same_tz(value): return _to_M8(value) raise ValueError("Passed item and index have different timezone") @@ -461,7 +472,7 @@ def _union(self, other, sort): def union_many(self, others): """ - A bit of a hack to accelerate unioning a collection of indexes + A bit of a hack to accelerate unioning a collection of indexes. """ this = self @@ -489,7 +500,7 @@ def union_many(self, others): this._data._dtype = dtype return this - def _can_fast_union(self, other): + def _can_fast_union(self, other) -> bool: if not isinstance(other, DatetimeIndex): return False @@ -581,7 +592,7 @@ def intersection(self, other, sort=False): Returns ------- - y : Index or DatetimeIndex or TimedeltaIndex + Index or DatetimeIndex or TimedeltaIndex """ return super().intersection(other, sort=sort) @@ -699,7 +710,9 @@ def snap(self, freq="S"): # we know it conforms; skip check return DatetimeIndex._simple_new(snapped, name=self.name, tz=self.tz, freq=freq) - def join(self, other, how="left", level=None, return_indexers=False, sort=False): + def join( + self, other, how: str = "left", level=None, return_indexers=False, sort=False + ): """ See Index.join """ @@ -840,9 +853,8 @@ def _parsed_string_to_bounds(self, reso, parsed): if parsed.tzinfo is not None: if self.tz is None: raise ValueError( - "The index must be timezone aware " - "when indexing with a date string with a " - "UTC offset" + "The index must be timezone aware when indexing " + "with a date string with a UTC offset" ) start = start.tz_localize(parsed.tzinfo).tz_convert(self.tz) end = end.tz_localize(parsed.tzinfo).tz_convert(self.tz) @@ -851,7 +863,16 @@ def _parsed_string_to_bounds(self, reso, parsed): end = end.tz_localize(self.tz) return start, end - def _partial_date_slice(self, reso, parsed, use_lhs=True, use_rhs=True): + def _partial_date_slice( + self, reso: str, parsed, use_lhs: bool = True, use_rhs: bool = True + ): + """ + Parameters + ---------- + reso : str + use_lhs : bool, default True + use_rhs : bool, default True + """ is_monotonic = self.is_monotonic if ( is_monotonic diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py index fd8ab74ed4920..909643d50e9d7 100644 --- a/pandas/core/indexes/frozen.py +++ b/pandas/core/indexes/frozen.py @@ -35,7 +35,7 @@ def union(self, other) -> "FrozenList": Returns ------- - diff : FrozenList + FrozenList The collection difference between self and other. """ if isinstance(other, tuple): @@ -53,7 +53,7 @@ def difference(self, other) -> "FrozenList": Returns ------- - diff : FrozenList + FrozenList The collection difference between self and other. """ other = set(other) @@ -92,7 +92,9 @@ def __hash__(self): return hash(tuple(self)) def _disabled(self, *args, **kwargs): - """This method will not function because object is immutable.""" + """ + This method will not function because object is immutable. + """ raise TypeError(f"'{type(self).__name__}' does not support mutable operations.") def __str__(self) -> str: diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index f046f0d89c428..dee4c959f8c90 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -143,21 +143,19 @@ def func(intvidx_self, other, sort=False): result = result.astype(intvidx_self.dtype) return result elif intvidx_self.closed != other.closed: - msg = ( + raise ValueError( "can only do set operations between two IntervalIndex " "objects that are closed on the same side" ) - raise ValueError(msg) # GH 19016: ensure set op will not return a prohibited dtype subtypes = [intvidx_self.dtype.subtype, other.dtype.subtype] common_subtype = find_common_type(subtypes) if is_object_dtype(common_subtype): - msg = ( + raise TypeError( f"can only do {self.op_name} between two IntervalIndex " "objects that have compatible dtypes" ) - raise TypeError(msg) return setop(intvidx_self, other, sort) @@ -210,7 +208,13 @@ class IntervalIndex(IntervalMixin, Index): # Constructors def __new__( - cls, data, closed=None, dtype=None, copy=False, name=None, verify_integrity=True + cls, + data, + closed=None, + dtype=None, + copy: bool = False, + name=None, + verify_integrity: bool = True, ): if name is None and hasattr(data, "name"): @@ -263,7 +267,9 @@ def _simple_new(cls, array, name, closed=None): ), ) ) - def from_breaks(cls, breaks, closed="right", name=None, copy=False, dtype=None): + def from_breaks( + cls, breaks, closed: str = "right", name=None, copy: bool = False, dtype=None + ): with rewrite_exception("IntervalArray", cls.__name__): array = IntervalArray.from_breaks( breaks, closed=closed, copy=copy, dtype=dtype @@ -288,7 +294,13 @@ def from_breaks(cls, breaks, closed="right", name=None, copy=False, dtype=None): ) ) def from_arrays( - cls, left, right, closed="right", name=None, copy=False, dtype=None + cls, + left, + right, + closed: str = "right", + name=None, + copy: bool = False, + dtype=None, ): with rewrite_exception("IntervalArray", cls.__name__): array = IntervalArray.from_arrays( @@ -313,7 +325,9 @@ def from_arrays( ), ) ) - def from_tuples(cls, data, closed="right", name=None, copy=False, dtype=None): + def from_tuples( + cls, data, closed: str = "right", name=None, copy: bool = False, dtype=None + ): with rewrite_exception("IntervalArray", cls.__name__): arr = IntervalArray.from_tuples(data, closed=closed, copy=copy, dtype=dtype) return cls._simple_new(arr, name=name) @@ -329,7 +343,9 @@ def _shallow_copy(self, left=None, right=None, **kwargs): @cache_readonly def _isnan(self): - """Return a mask indicating if each value is NA""" + """ + Return a mask indicating if each value is NA. + """ if self._mask is None: self._mask = isna(self.left) return self._mask @@ -351,7 +367,7 @@ def __contains__(self, key) -> bool: Returns ------- - boolean + bool """ if not isinstance(key, Interval): return False @@ -470,7 +486,9 @@ def _ndarray_values(self) -> np.ndarray: return np.array(self._data) def __array__(self, result=None): - """ the array interface, return my values """ + """ + The array interface, return my values. + """ return self._ndarray_values def __array_wrap__(self, result, context=None): @@ -503,7 +521,9 @@ def astype(self, dtype, copy=True): @cache_readonly def dtype(self): - """Return the dtype object of the underlying data""" + """ + Return the dtype object of the underlying data. + """ return self._data.dtype @property @@ -551,7 +571,7 @@ def is_monotonic_decreasing(self) -> bool: @cache_readonly def is_unique(self): """ - Return True if the IntervalIndex contains unique elements, else False + Return True if the IntervalIndex contains unique elements, else False. """ left = self.left right = self.right @@ -708,7 +728,7 @@ def _needs_i8_conversion(self, key): Returns ------- - boolean + bool """ if is_interval_dtype(key) or isinstance(key, Interval): return self._needs_i8_conversion(key.left) @@ -729,7 +749,7 @@ def _maybe_convert_i8(self, key): Returns ------- - key: scalar or list-like + scalar or list-like The original key if no conversion occurred, int if converted scalar, Int64Index if converted list-like. """ @@ -775,22 +795,21 @@ def _check_method(self, method): return if method in ["bfill", "backfill", "pad", "ffill", "nearest"]: - msg = f"method {method} not yet implemented for IntervalIndex" - raise NotImplementedError(msg) + raise NotImplementedError( + f"method {method} not yet implemented for IntervalIndex" + ) raise ValueError("Invalid fill method") def _searchsorted_monotonic(self, label, side, exclude_label=False): if not self.is_non_overlapping_monotonic: raise KeyError( - "can only get slices from an IntervalIndex if " - "bounds are non-overlapping and all monotonic " - "increasing or decreasing" + "can only get slices from an IntervalIndex if bounds are " + "non-overlapping and all monotonic increasing or decreasing" ) if isinstance(label, IntervalMixin): - msg = "Interval objects are not currently supported" - raise NotImplementedError(msg) + raise NotImplementedError("Interval objects are not currently supported") # GH 20921: "not is_monotonic_increasing" for the second condition # instead of "is_monotonic_decreasing" to account for single element @@ -850,7 +869,7 @@ def get_loc( Returns ------- - loc : int if unique index, slice if monotonic index, else mask + int if unique index, slice if monotonic index, else mask Examples -------- @@ -933,11 +952,10 @@ def get_indexer( self._check_method(method) if self.is_overlapping: - msg = ( - "cannot handle overlapping indices; use " - "IntervalIndex.get_indexer_non_unique" + raise InvalidIndexError( + "cannot handle overlapping indices; " + "use IntervalIndex.get_indexer_non_unique" ) - raise InvalidIndexError(msg) target_as_index = ensure_index(target) @@ -1071,7 +1089,7 @@ def delete(self, loc): Returns ------- - new_index : IntervalIndex + IntervalIndex """ new_left = self.left.delete(loc) new_right = self.right.delete(loc) @@ -1090,7 +1108,7 @@ def insert(self, loc, item): Returns ------- - new_index : IntervalIndex + IntervalIndex """ if isinstance(item, Interval): if item.closed != self.closed: @@ -1117,11 +1135,10 @@ def _concat_same_dtype(self, to_concat, name): we allow a 0-len index here as well """ if not len({i.closed for i in to_concat if len(i)}) == 1: - msg = ( + raise ValueError( "can only append two IntervalIndex objects " "that are closed on the same side" ) - raise ValueError(msg) return super()._concat_same_dtype(to_concat, name) @Appender(_index_shared_docs["take"] % _index_doc_kwargs) @@ -1175,10 +1192,13 @@ def _format_data(self, name=None): n = min(max_seq_items // 2, 10) head = [formatter(x) for x in self[:n]] tail = [formatter(x) for x in self[-n:]] - summary = f"[{', '.join(head)} ... {', '.join(tail)}]" + head_joined = ", ".join(head) + tail_joined = ", ".join(tail) + summary = f"[{head_joined} ... {tail_joined}]" else: tail = [formatter(x) for x in self] - summary = f"[{', '.join(tail)}]" + joined = ", ".join(tail) + summary = f"[{joined}]" return summary + "," + self._format_space() @@ -1189,7 +1209,7 @@ def _format_attrs(self): attrs.append(("dtype", f"'{self.dtype}'")) return attrs - def _format_space(self): + def _format_space(self) -> str: space = " " * (len(type(self).__name__) + 1) return f"\n{space}" @@ -1200,7 +1220,7 @@ def argsort(self, *args, **kwargs): def equals(self, other) -> bool: """ - Determines if two IntervalIndex objects contain the same elements + Determines if two IntervalIndex objects contain the same elements. """ if self.is_(other): return True @@ -1288,7 +1308,7 @@ def _intersection_unique(self, other: "IntervalIndex") -> "IntervalIndex": Returns ------- - taken : IntervalIndex + IntervalIndex """ lindexer = self.left.get_indexer(other.left) rindexer = self.right.get_indexer(other.right) @@ -1310,7 +1330,7 @@ def _intersection_non_unique(self, other: "IntervalIndex") -> "IntervalIndex": Returns ------- - taken : IntervalIndex + IntervalIndex """ mask = np.zeros(len(self), dtype=bool) @@ -1360,7 +1380,9 @@ def is_all_dates(self) -> bool: def _is_valid_endpoint(endpoint) -> bool: - """helper for interval_range to check if start/end are valid types""" + """ + Helper for interval_range to check if start/end are valid types. + """ return any( [ is_number(endpoint), @@ -1372,7 +1394,9 @@ def _is_valid_endpoint(endpoint) -> bool: def _is_type_compatible(a, b) -> bool: - """helper for interval_range to check type compat of start/end/freq""" + """ + 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 ( diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 9e434d0f5f704..d3b738e2a95d1 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1,6 +1,7 @@ from collections import OrderedDict import datetime from sys import getsizeof +from typing import List, Optional import warnings import numpy as np @@ -85,7 +86,7 @@ def _codes_to_ints(self, codes): Returns ------- - int_keys : scalar or 1-dimensional array, of dtype uint64 + scalar or 1-dimensional array, of dtype uint64 Integer(s) representing one combination (each). """ # Shift the representation of each level by the pre-calculated number @@ -125,7 +126,7 @@ def _codes_to_ints(self, codes): Returns ------- - int_keys : int, or 1-dimensional array of dtype object + int, or 1-dimensional array of dtype object Integer(s) representing one combination (each). """ @@ -248,8 +249,8 @@ def __new__( dtype=None, copy=False, name=None, - verify_integrity=True, - _set_identity=True, + verify_integrity: bool = True, + _set_identity: bool = True, ): # compat with Index @@ -287,7 +288,7 @@ def __new__( return result - def _validate_codes(self, level: list, code: list): + def _validate_codes(self, level: List, code: List): """ Reassign code values as -1 if their corresponding levels are NaN. @@ -300,7 +301,7 @@ def _validate_codes(self, level: list, code: list): Returns ------- - code : new code where code value = -1 if it corresponds + new code where code value = -1 if it corresponds to a level with missing values (NaN, NaT, None). """ null_mask = isna(level) @@ -308,9 +309,10 @@ def _validate_codes(self, level: list, code: list): code = np.where(null_mask[code], -1, code) return code - def _verify_integrity(self, codes=None, levels=None): + def _verify_integrity( + self, codes: Optional[List] = None, levels: Optional[List] = None + ): """ - Parameters ---------- codes : optional list @@ -326,7 +328,7 @@ def _verify_integrity(self, codes=None, levels=None): Returns ------- - codes : new codes where code value = -1 if it corresponds to a + new codes where code value = -1 if it corresponds to a NaN level. """ # NOTE: Currently does not check, among other things, that cached @@ -336,8 +338,8 @@ def _verify_integrity(self, codes=None, levels=None): if len(levels) != len(codes): raise ValueError( - "Length of levels and codes must match. NOTE:" - " this index is in an inconsistent state." + "Length of levels and codes must match. NOTE: " + "this index is in an inconsistent state." ) codes_length = len(codes[0]) for i, (level, level_codes) in enumerate(zip(levels, codes)): @@ -389,7 +391,7 @@ def from_arrays(cls, arrays, sortorder=None, names=_no_default_names): Returns ------- - index : MultiIndex + MultiIndex See Also -------- @@ -454,7 +456,7 @@ def from_tuples(cls, tuples, sortorder=None, names=None): Returns ------- - index : MultiIndex + MultiIndex See Also -------- @@ -481,8 +483,7 @@ def from_tuples(cls, tuples, sortorder=None, names=None): if len(tuples) == 0: if names is None: - msg = "Cannot infer number of levels from empty list" - raise TypeError(msg) + raise TypeError("Cannot infer number of levels from empty list") arrays = [[]] * len(names) elif isinstance(tuples, (np.ndarray, Index)): if isinstance(tuples, Index): @@ -518,7 +519,7 @@ def from_product(cls, iterables, sortorder=None, names=_no_default_names): Returns ------- - index : MultiIndex + MultiIndex See Also -------- @@ -653,15 +654,15 @@ def array(self): ------ ValueError """ - msg = ( + raise ValueError( "MultiIndex has no single backing array. Use " "'MultiIndex.to_numpy()' to get a NumPy array of tuples." ) - raise ValueError(msg) @property def _is_homogeneous_type(self) -> bool: - """Whether the levels of a MultiIndex all have the same dtype. + """ + Whether the levels of a MultiIndex all have the same dtype. This looks at the dtypes of the levels. @@ -732,7 +733,7 @@ def set_levels(self, levels, level=None, inplace=False, verify_integrity=True): Level(s) to set (None for all levels). inplace : bool If True, mutates in place. - verify_integrity : bool (default True) + verify_integrity : bool ,default True If True, checks that levels and codes are compatible. Returns diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 048bff46759bc..b84c69b8caf51 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -85,8 +85,9 @@ def _validate_dtype(cls, dtype: Dtype) -> None: validation_func, expected = validation_metadata[cls._typ] if not validation_func(dtype): - msg = f"Incorrect `dtype` passed: expected {expected}, received {dtype}" - raise ValueError(msg) + raise ValueError( + f"Incorrect `dtype` passed: expected {expected}, received {dtype}" + ) @Appender(_index_shared_docs["_maybe_cast_slice_bound"]) def _maybe_cast_slice_bound(self, label, side, kind): @@ -106,7 +107,6 @@ def _convert_for_op(self, value): """ Convert value to be insertable to ndarray. """ - if is_bool(value) or is_bool_dtype(value): # force conversion to object # so we don't lose the bools @@ -121,17 +121,13 @@ def _convert_tolerance(self, tolerance, target): if not np.issubdtype(tolerance.dtype, np.number): if tolerance.ndim > 0: raise ValueError( - ( - f"tolerance argument for {type(self).__name__} must contain " - "numeric elements if it is list type" - ) + f"tolerance argument for {type(self).__name__} must contain " + "numeric elements if it is list type" ) else: raise ValueError( - ( - f"tolerance argument for {type(self).__name__} must be numeric " - f"if it is a scalar: {repr(tolerance)}" - ) + f"tolerance argument for {type(self).__name__} must be numeric " + f"if it is a scalar: {repr(tolerance)}" ) return tolerance @@ -244,7 +240,9 @@ class Int64Index(IntegerIndex): @property def inferred_type(self) -> str: - """Always 'integer' for ``Int64Index``""" + """ + Always 'integer' for ``Int64Index`` + """ return "integer" @property @@ -299,7 +297,9 @@ class UInt64Index(IntegerIndex): @property def inferred_type(self) -> str: - """Always 'integer' for ``UInt64Index``""" + """ + Always 'integer' for ``UInt64Index`` + """ return "integer" @property @@ -374,7 +374,9 @@ class Float64Index(NumericIndex): @property def inferred_type(self) -> str: - """Always 'floating' for ``Float64Index``""" + """ + Always 'floating' for ``Float64Index`` + """ return "floating" @Appender(_index_shared_docs["astype"]) diff --git a/pandas/io/formats/console.py b/pandas/io/formats/console.py index 1d4fa929b2138..bed29e1fd4792 100644 --- a/pandas/io/formats/console.py +++ b/pandas/io/formats/console.py @@ -6,7 +6,8 @@ def get_console_size(): - """Return console size as tuple = (width, height). + """ + Return console size as tuple = (width, height). Returns (None,None) in non-interactive session. """ @@ -50,9 +51,13 @@ def get_console_size(): def in_interactive_session(): - """ check if we're running in an interactive shell + """ + Check if we're running in an interactive shell. - returns True if running under python/ipython interactive shell + Returns + ------- + bool + True if running under python/ipython interactive shell. """ from pandas import get_option @@ -71,7 +76,11 @@ def check_main(): def in_ipython_frontend(): """ - check if we're inside an an IPython zmq frontend + Check if we're inside an an IPython zmq frontend. + + Returns + ------- + bool """ try: ip = get_ipython() # noqa From adb088b5919f9450425c1b1170aa293ea3b0831f Mon Sep 17 00:00:00 2001 From: MomIsBestFriend <50263213+MomIsBestFriend@users.noreply.github.com> Date: Sat, 21 Dec 2019 21:24:36 +0200 Subject: [PATCH 2/2] Update multi.py --- pandas/core/indexes/multi.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index d3b738e2a95d1..05a4da28eb0a1 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -733,7 +733,7 @@ def set_levels(self, levels, level=None, inplace=False, verify_integrity=True): Level(s) to set (None for all levels). inplace : bool If True, mutates in place. - verify_integrity : bool ,default True + verify_integrity : bool, default True If True, checks that levels and codes are compatible. Returns