Skip to content

CLN: fix all flake8 warnings in pandas/tseries #12075

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pandas/tseries/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"""

# flake8: noqa

from pandas.tseries.index import DatetimeIndex, date_range, bdate_range
from pandas.tseries.frequencies import infer_freq
Expand Down
86 changes: 50 additions & 36 deletions pandas/tseries/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,29 +17,28 @@
import pandas.algos as _algos



class DatelikeOps(object):
""" common ops for DatetimeIndex/PeriodIndex, but not TimedeltaIndex """

def strftime(self, date_format):
"""
Return an array of formatted strings specified by date_format, which
supports the same string format as the python standard library. Details
of the string format can be found in the `python string format doc
<https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`__
return np.asarray(self.format(date_format=date_format))
strftime.__doc__ = """
Return an array of formatted strings specified by date_format, which
supports the same string format as the python standard library. Details
of the string format can be found in `python string format doc <{0}>`__
.. versionadded:: 0.17.0
.. versionadded:: 0.17.0
Parameters
----------
date_format : str
date format string (e.g. "%Y-%m-%d")
Parameters
----------
date_format : str
date format string (e.g. "%Y-%m-%d")
Returns
-------
ndarray of formatted strings
"""
return np.asarray(self.format(date_format=date_format))
Returns
-------
ndarray of formatted strings
""".format("https://docs.python.org/2/library/datetime.html"
"#strftime-and-strptime-behavior")


class TimelikeOps(object):
Expand Down Expand Up @@ -68,7 +67,7 @@ def _round(self, freq, rounder):
unit = to_offset(freq).nanos

# round the local times
if getattr(self,'tz',None) is not None:
if getattr(self, 'tz', None) is not None:
values = self.tz_localize(None).asi8
else:
values = self.asi8
Expand All @@ -81,7 +80,7 @@ def _round(self, freq, rounder):
result = self._shallow_copy(result, **attribs)

# reconvert to local tz
if getattr(self,'tz',None) is not None:
if getattr(self, 'tz', None) is not None:
result = result.tz_localize(self.tz)
return result

Expand Down Expand Up @@ -181,7 +180,9 @@ def __getitem__(self, key):

@property
def freqstr(self):
""" return the frequency object as a string if its set, otherwise None """
"""
Return the frequency object as a string if its set, otherwise None
"""
if self.freq is None:
return None
return self.freq.freqstr
Expand Down Expand Up @@ -291,7 +292,8 @@ def _maybe_mask_results(self, result, fill_value=None, convert=None):
-------
result : ndarray with values replace by the fill_value
mask the result if needed, convert to the provided dtype if its not None
mask the result if needed, convert to the provided dtype if its not
None
This is an internal routine
"""
Expand Down Expand Up @@ -408,7 +410,7 @@ def _format_attrs(self):
freq = self.freqstr
if freq is not None:
freq = "'%s'" % freq
attrs.append(('freq',freq))
attrs.append(('freq', freq))
return attrs

@cache_readonly
Expand All @@ -424,18 +426,21 @@ def resolution(self):

def _convert_scalar_indexer(self, key, kind=None):
"""
we don't allow integer or float indexing on datetime-like when using loc
we don't allow integer or float indexing on datetime-like when using
loc
Parameters
----------
key : label of the slice bound
kind : optional, type of the indexing operation (loc/ix/iloc/None)
"""

if kind in ['loc'] and lib.isscalar(key) and (is_integer(key) or is_float(key)):
self._invalid_indexer('index',key)
if (kind in ['loc'] and lib.isscalar(key) and
(is_integer(key) or is_float(key))):
self._invalid_indexer('index', key)

return super(DatetimeIndexOpsMixin, self)._convert_scalar_indexer(key, kind=kind)
return (super(DatetimeIndexOpsMixin, self)
._convert_scalar_indexer(key, kind=kind))

def _add_datelike(self, other):
raise AbstractMethodError(self)
Expand All @@ -445,7 +450,10 @@ def _sub_datelike(self, other):

@classmethod
def _add_datetimelike_methods(cls):
""" add in the datetimelike methods (as we may have to override the superclass) """
"""
add in the datetimelike methods (as we may have to override the
superclass)
"""

