Pandas Series: dt.to_period() function
Series.dt.to_period() function
Cast to PeriodArray/Index at a particular frequency.
Converts DatetimeArray/Index to PeriodArray/Index.
Syntax:
Series.dt.to_period(self, *args, **kwargs)
Parameter:
Name | Description | Type / Default Value | Required / Optional |
---|---|---|---|
freq | One of pandas’ offset strings or an Offset object. Will be inferred by default. | str or Offset | Optional |
Returns: PeriodArray/Index
Raises: ValueError
When converting a DatetimeArray/Index with non-regular values, so that a frequency cannot be inferred.
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame({"y": [1, 2, 3]},
index=pd.to_datetime(["2019-03-31 00:00:00",
"2019-05-31 00:00:00",
"2019-08-31 00:00:00"]))
df.index.to_period("M")
Output:
PeriodIndex(['2019-03', '2019-05', '2019-08'], dtype='period[M]', freq='M')
Example - Infer the daily frequency:
Python-Pandas Code:
import numpy as np
import pandas as pd
idx = pd.date_range("2019-01-01", periods=2)
idx.to_period()
Output:
PeriodIndex(['2019-01-01', '2019-01-02'], dtype='period[D]', freq='D')
Previous: Series.dt.is_leap_year() function
Next: Series.dt.to_pydatetime() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/pandas/series/series-dt-to_period.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics