Skip to content

Commit 9e19d6b

Browse files
committed
ENH: add to_period method to TimeSeries to convert DatetimeIndex -> PeriodIndex
1 parent c6c1331 commit 9e19d6b

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

pandas/core/series.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2566,11 +2566,15 @@ def to_timestamp(self, freq='D', how='start', copy=True):
25662566
25672567
Parameters
25682568
----------
2569+
freq : string, default 'D'
2570+
Desired frequency
25692571
how : {'s', 'e', 'start', 'end'}
2572+
Convention for converting period to timestamp; start of period
2573+
vs. end
25702574
25712575
Returns
25722576
-------
2573-
DatetimeIndex
2577+
ts : TimeSeries with DatetimeIndex
25742578
"""
25752579
new_values = self.values
25762580
if copy:
@@ -2579,4 +2583,24 @@ def to_timestamp(self, freq='D', how='start', copy=True):
25792583
new_index = self.index.to_timestamp(freq=freq, how=how)
25802584
return Series(new_values, index=new_index, name=self.name)
25812585

2586+
def to_period(self, freq=None, copy=True):
2587+
"""
2588+
Convert TimeSeries from DatetimeIndex to PeriodIndex with desired
2589+
frequency (inferred from index if not passed)
2590+
2591+
Parameters
2592+
----------
2593+
freq : string, default
2594+
2595+
Returns
2596+
-------
2597+
ts : TimeSeries with PeriodIndex
2598+
"""
2599+
new_values = self.values
2600+
if copy:
2601+
new_values = new_values.copy()
25822602

2603+
if freq is None:
2604+
freq = self.index.freqstr or self.index.inferred_freq
2605+
new_index = self.index.to_period(freq=freq)
2606+
return Series(new_values, index=new_index, name=self.name)

pandas/tseries/tests/test_timeseries.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,19 @@ def test_normalize(self):
511511
self.assert_(result.is_normalized)
512512
self.assert_(not rng.is_normalized)
513513

514+
def test_to_period(self):
515+
from pandas.tseries.period import period_range
516+
517+
ts = _simple_ts('1/1/2000', '1/1/2001')
518+
519+
pts = ts.to_period()
520+
exp = ts.copy()
521+
exp.index = period_range('1/1/2000', '1/1/2001')
522+
assert_series_equal(pts, exp)
523+
524+
pts = ts.to_period('M')
525+
self.assert_(pts.index.equals(exp.index.asfreq('M')))
526+
514527
def _simple_ts(start, end, freq='D'):
515528
rng = date_range(start, end, freq=freq)
516529
return Series(np.random.randn(len(rng)), index=rng)

0 commit comments

Comments
 (0)