Skip to content

Commit

Permalink
PEP cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
jreback committed Jan 12, 2016
1 parent 4437e9c commit d8203cb
Show file tree
Hide file tree
Showing 7 changed files with 166 additions and 73 deletions.
2 changes: 1 addition & 1 deletion pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -3763,7 +3763,7 @@ def test_dt_accessor_api_for_categorical(self):
('round', ("D",), {}),
('floor', ("D",), {}),
('ceil', ("D",), {}),
#('tz_localize', ("UTC",), {}),
# ('tz_localize', ("UTC",), {}),
]
_special_func_names = [f[0] for f in special_func_defs]

Expand Down
54 changes: 39 additions & 15 deletions pandas/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,25 @@ def test_dt_namespace_accessor(self):
# GH 7207
# test .dt namespace accessor

ok_for_base = ['year','month','day','hour','minute','second','weekofyear','week','dayofweek','weekday','dayofyear','quarter','freq','days_in_month','daysinmonth']
ok_for_base = ['year', 'month', 'day', 'hour', 'minute', 'second',
'weekofyear', 'week', 'dayofweek', 'weekday',
'dayofyear', 'quarter', 'freq', 'days_in_month',
'daysinmonth']
ok_for_period = ok_for_base + ['qyear']
ok_for_period_methods = ['strftime']
ok_for_dt = ok_for_base + ['date','time','microsecond','nanosecond', 'is_month_start', 'is_month_end', 'is_quarter_start',
'is_quarter_end', 'is_year_start', 'is_year_end', 'tz']
ok_for_dt_methods = ['to_period','to_pydatetime','tz_localize','tz_convert', 'normalize', 'strftime', 'round', 'floor', 'ceil']
ok_for_td = ['days','seconds','microseconds','nanoseconds']
ok_for_td_methods = ['components','to_pytimedelta','total_seconds','round', 'floor', 'ceil']
ok_for_dt = ok_for_base + ['date', 'time', 'microsecond', 'nanosecond',
'is_month_start', 'is_month_end',
'is_quarter_start', 'is_quarter_end',
'is_year_start', 'is_year_end', 'tz']
ok_for_dt_methods = ['to_period', 'to_pydatetime', 'tz_localize',
'tz_convert', 'normalize', 'strftime', 'round',
'floor', 'ceil']
ok_for_td = ['days', 'seconds', 'microseconds', 'nanoseconds']
ok_for_td_methods = ['components', 'to_pytimedelta', 'total_seconds',
'round', 'floor', 'ceil']

def get_expected(s, name):
result = getattr(Index(s._values),prop)
result = getattr(Index(s._values), prop)
if isinstance(result, np.ndarray):
if com.is_integer_dtype(result):
result = result.astype('int64')
Expand Down Expand Up @@ -141,26 +149,42 @@ def compare(s, name):
tm.assert_series_equal(result, expected)

# round
s = Series(pd.to_datetime(['2012-01-01 13:00:00', '2012-01-01 12:01:00', '2012-01-01 08:00:00']))
s = Series(pd.to_datetime(['2012-01-01 13:00:00',
'2012-01-01 12:01:00',
'2012-01-01 08:00:00']))
result = s.dt.round('D')
expected = Series(pd.to_datetime(['2012-01-02', '2012-01-02', '2012-01-01']))
expected = Series(pd.to_datetime(['2012-01-02',
'2012-01-02',
'2012-01-01']))
tm.assert_series_equal(result, expected)

# round with tz
result = s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern').dt.round('D')
expected = Series(pd.to_datetime(['2012-01-01', '2012-01-01', '2012-01-01']).tz_localize('US/Eastern'))
result = s.dt.tz_localize('UTC').dt.tz_convert(
'US/Eastern').dt.round('D')
expected = Series(pd.to_datetime(['2012-01-01',
'2012-01-01',
'2012-01-01']
).tz_localize('US/Eastern'))
tm.assert_series_equal(result, expected)

