Pandas时间数据处理详细教程

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Pandas时间数据处理详细教程

胡桃の壶   2023-02-03 我要评论

转化时间类型

to_datetime()方法

to_datetime()方法支持将 int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like 类型的数据转化为时间类型

import pandas as pd

# str ---> 转化为时间类型:
ret = pd.to_datetime('2022-3-9')
print(ret)
print(type(ret))
"""
2022-03-09 00:00:00
<class 'pandas._libs.tslibs.timestamps.Timestamp'>   ---pandas中默认支持的时间点的类型
"""

# 字符串的序列 --->转化成时间类型:
ret = pd.to_datetime(['2022-3-9', '2022-3-8', '2022-3-7', '2022-3-6'])
print(ret)
print(type(ret))  
"""
DatetimeIndex(['2022-03-09', '2022-03-08', '2022-03-07', '2022-03-06'], dtype='datetime64[ns]', freq=None)
<class 'pandas.core.indexes.datetimes.DatetimeIndex'> ----pandas中默认支持的时间序列的类型
"""
# dtype = 'datetime64[ns]' ----> numpy中的时间数据类型!

DatetimeIndex()方法

DatetimeIndex()方法支持将一维 类数组( array-like (1-dimensional) )转化为时间序列

# pd.DatetimeIndex 将 字符串序列 转化为 时间序列
ret = pd.DatetimeIndex(['2022-3-9', '2022-3-8', '2022-3-7', '2022-3-6'])
print(ret)
print(type(ret))
"""
DatetimeIndex(['2022-03-09', '2022-03-08', '2022-03-07', '2022-03-06'], dtype='datetime64[ns]', freq=None)
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
"""

生成时间序列

使用date_range()方法可以生成时间序列。

时间序列一般不会主动生成,往往是在发生某个事情的时候,同时记录一下发生的时间!

ret = pd.date_range(
    start='2021-10-1',  # 开始点
    # end='2022-1-1',  # 结束点
    periods=5,  # 生成的元素的个数 和结束点只需要出现一个即可!
    freq='W',  # 生成数据的步长或者频率, W表示Week(星期)
)
print(ret)
"""
DatetimeIndex(['2021-10-03', '2021-10-10', '2021-10-17', '2021-10-24', '2021-10-31'],
              dtype='datetime64[ns]', freq='W-SUN')
"""

提取时间属性

使用如下数据作为初始数据(type:<class ‘pandas.core.frame.DataFrame’>):

# 转化为 pandas支持的时间序列之后再提取时间属性!
data.loc[:, 'time_list'] = pd.to_datetime(data.loc[:, 'time_list'])

# 可以通过列表推导式来获取时间属性
# 年月日
data['year'] =  [tmp.year for tmp in data.loc[:, 'time_list']]
data['month'] = [tmp.month for tmp in data.loc[:, 'time_list']]
data['day'] =   [tmp.day for tmp in data.loc[:, 'time_list']]
# 时分秒
data['hour'] =   [tmp.hour for tmp in data.loc[:, 'time_list']]
data['minute'] = [tmp.minute for tmp in data.loc[:, 'time_list']]
data['second'] = [tmp.second for tmp in data.loc[:, 'time_list']]
# 日期
data['date'] = [tmp.date() for tmp in data.loc[:, 'time_list']]
# 时间
data['time'] = [tmp.time() for tmp in data.loc[:, 'time_list']]
print(data)

# 一年中的第多少周
data['week'] = [tmp.week for tmp in data.loc[:, 'time_list']]

# 一周中的第多少天
data['weekday'] = [tmp.weekday() for tmp in data.loc[:, 'time_list']]

# 季度
data['quarter'] = [tmp.quarter for tmp in data.loc[:, 'time_list']]

# 一年中的第多少周 ---和week是一样的
data['weekofyear'] = [tmp.weekofyear for tmp in data.loc[:, 'time_list']]

# 一周中的第多少天 ---和weekday是一样的
data['dayofweek'] = [tmp.dayofweek for tmp in data.loc[:, 'time_list']]

# 一年中第 多少天
data['dayofyear'] = [tmp.dayofyear for tmp in data.loc[:, 'time_list']]

# 周几		---返回英文全拼
data['day_name'] = [tmp.day_name() for tmp in data.loc[:, 'time_list']]

# 是否为 闰年	---返回bool类型
data['is_leap_year'] = [tmp.is_leap_year for tmp in data.loc[:, 'time_list']]

print('data:\n', data)

dt属性

Pandas还有dt属性可以提取时间属性。

data['year'] = data.loc[:, 'time_list'].dt.year
data['month'] = data.loc[:, 'time_list'].dt.month
data['day'] = data.loc[:, 'time_list'].dt.day

print('data:\n', data)

计算时间间隔

# 计算时间间隔!
ret = pd.to_datetime('2022-3-9 10:08:00') - pd.to_datetime('2022-3-8')
print(ret)  		# 1 days 10:08:00
print(type(ret))  	# <class 'pandas._libs.tslibs.timedeltas.Timedelta'>
print(ret.days)		# 1

计算时间推移

配合Timedelta()方法可计算时间推移

Timedelta 中支持的参数 weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds

res = pd.to_datetime('2022-3-9 10:08:00') + pd.Timedelta(weeks=5)
print(res)						# 2022-04-13 10:08:00
print(type(res))				# <class 'pandas._libs.tslibs.timestamps.Timestamp'>
print(pd.Timedelta(weeks=5))	# 35 days 00:00:00

获取当前机器的支持的最大时间和 最小时间

# 获取当前机器的支持的最大时间和 最小时间
print('max :',pd.Timestamp.max)
print('min :',pd.Timestamp.min)
"""
max : 2262-04-11 23:47:16.854775807
min : 1677-09-21 00:12:43.145225
"""

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们