日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Pandas時(shí)間數(shù)據(jù)處理詳細(xì)教程_python

作者:胡桃の壺 ? 更新時(shí)間: 2023-03-23 編程語(yǔ)言

轉(zhuǎn)化時(shí)間類型

to_datetime()方法

to_datetime()方法支持將 int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like 類型的數(shù)據(jù)轉(zhuǎn)化為時(shí)間類型

import pandas as pd

# str ---> 轉(zhuǎn)化為時(shí)間類型:
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中默認(rèn)支持的時(shí)間點(diǎn)的類型
"""

# 字符串的序列 --->轉(zhuǎn)化成時(shí)間類型:
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中默認(rèn)支持的時(shí)間序列的類型
"""
# dtype = 'datetime64[ns]' ----> numpy中的時(shí)間數(shù)據(jù)類型!

DatetimeIndex()方法

DatetimeIndex()方法支持將一維 類數(shù)組( array-like (1-dimensional) )轉(zhuǎn)化為時(shí)間序列

# pd.DatetimeIndex 將 字符串序列 轉(zhuǎn)化為 時(shí)間序列
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'>
"""

生成時(shí)間序列

使用date_range()方法可以生成時(shí)間序列。

時(shí)間序列一般不會(huì)主動(dòng)生成,往往是在發(fā)生某個(gè)事情的時(shí)候,同時(shí)記錄一下發(fā)生的時(shí)間!

ret = pd.date_range(
    start='2021-10-1',  # 開(kāi)始點(diǎn)
    # end='2022-1-1',  # 結(jié)束點(diǎn)
    periods=5,  # 生成的元素的個(gè)數(shù) 和結(jié)束點(diǎn)只需要出現(xiàn)一個(gè)即可!
    freq='W',  # 生成數(shù)據(jù)的步長(zhǎng)或者頻率, W表示W(wǎng)eek(星期)
)
print(ret)
"""
DatetimeIndex(['2021-10-03', '2021-10-10', '2021-10-17', '2021-10-24', '2021-10-31'],
              dtype='datetime64[ns]', freq='W-SUN')
"""

提取時(shí)間屬性

使用如下數(shù)據(jù)作為初始數(shù)據(jù)(type:<class ‘pandas.core.frame.DataFrame’>):

# 轉(zhuǎn)化為 pandas支持的時(shí)間序列之后再提取時(shí)間屬性!
data.loc[:, 'time_list'] = pd.to_datetime(data.loc[:, 'time_list'])

# 可以通過(guò)列表推導(dǎo)式來(lái)獲取時(shí)間屬性
# 年月日
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']]
# 時(shí)分秒
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']]
# 時(shí)間
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屬性可以提取時(shí)間屬性。

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)

計(jì)算時(shí)間間隔

# 計(jì)算時(shí)間間隔!
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

計(jì)算時(shí)間推移

配合Timedelta()方法可計(jì)算時(shí)間推移

Timedelta 中支持的參數(shù) 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

獲取當(dāng)前機(jī)器的支持的最大時(shí)間和 最小時(shí)間

# 獲取當(dāng)前機(jī)器的支持的最大時(shí)間和 最小時(shí)間
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
"""

總結(jié)

原文鏈接:https://blog.csdn.net/weixin_45760274/article/details/123484877

欄目分類
最近更新