# floor
s = Series(pd.to_datetime(['2012-01-01 13:00:00', '2012-01-01 12:01:00', '2012-01-01 08:00:00']))
s = Series(pd.to_datetime(['2012-01-01 13:00:00',
'2012-01-01 12:01:00',
'2012-01-01 08:00:00']))
result = s.dt.floor('D')
expected = Series(pd.to_datetime(['2012-01-01', '2012-01-01', '2012-01-01']))
expected = Series(pd.to_datetime(['2012-01-01',
'2012-01-01',
'2012-01-01']))
tm.assert_series_equal(result, expected)

# ceil
s = Series(pd.to_datetime(['2012-01-01 13:00:00', '2012-01-01 12:01:00', '2012-01-01 08:00:00']))
s = Series(pd.to_datetime(['2012-01-01 13:00:00',
'2012-01-01 12:01:00',
'2012-01-01 08:00:00']))
result = s.dt.ceil('D')
expected = Series(pd.to_datetime(['2012-01-02', '2012-01-02', '2012-01-02']))
expected = Series(pd.to_datetime(['2012-01-02',
'2012-01-02',
'2012-01-02']))
tm.assert_series_equal(result, expected)

# datetimeindex with tz
Expand Down
13 changes: 8 additions & 5 deletions pandas/tseries/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def strftime(self, date_format):
"""
return np.asarray(self.format(date_format=date_format))


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

Expand All @@ -60,6 +61,7 @@ class TimelikeOps(object):
------
ValueError if the freq cannot be converted
""")

def _round(self, freq, rounder):

from pandas.tseries.frequencies import to_offset
Expand All @@ -70,7 +72,7 @@ def _round(self, freq, rounder):
values = self.tz_localize(None).asi8
else:
values = self.asi8
result = (unit*rounder(values/float(unit))).astype('i8')
result = (unit * rounder(values / float(unit))).astype('i8')
attribs = self._get_attributes_dict()
if 'freq' in attribs:
attribs['freq'] = None
Expand All @@ -82,18 +84,19 @@ def _round(self, freq, rounder):
if getattr(self,'tz',None) is not None:
result = result.tz_localize(self.tz)
return result

@Appender(_round_doc % "round")
def round(self, freq):
return self._round(freq, np.round)
return self._round(freq, np.round)

@Appender(_round_doc % "floor")
def floor(self, freq):
return self._round(freq, np.floor)
return self._round(freq, np.floor)

@Appender(_round_doc % "floor")
def ceil(self, freq):
return self._round(freq, np.ceil)
return self._round(freq, np.ceil)


class DatetimeIndexOpsMixin(object):
""" common ops mixin to support a unified inteface datetimelike Index """
Expand Down
32 changes: 19 additions & 13 deletions pandas/tseries/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,13 +141,16 @@ class DatetimeProperties(Properties):
def to_pydatetime(self):
return self.values.to_pydatetime()

DatetimeProperties._add_delegate_accessors(delegate=DatetimeIndex,
accessors=DatetimeIndex._datetimelike_ops,
typ='property')
DatetimeProperties._add_delegate_accessors(delegate=DatetimeIndex,
accessors=["to_period","tz_localize","tz_convert",
"normalize","strftime","round", "floor", "ceil"],
typ='method')
DatetimeProperties._add_delegate_accessors(
delegate=DatetimeIndex,
accessors=DatetimeIndex._datetimelike_ops,
typ='property')
DatetimeProperties._add_delegate_accessors(
delegate=DatetimeIndex,
accessors=["to_period", "tz_localize", "tz_convert",
"normalize", "strftime", "round", "floor", "ceil"],
typ='method')


class TimedeltaProperties(Properties):
"""
Expand Down Expand Up @@ -178,12 +181,15 @@ def components(self):
"""
return self.values.components.set_index(self.index)

TimedeltaProperties._add_delegate_accessors(delegate=TimedeltaIndex,
accessors=TimedeltaIndex._datetimelike_ops,
typ='property')
TimedeltaProperties._add_delegate_accessors(delegate=TimedeltaIndex,
accessors=["to_pytimedelta", "total_seconds", "round", "floor", "ceil"],
typ='method')
TimedeltaProperties._add_delegate_accessors(
delegate=TimedeltaIndex,
accessors=TimedeltaIndex._datetimelike_ops,
typ='property')
TimedeltaProperties._add_delegate_accessors(
delegate=TimedeltaIndex,
accessors=["to_pytimedelta", "total_seconds", "round", "floor", "ceil"],
typ='method')