def __add__(self, other):
from pandas.core.index import Index
Expand All @@ -454,14 +462,17 @@ def __add__(self, other):
if isinstance(other, TimedeltaIndex):
return self._add_delta(other)
elif isinstance(self, TimedeltaIndex) and isinstance(other, Index):
if hasattr(other,'_add_delta'):
if hasattr(other, '_add_delta'):
return other._add_delta(self)
raise TypeError("cannot add TimedeltaIndex and {typ}".format(typ=type(other)))
raise TypeError("cannot add TimedeltaIndex and {typ}"
.format(typ=type(other)))
elif isinstance(other, Index):
warnings.warn("using '+' to provide set union with datetimelike Indexes is deprecated, "
"use .union()",FutureWarning, stacklevel=2)
warnings.warn("using '+' to provide set union with "
"datetimelike Indexes is deprecated, "
"use .union()", FutureWarning, stacklevel=2)
return self.union(other)
elif isinstance(other, (DateOffset, timedelta, np.timedelta64, tslib.Timedelta)):
elif isinstance(other, (DateOffset, timedelta, np.timedelta64,
tslib.Timedelta)):
return self._add_delta(other)
elif com.is_integer(other):
return self.shift(other)
Expand All @@ -480,13 +491,16 @@ def __sub__(self, other):
return self._add_delta(-other)
elif isinstance(self, TimedeltaIndex) and isinstance(other, Index):
if not isinstance(other, TimedeltaIndex):
raise TypeError("cannot subtract TimedeltaIndex and {typ}".format(typ=type(other)))
raise TypeError("cannot subtract TimedeltaIndex and {typ}"
.format(typ=type(other)))
return self._add_delta(-other)
elif isinstance(other, Index):
warnings.warn("using '-' to provide set differences with datetimelike Indexes is deprecated, "
"use .difference()",FutureWarning, stacklevel=2)
warnings.warn("using '-' to provide set differences with "
"datetimelike Indexes is deprecated, "
"use .difference()", FutureWarning, stacklevel=2)
return self.difference(other)
elif isinstance(other, (DateOffset, timedelta, np.timedelta64, tslib.Timedelta)):
elif isinstance(other, (DateOffset, timedelta, np.timedelta64,
tslib.Timedelta)):
return self._add_delta(-other)
elif com.is_integer(other):
return self.shift(-other)
Expand Down Expand Up @@ -630,5 +644,5 @@ def summary(self, name=None):
result += '\nFreq: %s' % self.freqstr

# display as values, not quoted
result = result.replace("'","")
result = result.replace("'", "")
return result
76 changes: 48 additions & 28 deletions pandas/tseries/common.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
## datetimelike delegation ##
"""
datetimelike delegation
"""

import numpy as np
from pandas.core.base import PandasDelegate, NoNewAttributesMixin
Expand All @@ -8,20 +10,25 @@
from pandas.tseries.tdi import TimedeltaIndex
from pandas import tslib
from pandas.core.common import (_NS_DTYPE, _TD_DTYPE, is_period_arraylike,
is_datetime_arraylike, is_integer_dtype, is_list_like,
is_datetime_arraylike, is_integer_dtype,
is_list_like,
is_datetime64_dtype, is_datetime64tz_dtype,
is_timedelta64_dtype, is_categorical_dtype,
get_dtype_kinds, take_1d)


def is_datetimelike(data):
""" return a boolean if we can be successfully converted to a datetimelike """
"""
return a boolean if we can be successfully converted to a datetimelike
"""
try:
maybe_to_datetimelike(data)
return True
except (Exception):
pass
return False


