From 16d34629d32fd310607996d90879365bf788a195 Mon Sep 17 00:00:00 2001 From: Kaiqi Dong Date: Mon, 3 Dec 2018 13:52:56 +0100 Subject: [PATCH] fix quote position --- pandas/core/accessor.py | 10 +- pandas/core/arrays/base.py | 75 ++++++++++----- pandas/core/arrays/categorical.py | 138 ++++++++++++++++++++-------- pandas/core/arrays/datetimelike.py | 24 +++-- pandas/core/arrays/datetimes.py | 39 +++++--- pandas/core/arrays/integer.py | 3 +- pandas/core/arrays/period.py | 15 ++- pandas/core/arrays/sparse.py | 33 +++++-- pandas/core/arrays/timedeltas.py | 10 +- pandas/core/base.py | 20 ++-- pandas/core/dtypes/base.py | 18 ++-- pandas/core/dtypes/dtypes.py | 22 +++-- pandas/core/generic.py | 50 +++++++--- pandas/core/indexes/datetimelike.py | 4 +- pandas/core/indexes/multi.py | 1 - pandas/core/indexes/period.py | 3 +- pandas/core/indexing.py | 19 ++-- pandas/core/series.py | 9 ++ pandas/core/strings.py | 3 +- pandas/core/tools/datetimes.py | 7 +- pandas/plotting/_converter.py | 6 +- pandas/plotting/_core.py | 4 +- 22 files changed, 356 insertions(+), 157 deletions(-) diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index f2ae7f6b56551..fa1dc751c17da 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -41,7 +41,9 @@ def __dir__(self): class PandasDelegate(object): - """ an abstract base class for delegating methods/properties """ + """ + an abstract base class for delegating methods/properties + """ def _delegate_property_get(self, name, *args, **kwargs): raise TypeError("You cannot access the " @@ -146,7 +148,8 @@ def add_delegate_accessors(cls): # 2. We use a UserWarning instead of a custom Warning class CachedAccessor(object): - """Custom property-like object (descriptor) for caching accessors. + """ + Custom property-like object (descriptor) for caching accessors. Parameters ---------- @@ -189,7 +192,8 @@ def decorator(accessor): return decorator -_doc = """Register a custom accessor on %(klass)s objects. +_doc = """\ +Register a custom accessor on %(klass)s objects. Parameters ---------- diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index eb2fef482ff17..8877436dcf51c 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -22,7 +22,8 @@ class ExtensionArray(object): - """Abstract base class for custom 1-D array types. + """ + Abstract base class for custom 1-D array types. pandas will recognize instances of this class as proper arrays with a custom type and will not attempt to coerce them to objects. They @@ -100,7 +101,8 @@ class ExtensionArray(object): # ------------------------------------------------------------------------ @classmethod def _from_sequence(cls, scalars, dtype=None, copy=False): - """Construct a new ExtensionArray from a sequence of scalars. + """ + Construct a new ExtensionArray from a sequence of scalars. Parameters ---------- @@ -121,7 +123,8 @@ def _from_sequence(cls, scalars, dtype=None, copy=False): @classmethod def _from_factorized(cls, values, original): - """Reconstruct an ExtensionArray after factorization. + """ + Reconstruct an ExtensionArray after factorization. Parameters ---------- @@ -143,7 +146,8 @@ def _from_factorized(cls, values, original): def __getitem__(self, item): # type (Any) -> Any - """Select a subset of self. + """ + Select a subset of self. Parameters ---------- @@ -174,7 +178,8 @@ def __getitem__(self, item): def __setitem__(self, key, value): # type: (Union[int, np.ndarray], Any) -> None - """Set one or more values inplace. + """ + Set one or more values inplace. This method is not required to satisfy the pandas extension array interface. @@ -219,7 +224,8 @@ def __setitem__(self, key, value): def __len__(self): # type: () -> int - """Length of this array + """ + Length of this array Returns ------- @@ -228,8 +234,8 @@ def __len__(self): raise AbstractMethodError(self) def __iter__(self): - """Iterate over elements of the array. - + """ + Iterate over elements of the array. """ # This needs to be implemented so that pandas recognizes extension # arrays as list-like. The default implementation makes successive @@ -243,26 +249,32 @@ def __iter__(self): @property def dtype(self): # type: () -> ExtensionDtype - """An instance of 'ExtensionDtype'.""" + """ + An instance of 'ExtensionDtype'. + """ raise AbstractMethodError(self) @property def shape(self): # type: () -> Tuple[int, ...] - """Return a tuple of the array dimensions.""" + """ + Return a tuple of the array dimensions. + """ return (len(self),) @property def ndim(self): # type: () -> int - """Extension Arrays are only allowed to be 1-dimensional.""" + """ + Extension Arrays are only allowed to be 1-dimensional. + """ return 1 @property def nbytes(self): # type: () -> int - """The number of bytes needed to store this object in memory. - + """ + The number of bytes needed to store this object in memory. """ # If this is expensive to compute, return an approximate lower bound # on the number of bytes needed. @@ -272,7 +284,8 @@ def nbytes(self): # Additional Methods # ------------------------------------------------------------------------ def astype(self, dtype, copy=True): - """Cast to a NumPy array with 'dtype'. + """ + Cast to a NumPy array with 'dtype'. Parameters ---------- @@ -315,7 +328,8 @@ def isna(self): def _values_for_argsort(self): # type: () -> ndarray - """Return values for sorting. + """ + Return values for sorting. Returns ------- @@ -365,7 +379,8 @@ def argsort(self, ascending=True, kind='quicksort', *args, **kwargs): return result def fillna(self, value=None, method=None, limit=None): - """ Fill NA/NaN values using the specified method. + """ + Fill NA/NaN values using the specified method. Parameters ---------- @@ -418,7 +433,8 @@ def fillna(self, value=None, method=None, limit=None): return new_values def dropna(self): - """ Return ExtensionArray without NA values + """ + Return ExtensionArray without NA values Returns ------- @@ -462,7 +478,8 @@ def shift(self, periods=1): return self._concat_same_type([a, b]) def unique(self): - """Compute the ExtensionArray of unique values. + """ + Compute the ExtensionArray of unique values. Returns ------- @@ -475,7 +492,8 @@ def unique(self): def _values_for_factorize(self): # type: () -> Tuple[ndarray, Any] - """Return an array and missing value suitable for factorization. + """ + Return an array and missing value suitable for factorization. Returns ------- @@ -499,7 +517,8 @@ def _values_for_factorize(self): def factorize(self, na_sentinel=-1): # type: (int) -> Tuple[ndarray, ExtensionArray] - """Encode the extension array as an enumerated type. + """ + Encode the extension array as an enumerated type. Parameters ---------- @@ -552,7 +571,8 @@ def factorize(self, na_sentinel=-1): def take(self, indices, allow_fill=False, fill_value=None): # type: (Sequence[int], bool, Optional[Any]) -> ExtensionArray - """Take elements from an array. + """ + Take elements from an array. Parameters ---------- @@ -641,7 +661,8 @@ def take(self, indices, allow_fill=False, fill_value=None): def copy(self, deep=False): # type: (bool) -> ExtensionArray - """Return a copy of the array. + """ + Return a copy of the array. Parameters ---------- @@ -661,13 +682,16 @@ def copy(self, deep=False): def _formatting_values(self): # type: () -> np.ndarray # At the moment, this has to be an array since we use result.dtype - """An array of values to be printed in, e.g. the Series repr""" + """ + An array of values to be printed in, e.g. the Series repr + """ return np.array(self) @classmethod def _concat_same_type(cls, to_concat): # type: (Sequence[ExtensionArray]) -> ExtensionArray - """Concatenate multiple array + """ + Concatenate multiple array Parameters ---------- @@ -689,7 +713,8 @@ def _concat_same_type(cls, to_concat): @property def _ndarray_values(self): # type: () -> np.ndarray - """Internal pandas method for lossy conversion to a NumPy ndarray. + """ + Internal pandas method for lossy conversion to a NumPy ndarray. This method is not part of the pandas interface. diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 5db851d4bf021..c8d9cf4a79dfe 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -200,7 +200,8 @@ def contains(cat, key, container): return any(loc_ in container for loc_ in loc) -_codes_doc = """The category codes of this categorical. +_codes_doc = """\ +The category codes of this categorical. Level codes are an array if integer which are the positions of the real values in the categories array. @@ -425,7 +426,8 @@ def __init__(self, values, categories=None, ordered=None, dtype=None, @property def categories(self): - """The categories of this categorical. + """ + The categories of this categorical. Setting assigns new values to each category (effectively a rename of each individual category). @@ -464,12 +466,16 @@ def categories(self, categories): @property def ordered(self): - """Whether the categories have an ordered relationship""" + """ + Whether the categories have an ordered relationship + """ return self.dtype.ordered @property def dtype(self): - """The :class:`~pandas.api.types.CategoricalDtype` for this instance""" + """ + The :class:`~pandas.api.types.CategoricalDtype` for this instance + """ return self._dtype @property @@ -485,7 +491,9 @@ def _from_sequence(cls, scalars, dtype=None, copy=False): return Categorical(scalars, dtype=dtype) def copy(self): - """ Copy constructor. """ + """ + Copy constructor. + """ return self._constructor(values=self._codes.copy(), dtype=self.dtype, fastpath=True) @@ -516,17 +524,23 @@ def astype(self, dtype, copy=True): @cache_readonly def ndim(self): - """Number of dimensions of the Categorical """ + """ + Number of dimensions of the Categorical + """ return self._codes.ndim @cache_readonly def size(self): - """ return the len of myself """ + """ + return the len of myself + """ return len(self) @cache_readonly def itemsize(self): - """ return the size of a single category """ + """ + return the size of a single category + """ return self.categories.itemsize def tolist(self): @@ -541,7 +555,9 @@ def tolist(self): @property def base(self): - """ compat, we are always our own object """ + """ + compat, we are always our own object + """ return None @classmethod @@ -660,7 +676,8 @@ def from_codes(cls, codes, categories, ordered=False): _codes = None def _get_codes(self): - """ Get the codes. + """ + Get the codes. Returns ------- @@ -680,7 +697,8 @@ def _set_codes(self, codes): codes = property(fget=_get_codes, fset=_set_codes, doc=_codes_doc) def _set_categories(self, categories, fastpath=False): - """ Sets new categories inplace + """ + Sets new categories inplace Parameters ---------- @@ -713,7 +731,8 @@ def _set_categories(self, categories, fastpath=False): self._dtype = new_dtype def _set_dtype(self, dtype): - """Internal method for directly updating the CategoricalDtype + """ + Internal method for directly updating the CategoricalDtype Parameters ---------- @@ -775,7 +794,8 @@ def as_unordered(self, inplace=False): def set_categories(self, new_categories, ordered=None, rename=False, inplace=False): - """ Sets the categories to the specified new_categories. + """ + Sets the categories to the specified new_categories. `new_categories` can include new categories (which will result in unused categories) or remove old categories (which results in values @@ -845,7 +865,8 @@ def set_categories(self, new_categories, ordered=None, rename=False, return cat def rename_categories(self, new_categories, inplace=False): - """ Renames categories. + """ + Renames categories. Raises ------ @@ -938,7 +959,8 @@ def rename_categories(self, new_categories, inplace=False): return cat def reorder_categories(self, new_categories, ordered=None, inplace=False): - """ Reorders categories as specified in new_categories. + """ + Reorders categories as specified in new_categories. `new_categories` need to include all old categories and no new category items. @@ -980,7 +1002,8 @@ def reorder_categories(self, new_categories, ordered=None, inplace=False): inplace=inplace) def add_categories(self, new_categories, inplace=False): - """ Add new categories. + """ + Add new categories. `new_categories` will be included at the last/highest place in the categories and will be unused directly after this call. @@ -1029,7 +1052,8 @@ def add_categories(self, new_categories, inplace=False): return cat def remove_categories(self, removals, inplace=False): - """ Removes the specified categories. + """ + Removes the specified categories. `removals` must be included in the old categories. Values which were in the removed categories will be set to NaN @@ -1081,7 +1105,8 @@ def remove_categories(self, removals, inplace=False): rename=False, inplace=inplace) def remove_unused_categories(self, inplace=False): - """ Removes categories which are not used. + """ + Removes categories which are not used. Parameters ---------- @@ -1204,7 +1229,8 @@ def map(self, mapper): # for Series/ndarray like compat @property def shape(self): - """ Shape of the Categorical. + """ + Shape of the Categorical. For internal compatibility with numpy arrays. @@ -1296,6 +1322,9 @@ def __setstate__(self, state): @property def T(self): + """ + Return transposed numpy array. + """ return self @property @@ -1449,7 +1478,8 @@ def value_counts(self, dropna=True): return Series(count, index=CategoricalIndex(ix), dtype='int64') def get_values(self): - """ Return the values. + """ + Return the values. For internal compatibility with pandas formatting. @@ -1478,7 +1508,8 @@ def argsort(self, *args, **kwargs): # TODO(PY2): use correct signature # We have to do *args, **kwargs to avoid a a py2-only signature # issue since np.argsort differs from argsort. - """Return the indices that would sort the Categorical. + """ + Return the indices that would sort the Categorical. Parameters ---------- @@ -1521,7 +1552,8 @@ def argsort(self, *args, **kwargs): return super(Categorical, self).argsort(*args, **kwargs) def sort_values(self, inplace=False, ascending=True, na_position='last'): - """ Sorts the Categorical by category value returning a new + """ + Sorts the Categorical by category value returning a new Categorical by default. While an ordering is applied to the category values, sorting in this @@ -1639,7 +1671,8 @@ def _values_for_rank(self): return values def ravel(self, order='C'): - """ Return a flattened (numpy) array. + """ + Return a flattened (numpy) array. For internal compatibility with numpy arrays. @@ -1650,7 +1683,8 @@ def ravel(self, order='C'): return np.array(self) def view(self): - """Return a view of myself. + """ + Return a view of myself. For internal compatibility with numpy arrays. @@ -1662,7 +1696,8 @@ def view(self): return self def to_dense(self): - """Return my 'dense' representation + """ + Return my 'dense' representation For internal compatibility with numpy arrays. @@ -1674,7 +1709,8 @@ def to_dense(self): @deprecate_kwarg(old_arg_name='fill_value', new_arg_name='value') def fillna(self, value=None, method=None, limit=None): - """ Fill NA/NaN values using the specified method. + """ + Fill NA/NaN values using the specified method. Parameters ---------- @@ -1857,7 +1893,8 @@ def take_nd(self, indexer, allow_fill=None, fill_value=None): take = take_nd def _slice(self, slicer): - """ Return a slice of myself. + """ + Return a slice of myself. For internal compatibility with numpy arrays. """ @@ -1874,15 +1911,21 @@ def _slice(self, slicer): return self._constructor(values=codes, dtype=self.dtype, fastpath=True) def __len__(self): - """The length of this Categorical.""" + """ + The length of this Categorical. + """ return len(self._codes) def __iter__(self): - """Returns an Iterator over the values of this Categorical.""" + """ + Returns an Iterator over the values of this Categorical. + """ return iter(self.get_values().tolist()) def __contains__(self, key): - """Returns True if `key` is in this Categorical.""" + """ + Returns True if `key` is in this Categorical. + """ # if key is a NaN, check if any NaN is in self. if isna(key): return self.isna().any() @@ -1905,7 +1948,9 @@ def _tidy_repr(self, max_vals=10, footer=True): return compat.text_type(result) def _repr_categories(self): - """ return the base repr for the categories """ + """ + return the base repr for the categories + """ max_categories = (10 if get_option("display.max_categories") == 0 else get_option("display.max_categories")) from pandas.io.formats import format as fmt @@ -1922,7 +1967,9 @@ def _repr_categories(self): return category_strs def _repr_categories_info(self): - """ Returns a string representation of the footer.""" + """ + Returns a string representation of the footer. + """ category_strs = self._repr_categories() dtype = getattr(self.categories, 'dtype_str', @@ -1965,7 +2012,9 @@ def _get_repr(self, length=True, na_rep='NaN', footer=True): return compat.text_type(result) def __unicode__(self): - """ Unicode representation. """ + """ + Unicode representation. + """ _maxlen = 10 if len(self._codes) > _maxlen: result = self._tidy_repr(_maxlen) @@ -1978,13 +2027,17 @@ def __unicode__(self): return result def _maybe_coerce_indexer(self, indexer): - """ return an indexer coerced to the codes dtype """ + """ + return an indexer coerced to the codes dtype + """ if isinstance(indexer, np.ndarray) and indexer.dtype.kind == 'i': indexer = indexer.astype(self._codes.dtype) return indexer def __getitem__(self, key): - """ Return an item. """ + """ + Return an item. + """ if isinstance(key, (int, np.integer)): i = self._codes[key] if i == -1: @@ -1996,7 +2049,8 @@ def __getitem__(self, key): dtype=self.dtype, fastpath=True) def __setitem__(self, key, value): - """ Item assignment. + """ + Item assignment. Raises @@ -2100,7 +2154,8 @@ def _reduce(self, name, axis=0, skipna=True, **kwargs): return func(**kwargs) def min(self, numeric_only=None, **kwargs): - """ The minimum value of the object. + """ + The minimum value of the object. Only ordered `Categoricals` have a minimum! @@ -2125,7 +2180,8 @@ def min(self, numeric_only=None, **kwargs): return self.categories[pointer] def max(self, numeric_only=None, **kwargs): - """ The maximum value of the object. + """ + The maximum value of the object. Only ordered `Categoricals` have a maximum! @@ -2284,7 +2340,8 @@ def is_dtype_equal(self, other): return False def describe(self): - """ Describes this Categorical + """ + Describes this Categorical Returns ------- @@ -2441,6 +2498,9 @@ def _delegate_property_set(self, name, new_values): @property def codes(self): + """ + Return Series of codes as well as the index. + """ from pandas import Series return Series(self._parent.codes, index=self.index) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 83ee335aa5465..3f4e8cedb6ac5 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -76,7 +76,9 @@ def _simple_new(cls, values, **kwargs): raise AbstractMethodError(cls) def _get_attributes_dict(self): - """return an attributes dict for my class""" + """ + return an attributes dict for my class + """ return {k: getattr(self, k, None) for k in self._attributes} @@ -254,12 +256,16 @@ def isna(self): @property # NB: override with cache_readonly in immutable subclasses def _isnan(self): - """ return if each value is nan""" + """ + return if each value is nan + """ return (self.asi8 == iNaT) @property # NB: override with cache_readonly in immutable subclasses def hasnans(self): - """ return if I have any nans; enables various perf speedups """ + """ + return if I have any nans; enables various perf speedups + """ return bool(self._isnan.any()) def _maybe_mask_results(self, result, fill_value=iNaT, convert=None): @@ -293,7 +299,9 @@ def _maybe_mask_results(self, result, fill_value=iNaT, convert=None): @property def freq(self): - """Return the frequency object if it is set, otherwise None""" + """ + Return the frequency object if it is set, otherwise None. + """ return self._freq @freq.setter @@ -459,7 +467,9 @@ def _add_delta_tdi(self, other): return new_values.view('i8') def _add_nat(self): - """Add pd.NaT to self""" + """ + Add pd.NaT to self + """ if is_period_dtype(self): raise TypeError('Cannot add {cls} and {typ}' .format(cls=type(self).__name__, @@ -474,7 +484,9 @@ def _add_nat(self): return type(self)(result, tz=self.tz, freq=None) def _sub_nat(self): - """Subtract pd.NaT from self""" + """ + Subtract pd.NaT from self + """ # GH#19124 Timedelta - datetime is not in general well-defined. # We make an exception for pd.NaT, which in this case quacks # like a timedelta. diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 4d3caaacca1c1..7bc15c73802cb 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -340,6 +340,9 @@ def dtype(self): @property def tz(self): + """ + Return timezone. + """ # GH 18595 return self._tz @@ -358,12 +361,16 @@ def tzinfo(self): @property # NB: override with cache_readonly in immutable subclasses def _timezone(self): - """ Comparable timezone both for pytz / dateutil""" + """ + Comparable timezone both for pytz / dateutil + """ return timezones.get_timezone(self.tzinfo) @property def offset(self): - """get/set the frequency of the instance""" + """ + get/set the frequency of the instance + """ msg = ('{cls}.offset has been deprecated and will be removed ' 'in a future version; use {cls}.freq instead.' .format(cls=type(self).__name__)) @@ -372,7 +379,9 @@ def offset(self): @offset.setter def offset(self, value): - """get/set the frequency of the instance""" + """ + get/set the frequency of the instance + """ msg = ('{cls}.offset has been deprecated and will be removed ' 'in a future version; use {cls}.freq instead.' .format(cls=type(self).__name__)) @@ -1062,19 +1071,19 @@ def date(self): return tslib.ints_to_pydatetime(timestamps, box="date") - year = _field_accessor('year', 'Y', "The year of the datetime") + year = _field_accessor('year', 'Y', "\n The year of the datetime\n") month = _field_accessor('month', 'M', - "The month as January=1, December=12") - day = _field_accessor('day', 'D', "The days of the datetime") - hour = _field_accessor('hour', 'h', "The hours of the datetime") - minute = _field_accessor('minute', 'm', "The minutes of the datetime") - second = _field_accessor('second', 's', "The seconds of the datetime") + "\n The month as January=1, December=12 \n") + day = _field_accessor('day', 'D', "\nThe days of the datetime\n") + hour = _field_accessor('hour', 'h', "\nThe hours of the datetime\n") + minute = _field_accessor('minute', 'm', "\nThe minutes of the datetime\n") + second = _field_accessor('second', 's', "\nThe seconds of the datetime\n") microsecond = _field_accessor('microsecond', 'us', - "The microseconds of the datetime") + "\nThe microseconds of the datetime\n") nanosecond = _field_accessor('nanosecond', 'ns', - "The nanoseconds of the datetime") + "\nThe nanoseconds of the datetime\n") weekofyear = _field_accessor('weekofyear', 'woy', - "The week ordinal of the year") + "\nThe week ordinal of the year\n") week = weekofyear _dayofweek_doc = """ The day of the week with Monday=0, Sunday=6. @@ -1119,12 +1128,12 @@ def date(self): "The name of day in a week (ex: Friday)\n\n.. deprecated:: 0.23.0") dayofyear = _field_accessor('dayofyear', 'doy', - "The ordinal day of the year") - quarter = _field_accessor('quarter', 'q', "The quarter of the date") + "\nThe ordinal day of the year\n") + quarter = _field_accessor('quarter', 'q', "\nThe quarter of the date\n") days_in_month = _field_accessor( 'days_in_month', 'dim', - "The number of days in the month") + "\nThe number of days in the month\n") daysinmonth = days_in_month _is_month_doc = """ Indicates whether the date is the {first_or_last} day of the month. diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index e9d51aaea4218..7996e24d0c914 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -386,7 +386,8 @@ def _concat_same_type(cls, to_concat): return cls(data, mask) def astype(self, dtype, copy=True): - """Cast to a NumPy array or IntegerArray with 'dtype'. + """ + Cast to a NumPy array or IntegerArray with 'dtype'. Parameters ---------- diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 53629dca4d391..9342276921863 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -205,7 +205,8 @@ def _from_sequence(cls, scalars, dtype=None, copy=False): @classmethod def _from_datetime64(cls, data, freq, tz=None): - """Construct a PeriodArray from a datetime64 array + """ + Construct a PeriodArray from a datetime64 array Parameters ---------- @@ -255,7 +256,9 @@ def _ndarray_values(self): @property def freq(self): - """Return the frequency object for this PeriodArray.""" + """ + Return the frequency object for this PeriodArray. + """ return self.dtype.freq # -------------------------------------------------------------------- @@ -282,7 +285,9 @@ def freq(self): @property def is_leap_year(self): - """ Logical indicating if the date belongs to a leap year """ + """ + Logical indicating if the date belongs to a leap year + """ return isleapyear_arr(np.asarray(self.year)) @property @@ -568,7 +573,9 @@ def asfreq(self, freq=None, how='E'): # Formatting def _format_native_types(self, na_rep=u'NaT', date_format=None, **kwargs): - """ actually format my specific types """ + """ + actually format my specific types + """ # TODO(DatetimeArray): remove values = self.astype(object) diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py index 9a5ef3b3a7dd0..ae5a4eb7075de 100644 --- a/pandas/core/arrays/sparse.py +++ b/pandas/core/arrays/sparse.py @@ -169,7 +169,9 @@ def _is_boolean(self): @property def kind(self): - """The sparse kind. Either 'integer', or 'block'.""" + """ + The sparse kind. Either 'integer', or 'block'. + """ return self.subtype.kind @property @@ -285,7 +287,8 @@ def is_dtype(cls, dtype): return isinstance(dtype, np.dtype) or dtype == 'Sparse' def update_dtype(self, dtype): - """Convert the SparseDtype to a new dtype. + """ + Convert the SparseDtype to a new dtype. This takes care of converting the ``fill_value``. @@ -478,7 +481,9 @@ def _sparse_array_op(left, right, op, name): def _wrap_result(name, data, sparse_index, fill_value, dtype=None): - """ wrap op result to have correct dtype """ + """ + wrap op result to have correct dtype + """ if name.startswith('__'): # e.g. __eq__ --> eq name = name[2:-2] @@ -787,7 +792,8 @@ def nbytes(self): @property def density(self): - """The percent of non- ``fill_value`` points, as decimal. + """ + The percent of non- ``fill_value`` points, as decimal. Examples -------- @@ -800,7 +806,8 @@ def density(self): @property def npoints(self): - """The number of non- ``fill_value`` points. + """ + The number of non- ``fill_value`` points. Examples -------- @@ -1523,12 +1530,16 @@ def mean(self, axis=0, *args, **kwargs): return (sp_sum + self.fill_value * nsparse) / (ct + nsparse) def transpose(self, *axes): - """Returns the SparseArray.""" + """ + Returns the SparseArray. + """ return self @property def T(self): - """Returns the SparseArray.""" + """ + Returns the SparseArray. + """ return self # ------------------------------------------------------------------------ @@ -1742,14 +1753,18 @@ def __unicode__(self): def _maybe_to_dense(obj): - """ try to convert to dense """ + """ + try to convert to dense + """ if hasattr(obj, 'to_dense'): return obj.to_dense() return obj def _maybe_to_sparse(array): - """ array must be SparseSeries or SparseArray """ + """ + array must be SparseSeries or SparseArray + """ if isinstance(array, ABCSparseSeries): array = array.values.copy() return array diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 83cea51cec9f6..0039cc9565df7 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -444,16 +444,16 @@ def to_pytimedelta(self): return tslibs.ints_to_pytimedelta(self.asi8) days = _field_accessor("days", "days", - " Number of days for each element. ") + "\nNumber of days for each element.\n") seconds = _field_accessor("seconds", "seconds", - " Number of seconds (>= 0 and less than 1 day) " - "for each element. ") + "\nNumber of seconds (>= 0 and less than 1 day) " + "for each element.\n") microseconds = _field_accessor("microseconds", "microseconds", "\nNumber of microseconds (>= 0 and less " - "than 1 second) for each\nelement. ") + "than 1 second) for each element.\n") nanoseconds = _field_accessor("nanoseconds", "nanoseconds", "\nNumber of nanoseconds (>= 0 and less " - "than 1 microsecond) for each\nelement.\n") + "than 1 microsecond) for each element.\n") @property def components(self): diff --git a/pandas/core/base.py b/pandas/core/base.py index fd303182959a5..31ff60b025758 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -631,7 +631,9 @@ def _aggregate_multiple_funcs(self, arg, _level, _axis): return result def _shallow_copy(self, obj=None, obj_type=None, **kwargs): - """ return a new object with the replacement attributes """ + """ + return a new object with the replacement attributes + """ if obj is None: obj = self._selected_obj.copy() if obj_type is None: @@ -644,7 +646,9 @@ def _shallow_copy(self, obj=None, obj_type=None, **kwargs): return obj_type(obj, **kwargs) def _is_cython_func(self, arg): - """ if we define an internal function for this argument, return it """ + """ + if we define an internal function for this argument, return it + """ return self._cython_table.get(arg) def _is_builtin_func(self, arg): @@ -675,7 +679,8 @@ def transpose(self, *args, **kwargs): @property def _is_homogeneous_type(self): - """Whether the object has a single dtype. + """ + Whether the object has a single dtype. By definition, Series and Index are always considered homogeneous. A MultiIndex may or may not be homogeneous, depending on the @@ -780,7 +785,8 @@ def base(self): @property def _ndarray_values(self): # type: () -> np.ndarray - """The data as an ndarray, possibly losing information. + """ + The data as an ndarray, possibly losing information. The expectation is that this is cheap to compute, and is primarily used for interacting with our indexers. @@ -927,7 +933,8 @@ def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None, return func(**kwds) def _map_values(self, mapper, na_action=None): - """An internal function that maps values using the input + """ + An internal function that maps values using the input correspondence (which can be a dict, Series, or function). Parameters @@ -1201,7 +1208,8 @@ def factorize(self, sort=False, na_sentinel=-1): return algorithms.factorize(self, sort=sort, na_sentinel=na_sentinel) _shared_docs['searchsorted'] = ( - """Find indices where elements should be inserted to maintain order. + """ + Find indices where elements should be inserted to maintain order. Find the indices into a sorted %(klass)s `self` such that, if the corresponding elements in `value` were inserted before the indices, diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index df0e89cced816..aa81e88abf28e 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -146,7 +146,8 @@ def _is_boolean(self): class ExtensionDtype(_DtypeOpsMixin): - """A custom data type, to be paired with an ExtensionArray. + """ + A custom data type, to be paired with an ExtensionArray. .. versionadded:: 0.23.0 @@ -211,7 +212,8 @@ def __str__(self): @property def type(self): # type: () -> type - """The scalar type for the array, e.g. ``int`` + """ + The scalar type for the array, e.g. ``int`` It's expected ``ExtensionArray[item]`` returns an instance of ``ExtensionDtype.type`` for scalar ``item``, assuming @@ -223,7 +225,8 @@ def type(self): @property def kind(self): # type () -> str - """A character code (one of 'biufcmMOSUV'), default 'O' + """ + A character code (one of 'biufcmMOSUV'), default 'O' This should match the NumPy dtype used when the array is converted to an ndarray, which is probably 'O' for object if @@ -239,7 +242,8 @@ def kind(self): @property def name(self): # type: () -> str - """A string identifying the data type. + """ + A string identifying the data type. Will be used for display in, e.g. ``Series.dtype`` """ @@ -247,7 +251,8 @@ def name(self): @classmethod def construct_array_type(cls): - """Return the array type associated with this dtype + """ + Return the array type associated with this dtype Returns ------- @@ -257,7 +262,8 @@ def construct_array_type(cls): @classmethod def construct_from_string(cls, string): - """Attempt to construct this type from a string. + """ + Attempt to construct this type from a string. Parameters ---------- diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index fee983f969221..e432f3604f7b1 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -342,7 +342,8 @@ def _hash_categories(categories, ordered=True): @classmethod def construct_array_type(cls): - """Return the array type associated with this dtype + """ + Return the array type associated with this dtype Returns ------- @@ -353,7 +354,8 @@ def construct_array_type(cls): @classmethod def construct_from_string(cls, string): - """ attempt to construct this type from a string, raise a TypeError if + """ + attempt to construct this type from a string, raise a TypeError if it's not possible """ try: if string == 'category': @@ -459,7 +461,9 @@ def categories(self): @property def ordered(self): - """Whether the categories have an ordered relationship""" + """ + Whether the categories have an ordered relationship + """ return self._ordered @property @@ -488,7 +492,8 @@ class DatetimeTZDtype(PandasExtensionDtype): _cache = {} def __new__(cls, unit=None, tz=None): - """ Create a new unit if needed, otherwise return from the cache + """ + Create a new unit if needed, otherwise return from the cache Parameters ---------- @@ -547,7 +552,8 @@ def __new__(cls, unit=None, tz=None): @classmethod def construct_array_type(cls): - """Return the array type associated with this dtype + """ + Return the array type associated with this dtype Returns ------- @@ -558,7 +564,8 @@ def construct_array_type(cls): @classmethod def construct_from_string(cls, string): - """ attempt to construct this type from a string, raise a TypeError if + """ + attempt to construct this type from a string, raise a TypeError if it's not possible """ try: @@ -775,7 +782,8 @@ def __new__(cls, subtype=None): @classmethod def construct_array_type(cls): - """Return the array type associated with this dtype + """ + Return the array type associated with this dtype Returns ------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f43b93f200db3..1918eb08831ac 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -152,6 +152,9 @@ def _init_mgr(self, mgr, axes=None, dtype=None, copy=False): @property def is_copy(self): + """ + Return the copy. + """ warnings.warn("Attribute 'is_copy' is deprecated and will be removed " "in a future version.", FutureWarning, stacklevel=2) return self._is_copy @@ -415,12 +418,16 @@ def _stat_axis(self): @property def shape(self): - """Return a tuple of axis dimensions""" + """ + Return a tuple of axis dimensions + """ return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS) @property def axes(self): - """Return index label(s) of the internal NDFrame""" + """ + Return index label(s) of the internal NDFrame + """ # we do it this way because if we have reversed axes, then # the block manager shows then reversed return [self._get_axis(a) for a in self._AXIS_ORDERS] @@ -685,7 +692,8 @@ def swapaxes(self, axis1, axis2, copy=True): return self._constructor(new_values, *new_axes).__finalize__(self) def droplevel(self, level, axis=0): - """Return DataFrame with requested index / column level(s) removed. + """ + Return DataFrame with requested index / column level(s) removed. .. versionadded:: 0.24.0 @@ -1457,7 +1465,8 @@ def __nonzero__(self): __bool__ = __nonzero__ def bool(self): - """Return the bool of a single element PandasObject. + """ + Return the bool of a single element PandasObject. This must be a boolean scalar value, either True or False. Raise a ValueError if the PandasObject does not have exactly 1 element, or that @@ -1893,7 +1902,9 @@ def __array_wrap__(self, result, context=None): # return dict(typestr=values.dtype.str,shape=values.shape,data=values) def to_dense(self): - """Return dense representation of NDFrame (as opposed to sparse)""" + """ + Return dense representation of NDFrame (as opposed to sparse) + """ # compat return self @@ -3550,7 +3561,8 @@ def xs(self, key, axis=0, level=None, drop_level=True): _xs = xs def select(self, crit, axis=0): - """Return data corresponding to axis labels matching criteria + """ + Return data corresponding to axis labels matching criteria .. deprecated:: 0.21.0 Use df.loc[df.index.map(crit)] to select via labels @@ -4311,7 +4323,8 @@ def _needs_reindex_multi(self, axes, method, level): def _reindex_multi(self, axes, copy, fill_value): return NotImplemented - _shared_docs['reindex_axis'] = ("""Conform input object to new index + _shared_docs['reindex_axis'] = (""" + Conform input object to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False. @@ -5116,7 +5129,8 @@ def _get_bool_data(self): # Internal Interface Methods def as_matrix(self, columns=None): - """Convert the frame to its Numpy-array representation. + """ + Convert the frame to its Numpy-array representation. .. deprecated:: 0.23.0 Use :meth:`DataFrame.values` instead. @@ -5757,7 +5771,8 @@ def _convert(self, datetime=False, numeric=False, timedelta=False, def convert_objects(self, convert_dates=True, convert_numeric=False, convert_timedeltas=True, copy=True): - """Attempt to infer better dtype for object columns. + """ + Attempt to infer better dtype for object columns. .. deprecated:: 0.21.0 @@ -9662,7 +9677,9 @@ def describe_1d(data): return d def _check_percentile(self, q): - """Validate percentiles (used by describe and quantile).""" + """ + Validate percentiles (used by describe and quantile). + """ msg = ("percentiles should all be in the interval [0, 1]. " "Try {0} instead.") @@ -9821,7 +9838,9 @@ def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwargs): @classmethod def _add_numeric_operations(cls): - """Add the operations to the cls; evaluate the doc strings again""" + """ + Add the operations to the cls; evaluate the doc strings again + """ axis_descr, name, name2 = _doc_parms(cls) @@ -9947,7 +9966,8 @@ def compound(self, axis=None, skipna=None, level=None): @classmethod def _add_series_only_operations(cls): - """Add the series only operations to the cls; evaluate the doc + """ + Add the series only operations to the cls; evaluate the doc strings again. """ @@ -9973,7 +9993,8 @@ def nanptp(values, axis=0, skipna=True): @classmethod def _add_series_or_dataframe_operations(cls): - """Add the series or dataframe only operations to the cls; evaluate + """ + Add the series or dataframe only operations to the cls; evaluate the doc strings again. """ @@ -10035,7 +10056,8 @@ def transform(self, func, *args, **kwargs): """ def _find_valid_index(self, how): - """Retrieves the index of the first valid value. + """ + Retrieves the index of the first valid value. Parameters ---------- diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 5e25efe77d8b9..8542a59a69d38 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -216,7 +216,9 @@ def ceil(self, freq, ambiguous='raise', nonexistent='raise'): class DatetimeIndexOpsMixin(DatetimeLikeArrayMixin): - """ common ops mixin to support a unified interface datetimelike Index """ + """ + common ops mixin to support a unified interface datetimelike Index + """ # override DatetimeLikeArrayMixin method copy = Index.copy diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index f03376c32f7f4..1e2f0d8108f02 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1,4 +1,3 @@ - # pylint: disable=E1101,E1103,W0232 import datetime from sys import getsizeof diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 56df454bddf1c..ef0c4b3b8a9d7 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -960,7 +960,8 @@ def asi8(self): return self.view('i8') def item(self): - """ return the first element of the underlying data as a python + """ + return the first element of the underlying data as a python scalar """ # TODO(DatetimeArray): remove diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index cfa451db866be..0914324a03f84 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2415,7 +2415,8 @@ def _convert_key(self, key, is_setter=False): def length_of_indexer(indexer, target=None): - """return the length of a single non-tuple indexer which could be a slice + """ + return the length of a single non-tuple indexer which could be a slice """ if target is not None and isinstance(indexer, slice): target_len = len(target) @@ -2443,7 +2444,8 @@ def length_of_indexer(indexer, target=None): def convert_to_index_sliceable(obj, key): - """if we are index sliceable, then return my slicer, otherwise return None + """ + if we are index sliceable, then return my slicer, otherwise return None """ idx = obj.index if isinstance(key, slice): @@ -2493,7 +2495,8 @@ def check_bool_indexer(ax, key): def check_setitem_lengths(indexer, value, values): - """Validate that value and indexer are the same length. + """ + Validate that value and indexer are the same length. An special-case is allowed for when the indexer is a boolean array and the number of true values equals the length of ``value``. In @@ -2536,7 +2539,8 @@ def check_setitem_lengths(indexer, value, values): def convert_missing_indexer(indexer): - """ reverse convert a missing indexer, which is a dict + """ + reverse convert a missing indexer, which is a dict return the scalar indexer and a boolean indicating if we converted """ @@ -2553,7 +2557,9 @@ def convert_missing_indexer(indexer): def convert_from_missing_indexer_tuple(indexer, axes): - """ create a filtered indexer that doesn't have any missing indexers """ + """ + create a filtered indexer that doesn't have any missing indexers + """ def get_indexer(_i, _idx): return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else @@ -2607,7 +2613,8 @@ def maybe_convert_indices(indices, n): def validate_indices(indices, n): - """Perform bounds-checking for an indexer. + """ + Perform bounds-checking for an indexer. -1 is allowed for indicating missing values. diff --git a/pandas/core/series.py b/pandas/core/series.py index c3bcd2d76c27a..ecbe899525fdb 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -389,6 +389,9 @@ def _update_inplace(self, result, **kwargs): @property def name(self): + """ + Return name of the Series. + """ return self._name @name.setter @@ -678,6 +681,9 @@ def __array_prepare__(self, result, context=None): @property def real(self): + """ + Return the real value of vector. + """ return self.values.real @real.setter @@ -686,6 +692,9 @@ def real(self, v): @property def imag(self): + """ + Return imag value of vector. + """ return self.values.imag @imag.setter diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 0b791f6f91aa3..d372623472f3c 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -2804,7 +2804,8 @@ def rfind(self, sub, start=0, end=None): return self._wrap_result(result) def normalize(self, form): - """Return the Unicode normal form for the strings in the Series/Index. + """ + Return the Unicode normal form for the strings in the Series/Index. For more information on the forms, see the :func:`unicodedata.normalize`. diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index ee44a64514f4f..a6d71b7db3cfd 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -700,9 +700,10 @@ def coerce(values): def _attempt_YYYYMMDD(arg, errors): - """ try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like, - arg is a passed in as an object dtype, but could really be ints/strings - with nan-like/or floats (e.g. with nan) + """ + try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like, + arg is a passed in as an object dtype, but could really be ints/strings + with nan-like/or floats (e.g. with nan) Parameters ---------- diff --git a/pandas/plotting/_converter.py b/pandas/plotting/_converter.py index 20e4fdffc39b6..8139694138a84 100644 --- a/pandas/plotting/_converter.py +++ b/pandas/plotting/_converter.py @@ -55,7 +55,8 @@ def get_pairs(): def register(explicit=True): - """Register Pandas Formatters and Converters with matplotlib + """ + Register Pandas Formatters and Converters with matplotlib This function modifies the global ``matplotlib.units.registry`` dictionary. Pandas adds custom converters for @@ -87,7 +88,8 @@ def register(explicit=True): def deregister(): - """Remove pandas' formatters and converters + """ + Remove pandas' formatters and converters Removes the custom converters added by :func:`register`. This attempts to set the state of the registry back to the state before diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 8574275c8478b..c50514a1414cd 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -1948,7 +1948,6 @@ def _plot(data, x=None, y=None, subplots=False, for bar plot layout by `position` keyword. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center) %(klass_note)s - """ @@ -2709,7 +2708,8 @@ def __call__(self, *args, **kwargs): class SeriesPlotMethods(BasePlotMethods): - """Series plotting accessor and method + """ + Series plotting accessor and method Examples --------