看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
pandas.DataFrame.to_period() 方法用于将 DataFrame 的时间数据转换为 Period 类型。Period 是 pandas 中用于处理周期性数据(如月份、季度、年份等)的数据类型。此方法将时间序列数据从 DatetimeIndex 转换为 PeriodIndex,以便进行周期性分析。
to_period() 方法主要用于以下数据类型:
将DataFrame从DatetimeIndex转换为PeriodIndex。以所需的频率将DataFrame从DatetimeIndex转换为PeriodIndex(如果未传递,则从索引推断)。
DataFrame.to_period(freq=None, axis=0, copy=None)
Series.to_period(freq=None, copy=None)
DatetimeIndex.to_period(*args, **kwargs)
Timestamp.to_period(freq=None)
Series.dt.to_period(*args, **kwargs)
freq (str 或 DateOffset, 默认为 None):
指定周期的频率。例如,'M' 表示按月分组,'Q' 表示按季度分组。可以选择的频率包括 'D'(天)、'M'(月)、'Q'(季度)、'Y'(年)等。
axis (int 或 str, 默认为 0):
指定转换的轴。0 表示按行进行转换,1 表示按列进行转换。如果 axis=0,则 DataFrame 的行将被转换为周期类型;如果 axis=1,则列将被转换为周期类型。
copy (bool, 默认为 None):
是否返回一个新的 DataFrame,如果为 True,则返回一个复制的 DataFrame;如果为 False 或 None,则返回原数据的视图(如果可能)。
DataFrameDataFrame,其中时间数据被转换为 PeriodIndex。to_period() 方法在以下场景中非常有用:
DatetimeIndex 转换为周期数据,以便进行周期性分析。PeriodIndex 可以简化处理。idx = pd.to_datetime(
[
"2001-03-31 00:00:00",
"2002-05-31 00:00:00",
"2003-08-31 00:00:00",
]
)
idx
'''
DatetimeIndex(['2001-03-31', '2002-05-31', '2003-08-31'],
dtype='datetime64[ns]', freq=None)
'''
idx.to_period("M")
# PeriodIndex(['2001-03', '2002-05', '2003-08'], dtype='period[M]')
对于年度频率:
idx.to_period("Y")
# PeriodIndex(['2001', '2002', '2003'], dtype='period[Y-DEC]')
idx = pd.DatetimeIndex(['2023', '2024', '2025'])
s = pd.Series([1, 2, 3], index=idx)
s = s.to_period()
s
'''
2023 1
2024 2
2025 3
Freq: Y-DEC, dtype: int64
'''
# 查看索引
s.index
# PeriodIndex(['2023', '2024', '2025'], dtype='period[Y-DEC]')
ts = pd.Timestamp('2020-03-14T15:32:52.192548651')
# 年末频率
ts.to_period(freq='Y')
# Period('2020', 'Y-DEC')
# 月末频率
ts.to_period(freq='M')
# Period('2020-03', 'M')
# 每周频率
ts.to_period(freq='W')
# Period('2020-03-09/2020-03-15', 'W-SUN')
# 季度末频率
ts.to_period(freq='Q')
# Period('2020Q1', 'Q-DEC')
假设有一个包含日期的 DataFrame,我们希望将这些日期转换为按月的周期。
import pandas as pd
# 构造示例数据
data = {
'Date': pd.date_range('2023-01-01', periods=6, freq='D'),
'Value': [10, 20, 30, 40, 50, 60]
}
df = pd.DataFrame(data)
df.set_index('Date', inplace=True)
# 将 Date 列转换为按月的周期
period_df = df.to_period(freq='M')
# 输出构造的数据和转换后的结果
print("原始数据:")
print(df)
print("\n转换后的数据:")
print(period_df)
输出:
原始数据:
Value
Date
2023-01-01 10
2023-01-02 20
2023-01-03 30
2023-01-04 40
2023-01-05 50
2023-01-06 60
转换后的数据:
Value
Date
2023-01 10
2023-01 20
2023-01 30
2023-01 40
2023-01 50
2023-01 60
在这个例子中,我们使用 to_period(freq='M') 将日期转换为按月的周期。
假设我们希望将日期数据转换为按季度的周期。
import pandas as pd
# 构造示例数据
data = {
'Date': pd.date_range('2023-01-01', periods=12, freq='M'),
'Value': range(12)
}
df = pd.DataFrame(data)
df.set_index('Date', inplace=True)
# 将 Date 列转换为按季度的周期
period_df = df.to_period(freq='Q')
# 输出构造的数据和转换后的结果
print("原始数据:")
print(df)
print("\n转换后的数据:")
print(period_df)
输出:
原始数据:
Value
Date
2023-01-31 0
2023-02-28 1
2023-03-31 2
2023-04-30 3
2023-05-31 4
2023-06-30 5
2023-07-31 6
2023-08-31 7
2023-09-30 8
2023-10-31 9
2023-11-30 10
2023-12-31 11
转换后的数据:
Value
Date
2023Q1 0
2023Q1 1
2023Q1 2
2023Q2 3
2023Q2 4
2023Q2 5
2023Q3 6
2023Q3 7
2023Q3 8
2023Q4 9
2023Q4 10
2023Q4 11
在这个例子中,我们使用 to_period(freq='Q') 将日期转换为按季度的周期。
更新时间:2024-08-11 12:07:21 标签:pandas python 时期 时间