class PeriodProperties(Properties):
"""
Expand Down
66 changes: 52 additions & 14 deletions pandas/tseries/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -1469,23 +1469,61 @@ def _set_freq(self, value):
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")
microsecond = _field_accessor('microsecond', 'us', "The microseconds of the datetime")
nanosecond = _field_accessor('nanosecond', 'ns', "The nanoseconds of the datetime")
weekofyear = _field_accessor('weekofyear', 'woy', "The week ordinal of the year")
microsecond = _field_accessor(
'microsecond',
'us',
"The microseconds of the datetime")
nanosecond = _field_accessor(
'nanosecond',
'ns',
"The nanoseconds of the datetime")
weekofyear = _field_accessor(
'weekofyear',
'woy',
"The week ordinal of the year")
week = weekofyear
dayofweek = _field_accessor('dayofweek', 'dow',
"The day of the week with Monday=0, Sunday=6")
dayofweek = _field_accessor(
'dayofweek',
'dow',
"The day of the week with Monday=0, Sunday=6")
weekday = dayofweek
dayofyear = _field_accessor('dayofyear', 'doy', "The ordinal day of the year")
quarter = _field_accessor('quarter', 'q', "The quarter of the date")
days_in_month = _field_accessor('days_in_month', 'dim', "The number of days in the month\n\n.. versionadded:: 0.16.0")
dayofyear = _field_accessor(
'dayofyear',
'doy',
"The ordinal day of the year")
quarter = _field_accessor(
'quarter',
'q',
"The quarter of the date")
days_in_month = _field_accessor(
'days_in_month',
'dim',
"The number of days in the month\n\n.. versionadded:: 0.16.0")
daysinmonth = days_in_month
is_month_start = _field_accessor('is_month_start', 'is_month_start', "Logical indicating if first day of month (defined by frequency)")
is_month_end = _field_accessor('is_month_end', 'is_month_end', "Logical indicating if last day of month (defined by frequency)")
is_quarter_start = _field_accessor('is_quarter_start', 'is_quarter_start', "Logical indicating if first day of quarter (defined by frequency)")
is_quarter_end = _field_accessor('is_quarter_end', 'is_quarter_end', "Logical indicating if last day of quarter (defined by frequency)")
is_year_start = _field_accessor('is_year_start', 'is_year_start', "Logical indicating if first day of year (defined by frequency)")
is_year_end = _field_accessor('is_year_end', 'is_year_end', "Logical indicating if last day of year (defined by frequency)")
is_month_start = _field_accessor(
'is_month_start',
'is_month_start',
"Logical indicating if first day of month (defined by frequency)")
is_month_end = _field_accessor(
'is_month_end',
'is_month_end',
"Logical indicating if last day of month (defined by frequency)")
is_quarter_start = _field_accessor(
'is_quarter_start',
'is_quarter_start',
"Logical indicating if first day of quarter (defined by frequency)")
is_quarter_end = _field_accessor(
'is_quarter_end',
'is_quarter_end',
"Logical indicating if last day of quarter (defined by frequency)")
is_year_start = _field_accessor(
'is_year_start',
'is_year_start',
"Logical indicating if first day of year (defined by frequency)")
is_year_end = _field_accessor(
'is_year_end',
'is_year_end',
"Logical indicating if last day of year (defined by frequency)")

@property
def time(self):
Expand Down
60 changes: 41 additions & 19 deletions pandas/tseries/tests/test_timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,35 +225,57 @@ def test_round(self):
self.assertEqual(r2, s2)

# invalid
for freq in ['Y','M','foobar']:
self.assertRaises(ValueError, lambda : t1.round(freq))
for freq in ['Y', 'M', 'foobar']:
self.assertRaises(ValueError, lambda: t1.round(freq))

t1 = timedelta_range('1 days',periods=3,freq='1 min 2 s 3 us')
t2 = -1*t1
t1a = timedelta_range('1 days',periods=3,freq='1 min 2 s')
t1b = timedelta_range('1 days',periods=3,freq='1 min')
t1c = pd.TimedeltaIndex([1,1,1],unit='D')
t1 = timedelta_range('1 days', periods=3, freq='1 min 2 s 3 us')
t2 = -1 * t1
t1a = timedelta_range('1 days', periods=3, freq='1 min 2 s')
t1c = pd.TimedeltaIndex([1, 1, 1], unit='D')

# note that negative times round DOWN! so don't give whole numbers
for (freq, s1, s2) in [('N', t1, t2),
('U', t1, t2),
('L', t1a, TimedeltaIndex(['-1 days +00:00:00', '-2 days +23:58:58', '-2 days +23:57:56'],
dtype='timedelta64[ns]', freq=None)),
('S', t1a, TimedeltaIndex(['-1 days +00:00:00', '-2 days +23:58:58', '-2 days +23:57:56'],
dtype='timedelta64[ns]', freq=None)),
('12T', t1c, TimedeltaIndex(['-1 days', '-1 days', '-1 days'],
dtype='timedelta64[ns]', freq=None)),
('H', t1c, TimedeltaIndex(['-1 days', '-1 days', '-1 days'],
dtype='timedelta64[ns]', freq=None)),
('d', t1c, pd.TimedeltaIndex([-1,-1,-1],unit='D'))]:
('L', t1a,
TimedeltaIndex(['-1 days +00:00:00',
'-2 days +23:58:58',
'-2 days +23:57:56'],
dtype='timedelta64[ns]',
freq=None)
),
('S', t1a,
TimedeltaIndex(['-1 days +00:00:00',
'-2 days +23:58:58',
'-2 days +23:57:56'],
dtype='timedelta64[ns]',
freq=None)
),
('12T', t1c,
TimedeltaIndex(['-1 days',
'-1 days',
'-1 days'],
dtype='timedelta64[ns]',
freq=None)
),
('H', t1c,
TimedeltaIndex(['-1 days',
'-1 days',
'-1 days'],
dtype='timedelta64[ns]',
freq=None)
),
('d', t1c,
pd.TimedeltaIndex([-1, -1, -1], unit='D')
)]:

r1 = t1.round(freq)
tm.assert_index_equal(r1, s1)
r2 = t2.round(freq)
tm.assert_index_equal(r2, s2)
tm.assert_index_equal(r2, s2)

# invalid
for freq in ['Y','M','foobar']:
self.assertRaises(ValueError, lambda : t1.round(freq))
for freq in ['Y', 'M', 'foobar']:
self.assertRaises(ValueError, lambda: t1.round(freq))

def test_repr(self):

Expand Down
12 changes: 6 additions & 6 deletions pandas/tseries/tests/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def test_indexing(self):
expected = ts['2001']
expected.name = 'A'

df.loc['2001','A'] = 1
df.loc['2001', 'A'] = 1

result = df['2001']['A']
assert_series_equal(expected, result)
Expand Down Expand Up @@ -2805,9 +2805,9 @@ def test_round(self):
expected = Timestamp('20130104 12:30:00')
self.assertEqual(result, expected)

dti = date_range('20130101 09:10:11',periods=5)
dti = date_range('20130101 09:10:11', periods=5)
result = dti.round('D')
expected = date_range('20130101',periods=5)
expected = date_range('20130101', periods=5)
tm.assert_index_equal(result, expected)

# floor
Expand All @@ -2823,12 +2823,12 @@ def test_round(self):
self.assertEqual(result, expected)

# round with tz
dt = Timestamp('20130101 09:10:11',tz='US/Eastern')
dt = Timestamp('20130101 09:10:11', tz='US/Eastern')
result = dt.round('D')
expected = Timestamp('20130101',tz='US/Eastern')
expected = Timestamp('20130101', tz='US/Eastern')
self.assertEqual(result, expected)

dt = Timestamp('20130101 09:10:11',tz='US/Eastern')
dt = Timestamp('20130101 09:10:11', tz='US/Eastern')
result = dt.round('s')
self.assertEqual(result, dt)

Expand Down

0 comments on commit d8203cb

Please sign in to comment.