def maybe_to_datetimelike(data, copy=False):
"""
return a DelegatedClass of a Series that is datetimelike
Expand All @@ -42,7 +49,8 @@ def maybe_to_datetimelike(data, copy=False):
from pandas import Series

if not isinstance(data, Series):
raise TypeError("cannot convert an object of type {0} to a datetimelike index".format(type(data)))
raise TypeError("cannot convert an object of type {0} to a "
"datetimelike index".format(type(data)))

index = data.index
name = data.name
Expand All @@ -51,22 +59,28 @@ def maybe_to_datetimelike(data, copy=False):
data = orig.values.categories

if is_datetime64_dtype(data.dtype):
return DatetimeProperties(DatetimeIndex(data, copy=copy, freq='infer'), index, name=name,
orig=orig)
return DatetimeProperties(DatetimeIndex(data, copy=copy, freq='infer'),
index, name=name, orig=orig)
elif is_datetime64tz_dtype(data.dtype):
return DatetimeProperties(DatetimeIndex(data, copy=copy, freq='infer', ambiguous='infer'),
return DatetimeProperties(DatetimeIndex(data, copy=copy, freq='infer',
ambiguous='infer'),
index, data.name, orig=orig)
elif is_timedelta64_dtype(data.dtype):
return TimedeltaProperties(TimedeltaIndex(data, copy=copy, freq='infer'), index,
return TimedeltaProperties(TimedeltaIndex(data, copy=copy,
freq='infer'), index,
name=name, orig=orig)
else:
if is_period_arraylike(data):
return PeriodProperties(PeriodIndex(data, copy=copy), index, name=name, orig=orig)
return PeriodProperties(PeriodIndex(data, copy=copy), index,
name=name, orig=orig)
if is_datetime_arraylike(data):
return DatetimeProperties(DatetimeIndex(data, copy=copy, freq='infer'), index,
return DatetimeProperties(DatetimeIndex(data, copy=copy,
freq='infer'), index,
name=name, orig=orig)

raise TypeError("cannot convert an object of type {0} to a datetimelike index".format(type(data)))
raise TypeError("cannot convert an object of type {0} to a "
"datetimelike index".format(type(data)))


class Properties(PandasDelegate, NoNewAttributesMixin):

Expand All @@ -80,7 +94,7 @@ def __init__(self, values, index, name, orig=None):
def _delegate_property_get(self, name):
from pandas import Series

result = getattr(self.values,name)
result = getattr(self.values, name)

# maybe need to upcast (ints)
if isinstance(result, np.ndarray):
Expand All @@ -97,14 +111,16 @@ def _delegate_property_get(self, name):
result = Series(result, index=self.index, name=self.name)

# setting this object will show a SettingWithCopyWarning/Error
result.is_copy = ("modifications to a property of a datetimelike object are not "
"supported and are discarded. Change values on the original.")
result.is_copy = ("modifications to a property of a datetimelike "
"object are not supported and are discarded. "
"Change values on the original.")

return result

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.")
raise ValueError("modifications to a property of a datetimelike "
"object are not supported. Change values on the "
"original.")

def _delegate_method(self, name, *args, **kwargs):
from pandas import Series
Expand All @@ -118,8 +134,9 @@ def _delegate_method(self, name, *args, **kwargs):
result = Series(result, index=self.index, name=self.name)

# setting this object will show a SettingWithCopyWarning/Error
result.is_copy = ("modifications to a method of a datetimelike object are not "
"supported and are discarded. Change values on the original.")
result.is_copy = ("modifications to a method of a datetimelike object "
"are not supported and are discarded. Change "
"values on the original.")

return result

Expand Down Expand Up @@ -205,9 +222,10 @@ class PeriodProperties(Properties):
Raises TypeError if the Series does not contain datetimelike values.
"""

PeriodProperties._add_delegate_accessors(delegate=PeriodIndex,
accessors=PeriodIndex._datetimelike_ops,
typ='property')
PeriodProperties._add_delegate_accessors(
delegate=PeriodIndex,
accessors=PeriodIndex._datetimelike_ops,
typ='property')
PeriodProperties._add_delegate_accessors(delegate=PeriodIndex,
accessors=["strftime"],
typ='method')
Expand All @@ -222,8 +240,8 @@ class CombinedDatetimelikeProperties(DatetimeProperties, TimedeltaProperties):

def _concat_compat(to_concat, axis=0):
"""
provide concatenation of an datetimelike array of arrays each of which is a single
M8[ns], datetimet64[ns, tz] or m8[ns] dtype
provide concatenation of an datetimelike array of arrays each of which is a
single M8[ns], datetimet64[ns, tz] or m8[ns] dtype
Parameters
----------
Expand Down Expand Up @@ -258,24 +276,26 @@ def convert_to_pydatetime(x, axis):
if 'datetimetz' in typs:

# we require ALL of the same tz for datetimetz
tzs = set([ getattr(x,'tz',None) for x in to_concat ])-set([None])
tzs = set([getattr(x, 'tz', None) for x in to_concat]) - set([None])
if len(tzs) == 1:
return DatetimeIndex(np.concatenate([ x.tz_localize(None).asi8 for x in to_concat ]), tz=list(tzs)[0])
return DatetimeIndex(np.concatenate([x.tz_localize(None).asi8
for x in to_concat]),
tz=list(tzs)[0])

# single dtype
if len(typs) == 1:

if not len(typs-set(['datetime'])):
if not len(typs - set(['datetime'])):
new_values = np.concatenate([x.view(np.int64) for x in to_concat],
axis=axis)
return new_values.view(_NS_DTYPE)

elif not len(typs-set(['timedelta'])):
elif not len(typs - set(['timedelta'])):
new_values = np.concatenate([x.view(np.int64) for x in to_concat],
axis=axis)
return new_values.view(_TD_DTYPE)

# need to coerce to object
to_concat = [convert_to_pydatetime(x, axis) for x in to_concat]

return np.concatenate(to_concat,axis=axis)
return np.concatenate(to_concat, axis=axis)
Loading