Pandas教程-Pandas日期时间

Pandas可以为所有领域的时间序列数据提供功能。它还通过使用NumPy的datetime64和timedelta64数据类型整合了来自其他Python库(如scikits.timeseries)的大量功能。它为操作时间序列数据提供了新的功能。Pandas日期时间中执行的操作可以列举为:
- DatetimeIndex
- 日期范围生成
- 本地化和转换
- 时区处理
- 时间序列操作
时间序列工具对于数据科学应用程序非常有用,并与Python中使用的其他包一起使用。
示例1: DatetimeIndex
下面的代码生成从'5/4/2013'开始的八个日期,频率为一秒。
代码
# Python Program for Pandas datetime Library
import pandas as pd
# Create the dates with frequency
info = pd.date_range('5/4/2013', periods = 8, freq ='S')
# Display the generated sequence of dates
info
输出:
DatetimeIndex(['2013-05-04 00:00:00', '2013-05-04 00:00:01',
'2013-05-04 00:00:02', '2013-05-04 00:00:03',
'2013-05-04 00:00:04', '2013-05-04 00:00:05',
'2013-05-04 00:00:06', '2013-05-04 00:00:07'],
dtype='datetime64[ns]', freq='S')
示例2: 转换
下面的代码使用Pandas中的pd.to_datetime()函数,将具有年、月和日的单独列的DataFrame转换为单个日期时间格式。
代码
# Python Program for Pandas datetime Library
import pandas as pd
# Create a DataFrame with 'year', 'month', and 'day' columns
info = pd.DataFrame({'year': [2014, 2012],
'month': [5, 7],
'day': [20, 17]})
# Convert the DataFrame columns to datetime format
pd.to_datetime(info)
输出:
0 2014-05-20
1 2012-07-17
dtype: datetime64[ns]
示例3: 生成范围
下面的代码生成从'2017-06-04'开始的五个日期,频率为一秒。
代码
# Python Program for Pandas datetime Library
import pandas as pd
start_date = '2017-06-04'
num_periods = 5
frequency = 'S'
dates = pd.date_range(start=start_date, periods=num_periods, freq=frequency)
# Display the generated sequence of dates
dates
输出:
DatetimeIndex(['2017-06-04 00:00:00',
'2017-06-04 00:00:01',
'2017-06-04 00:00:02',
'2017-06-04 00:00:03',
'2017-06-04 00:00:04'],
dtype='datetime64[ns]', freq='S')
示例4: 本地化
下面的Python日期时间代码将由变量'dmy'表示的日期时间序列的时区本地化为UTC,使用Pandas中的tz_localize()函数。
代码
# Python Program for Pandas datetime Library
import pandas as pd
# Localize the timezone of the 'dmy' datetime sequence to UTC
info = dmy.tz_localize('UTC')
# Display the updated datetime sequence
info
输出:
DatetimeIndex(['2017-06-04 00:00:00+00:00', '2017-06-04 00:00:01+00:00',
'2017-06-04 00:00:02+00:00',
'2017-06-04 00:00:03+00:00',
'2017-06-04 00:00:04+00:00'],
dtype='datetime64[ns, UTC]', freq='S')
示例5: 时间序列操作
下面的代码用于执行时间序列操作,如滚动均值。
代码
# Python Program for Pandas datetime Library
import pandas as pd
# Create a sample DataFrame with datetime index
data = {'Value': [10, 15, 8, 12, 9]}
index = pd.date_range('2022-01-01', periods=5, freq='D')
df = pd.DataFrame(data, index=index)
# Perform rolling window calculation on the 'Value' column
rolling_mean = df['Value'].rolling(window=3).mean()
# Print the DataFrame and rolling mean values
print("DataFrame:")
print(df)
print("Rolling Mean:")
print(rolling_mean)
输出:
DataFrame:
Value
2022-01-01 10
2022-01-02 15
2022-01-03 8
2022-01-04 12
2022-01-05 9
Rolling Mean:
2022-01-01 NaN
2022-01-02 NaN
2022-01-03 11.000000
2022-01-04 11.666667
2022-01-05 9.666667
Freq: D, Name: Value, dtype: float64
结论:
Pandas库为在Python中处理日期时间数据提供了强大的功能。它提供了各种功能,以有效地处理、操作和分析日期和时间。