diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index b0bead2f66ce4..baca22f28f5c3 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -253,8 +253,10 @@ def array_to_timedelta64(object[:] values, unit='ns', errors='raise'): cdef inline int64_t cast_from_unit(object ts, object unit) except? -1: - """ return a casting of the unit represented to nanoseconds - round the fractional part of a float to our precision, p """ + """ + return a casting of the unit represented to nanoseconds + round the fractional part of a float to our precision, p + """ cdef: int64_t m int p @@ -482,7 +484,6 @@ cdef inline parse_timedelta_string(object ts): cdef inline int64_t timedelta_as_neg(int64_t value, bint neg): """ - Parameters ---------- value : int64_t of the timedelta value @@ -495,7 +496,6 @@ cdef inline int64_t timedelta_as_neg(int64_t value, bint neg): cdef inline timedelta_from_spec(object number, object frac, object unit): """ - Parameters ---------- number : a list of number digits @@ -739,9 +739,18 @@ cdef _to_py_int_float(v): # heavy lifting. cdef class _Timedelta(timedelta): cdef readonly: - int64_t value # nanoseconds - object freq # frequency reference - bint is_populated # are my components populated + int64_t value + """ + nanoseconds + """ + object freq + """ + frequency reference + """ + bint is_populated + """ + are my components populated + """ int64_t _d, _h, _m, _s, _ms, _us, _ns # higher than np.ndarray and np.matrix @@ -813,7 +822,9 @@ cdef class _Timedelta(timedelta): return timedelta(microseconds=int(self.value) / 1000) def to_timedelta64(self): - """ Returns a numpy.timedelta64 object with 'ns' precision """ + """ + Returns a numpy.timedelta64 object with 'ns' precision + """ return np.timedelta64(self.value, 'ns') def total_seconds(self): @@ -823,12 +834,16 @@ cdef class _Timedelta(timedelta): return self.value / 1e9 def view(self, dtype): - """ array view compat """ + """ + array view compat + """ return np.timedelta64(self.value).view(dtype) @property def components(self): - """ Return a Components NamedTuple-like """ + """ + Return a Components NamedTuple-like + """ self._ensure_components() # return the named tuple return Components(self._d, self._h, self._m, self._s, @@ -897,6 +912,7 @@ cdef class _Timedelta(timedelta): >>> td.asm8 numpy.timedelta64(42,'ns') """ + return np.int64(self.value).view('m8[ns]') @property @@ -993,7 +1009,6 @@ cdef class _Timedelta(timedelta): def _repr_base(self, format=None): """ - Parameters ---------- format : None|all|sub_day|long @@ -1001,7 +1016,6 @@ cdef class _Timedelta(timedelta): Returns ------- converted : string of a Timedelta - """ cdef object sign, seconds_pretty, subs, fmt, comp_dict @@ -1127,7 +1141,6 @@ class Timedelta(_Timedelta): Notes ----- The ``.value`` attribute is always in ns. - """ def __new__(cls, object value=_no_input, unit=None, **kwargs): cdef _Timedelta td_base @@ -1473,7 +1486,8 @@ cdef _rfloordiv(int64_t value, right): cdef _broadcast_floordiv_td64(int64_t value, object other, object (*operation)(int64_t value, object right)): - """Boilerplate code shared by Timedelta.__floordiv__ and + """ + Boilerplate code shared by Timedelta.__floordiv__ and Timedelta.__rfloordiv__ because np.timedelta64 does not implement these. Parameters diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index b4862a5f3b02f..8b8134e9d6dcf 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -59,7 +59,9 @@ def maybe_integer_op_deprecated(obj): cdef inline object create_timestamp_from_ts(int64_t value, npy_datetimestruct dts, object tz, object freq): - """ convenience routine to construct a Timestamp from its parts """ + """ + onvenience routine to construct a Timestamp from its parts + """ cdef _Timestamp ts_base ts_base = _Timestamp.__new__(Timestamp, dts.year, dts.month, dts.day, dts.hour, dts.min, @@ -113,7 +115,9 @@ class RoundTo(enum.Enum): cdef inline _npdivmod(x1, x2): - """implement divmod for numpy < 1.13""" + """ + implement divmod for numpy < 1.13 + """ return np.floor_divide(x1, x2), np.remainder(x1, x2) @@ -326,7 +330,9 @@ cdef class _Timestamp(datetime): self.microsecond, self.tzinfo) cpdef to_datetime64(self): - """ Returns a numpy.datetime64 object with 'ns' precision """ + """ + Returns a numpy.datetime64 object with 'ns' precision + """ return np.datetime64(self.value, 'ns') def __add__(self, other): @@ -413,7 +419,9 @@ cdef class _Timestamp(datetime): return datetime.__sub__(self, other) cdef int64_t _maybe_convert_value_to_local(self): - """Convert UTC i8 value to local i8 value if tz exists""" + """ + Convert UTC i8 value to local i8 value if tz exists + """ cdef: int64_t val val = self.value @@ -500,7 +508,9 @@ cdef class _Timestamp(datetime): return Timedelta(nanoseconds=1) def timestamp(self): - """Return POSIX timestamp as float.""" + """ + Return POSIX timestamp as float. + """ # py27 compat, see GH#17329 return round(self.value / 1e9, 6) @@ -512,7 +522,8 @@ cdef class _Timestamp(datetime): class Timestamp(_Timestamp): - """Pandas replacement for datetime.datetime + """ + Pandas replacement for datetime.datetime Timestamp is the pandas equivalent of python's Datetime and is interchangeable with it in most cases. It's the type used @@ -1189,7 +1200,9 @@ class Timestamp(_Timestamp): # replace def validate(k, v): - """ validate integers """ + """ + validate integers + """ if not is_integer_object(v): raise ValueError("value must be an integer, received " "{v} for {k}".format(v=type(v), k=k)) diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index b778b2132cd96..dbd9fd3d9a710 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -42,8 +42,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__ + """ # data are already in UTC # so need to localize @@ -397,7 +399,9 @@ def nbytes(self): @cache_readonly def _is_dates_only(self): - """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) + """ from pandas.io.formats.format import _is_dates_only return _is_dates_only(self.values) and self.tz is None @@ -411,7 +415,9 @@ def __reduce__(self): return _new_DatetimeIndex, (self.__class__, d), None def __setstate__(self, state): - """Necessary for making this object picklable""" + """ + Necessary for making this object picklable + """ if isinstance(state, dict): super(DatetimeIndex, self).__setstate__(state) @@ -439,13 +445,17 @@ 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') def _maybe_update_attributes(self, attrs): - """ Update Index attributes (e.g. freq) depending on op """ + """ + Update Index attributes (e.g. freq) depending on op + """ freq = attrs.get('freq', None) if freq is not None: # no need to infer if freq is None diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 444f9e21b0bdc..54dfc154e60c1 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1,4 +1,6 @@ -""" define the IntervalIndex """ +""" +define the IntervalIndex +""" import textwrap import warnings @@ -225,7 +227,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 @@ -381,7 +385,9 @@ def _ndarray_values(self): 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): @@ -413,12 +419,16 @@ 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 def inferred_type(self): - """Return a string of the type inferred from the values""" + """ + Return a string of the type inferred from the values + """ return 'interval' @Appender(Index.memory_usage.__doc__) @@ -718,7 +728,8 @@ def _find_non_overlapping_monotonic_bounds(self, key): return start, stop def get_loc(self, key, method=None): - """Get integer location, slice or boolean mask for requested label. + """ + Get integer location, slice or boolean mask for requested label. Parameters ---------- @@ -1014,7 +1025,9 @@ def _format_with_header(self, header, **kwargs): return header + list(self._format_native_types(**kwargs)) def _format_native_types(self, na_rep='', quoting=None, **kwargs): - """ actually format my specific types """ + """ + actually format my specific types + """ from pandas.io.formats.format import IntervalArrayFormatter return IntervalArrayFormatter(values=self, na_rep=na_rep, @@ -1140,7 +1153,9 @@ def is_all_dates(self): def _is_valid_endpoint(endpoint): - """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), isinstance(endpoint, Timestamp), isinstance(endpoint, Timedelta), @@ -1148,7 +1163,9 @@ def _is_valid_endpoint(endpoint): def _is_type_compatible(a, b): - """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 ((is_number(a) and is_number(b)) or diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index c1a78b985fec9..aa166309bd560 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -309,12 +309,16 @@ def _shallow_copy(self, values=None, **kwargs): return self._simple_new(values, **attributes) def _shallow_copy_with_infer(self, values=None, **kwargs): - """ we always want to return a PeriodIndex """ + """ + we always want to return a PeriodIndex + """ return self._shallow_copy(values=values, **kwargs) @property def _box_func(self): - """Maybe box an ordinal or Period""" + """ + Maybe box an ordinal or Period + """ # TODO(DatetimeArray): Avoid double-boxing # PeriodArray takes care of boxing already, so we need to check # whether we're given an ordinal or a Period. It seems like some @@ -328,7 +332,8 @@ def func(x): return func def _maybe_box_as_values(self, values, **attribs): - """Box an array of ordinals to a PeriodArray + """ + Box an array of ordinals to a PeriodArray This is purely for compatibility between PeriodIndex and Datetime/TimedeltaIndex. Once these are all backed by @@ -509,7 +514,6 @@ def asof_locs(self, where, mask): """ where : array of timestamps mask : array of booleans where data is not NA - """ where_idx = where if isinstance(where_idx, DatetimeIndex): @@ -721,7 +725,6 @@ def _maybe_cast_slice_bound(self, label, side, kind): Notes ----- Value of `side` parameter should be validated in caller. - """ assert kind in ['ix', 'loc', 'getitem'] @@ -835,7 +838,9 @@ def _apply_meta(self, rawarr): return rawarr def __setstate__(self, state): - """Necessary for making this object picklable""" + """ + Necessary for making this object picklable + """ if isinstance(state, dict): super(PeriodIndex, self).__setstate__(state) @@ -922,7 +927,9 @@ def view(self, dtype=None, type=None): @property def flags(self): - """ return the ndarray.flags for the underlying data """ + """ + return the ndarray.flags for the underlying data + """ warnings.warn("{obj}.flags is deprecated and will be removed " "in a future version".format(obj=type(self).__name__), FutureWarning, stacklevel=2) @@ -948,7 +955,9 @@ def item(self): @property def data(self): - """ return the data pointer of the underlying data """ + """ + return the data pointer of the underlying data + """ warnings.warn("{obj}.data is deprecated and will be removed " "in a future version".format(obj=type(self).__name__), FutureWarning, stacklevel=2) @@ -956,7 +965,8 @@ def data(self): @property def base(self): - """ return the base object if the memory of the underlying data is + """ + return the base object if the memory of the underlying data is shared """ warnings.warn("{obj}.base is deprecated and will be removed " diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 1c84e592d3a0d..7654695397136 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -1,4 +1,6 @@ -""" implement the TimedeltaIndex """ +""" +implement the TimedeltaIndex +""" from datetime import datetime import warnings @@ -205,7 +207,9 @@ def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE): # ------------------------------------------------------------------- def __setstate__(self, state): - """Necessary for making this object picklable""" + """ + Necessary for making this object picklable + """ if isinstance(state, dict): super(TimedeltaIndex, self).__setstate__(state) else: @@ -213,7 +217,9 @@ def __setstate__(self, state): _unpickle_compat = __setstate__ def _maybe_update_attributes(self, attrs): - """ Update Index attributes (e.g. freq) depending on op """ + """ + Update Index attributes (e.g. freq) depending on op + """ freq = attrs.get('freq', None) if freq is not None: # no need to infer if freq is None @@ -541,7 +547,6 @@ def _maybe_cast_slice_bound(self, label, side, kind): Returns ------- label : object - """ assert kind in ['ix', 'loc', 'getitem', None] diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index 6bcf56c306e6a..e359a72062de4 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -117,7 +117,9 @@ def to_timedelta(arg, unit='ns', box=True, errors='raise'): def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'): - """Convert string 'r' to a timedelta object.""" + """ + Convert string 'r' to a timedelta object. + """ try: result = convert_to_timedelta64(r, unit) @@ -136,7 +138,9 @@ def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'): def _convert_listlike(arg, unit='ns', box=True, errors='raise', name=None): - """Convert a list of objects to a timedelta index object.""" + """ + Convert a list of objects to a timedelta index object. + """ if isinstance(arg, (list, tuple)) or not hasattr(arg, 'dtype'): # This is needed only to ensure that in the case where we end up diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 8c7d20684fd8c..1a7e51b41f7df 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -23,7 +23,9 @@ class FixedOffset(tzinfo): - """Fixed offset in minutes east from UTC.""" + """ + Fixed offset in minutes east from UTC. + """ def __init__(self, offset, name): self.__offset = timedelta(minutes=offset) @@ -1052,7 +1054,9 @@ def test_iteration_preserves_nanoseconds(self, tz): class TestDateRange(object): - """Tests for date_range with timezones""" + """ + Tests for date_range with timezones + """ def test_hongkong_tz_convert(self): # GH#1673 smoke test dr = date_range('2012-01-01', '2012-01-10', freq='D', tz='Hongkong') @@ -1105,7 +1109,9 @@ def test_date_range_with_tz(self, tzstr): class TestToDatetime(object): - """Tests for the to_datetime constructor with timezones""" + """ + Tests for the to_datetime constructor with timezones + """ def test_to_datetime_utc(self): arr = np.array([dateutil.parser.parse('2012-06-13T01:39:00Z')], dtype=object)