python Pandas時序數據處理
Python中時間的一些常用操作
import time # 從格林威治時間到現在,單位秒 print('系統(tǒng)時間戳:', time.time()) print('本地時間按格式轉成str:', time.strftime('%Y-%m-%d %X', time.localtime())) # 無參的localtime返回time.struct_time格式的時間,是本地時區(qū)的時間 print('無參localtime:', time.localtime()) print('本時區(qū)時間轉成時間戳:', time.mktime(time.localtime())) # 將時間戳轉換為能讀懂的時間 print('時間戳轉時間:', time.strftime('%Y-%m-%d %X', time.localtime(time.time())))
運行結果:
系統(tǒng)時間戳: 1542188096.1592166
本地時間按格式轉成str: 2018-11-14 17:34:56
無參localtime: time.struct_time(tm_year=2018, tm_mon=11, tm_mday=14, tm_hour=17, tm_min=34, tm_sec=56, tm_wday=2, tm_yday=318, tm_isdst=0)
本時區(qū)時間轉成時間戳: 1542188096.0
時間戳轉時間: 2018-11-14 17:34:56
Pandas時間序列(DatetimeIndex)與時序數據
時間序列在Series對象中且作為索引存在時,就構成了時序數據。
import datetime import numpy as np import pandas as pd # pd.date_range()函數用于創(chuàng)建一個Pandas時間序列DatetimeIndex # start參數(也是第一個參數)傳入一個str格式的開始時間,也可以傳入一個datetime對象 # 這里用datetime.datetime()創(chuàng)建了一個datetime對象,只用了前三個參數也就是年月日 # pd.date_range()函數可以指明end表示時間序列的結尾時間 # 這里用periods參數指明序列中要生成的時間的個數,freq='D'指定為每天(Day)生成一個時間 dti = pd.date_range(start=datetime.datetime(2018, 11, 14), periods=18, freq='D') print(dti, '\n', '*' * 40, sep='') # 將時間序列放在Series對象中作為索引,這里freq='W'表示隔一周生成一個 s_dti = pd.Series(np.arange(6), index=pd.date_range('2018/11/4', periods=6, freq='W')) print(s_dti.head(), '\n', '*' * 40, sep='') # 取時序數據中指定時間的內容 print(s_dti['2018-11-25'], '\n', '*' * 40, sep='') # 取第二個索引對應的時間的年月日 print(s_dti.index[2].year, s_dti.index[2].month, s_dti.index[2].day, '\n', '*' * 40, sep='')
運行結果:
DatetimeIndex(['2018-11-14', '2018-11-15', '2018-11-16', '2018-11-17',
'2018-11-18', '2018-11-19', '2018-11-20', '2018-11-21',
'2018-11-22', '2018-11-23', '2018-11-24', '2018-11-25',
'2018-11-26', '2018-11-27', '2018-11-28', '2018-11-29',
'2018-11-30', '2018-12-01'],
dtype='datetime64[ns]', freq='D')
****************************************
2018-11-04 0
2018-11-11 1
2018-11-18 2
2018-11-25 3
2018-12-02 4
Freq: W-SUN, dtype: int32
****************************************
3
****************************************
20181118
****************************************
杭州天氣的時序處理
import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt df = pd.read_csv('E:/Data/practice/hz_weather.csv') df = df[['日期', '最高氣溫', '最低氣溫']] # print(df.head())
print(type(df.日期)) # <class 'pandas.core.series.Series'> print(type(df.日期.values)) # <class 'numpy.ndarray'> # 修改日期格式 # 注意,df.日期得到的是Series對象,df.日期.values得到的是ndarray多維數組 # pd.to_datetime()函數將輸入解析成時間對象的格式并返回 # format參數指定解析的方式 # 當輸入列表形式的值時,返回DatetimeIndex;當輸入Series時,返回Series;當輸入常量時,返回Timestamp print(type(pd.to_datetime(df.日期.values, format="%Y-%m-%d"))) # <class 'pandas.core.indexes.datetimes.DatetimeIndex'> print(type(pd.to_datetime(df.日期, format="%Y-%m-%d"))) # <class 'pandas.core.series.Series'> df.日期 = pd.to_datetime(df.日期.values, format="%Y-%m-%d") # print(df.head())
# 將日期設置為索引 df = df.set_index('日期') # 取出第0個索引值對應的日期 print(df.index[0]) # 2017-01-01 00:00:00 # DatetimeIndex里存的是一個個的Timestamp,查看一下類型 print(type(df.index[0])) # <class 'pandas._libs.tslibs.timestamps.Timestamp'> # print(df.info())
# 提取1月份的溫度數據 df_jan = df[(df.index >= "2017-1-1") & (df.index < "2017-2-1")] # 或用這種方式也可以 df_jan = df["2017-1-1":"2017-1-31"] # print(df_jan.info())
# 只取到月份 df_m = df.to_period('M') # print(df_m.head())
# 利用上面的只取到月份,對level=0(即索引層級)做聚合就可以求月內的平均值等 s_m_mean = df_m.groupby(level=0).mean() # print(s_m_mean.head())
# 繪制[最高溫度]和[最低溫度]兩個指標隨著索引[時間]變化的圖 fig, ax = plt.subplots(1, 1, figsize=(12, 4)) df.plot(ax=ax) plt.show()
附:matplotlib中文支持
到此這篇關于python Pandas時序數據處理 的文章就介紹到這了,更多相關Pandas 時序數據 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python實現在PyPI上發(fā)布自定義軟件包的方法詳解
在Python中我們經常使用pip來安裝第三方Python軟件包,其實我們每個人都可以免費地將自己寫的Python包發(fā)布到PyPI上。本文我們就將詳細介紹如何發(fā)布測試包,需要的可以參考一下2022-06-06Python中字典創(chuàng)建、遍歷、添加等實用操作技巧合集
這篇文章主要介紹了Python中字典創(chuàng)建、遍歷、添加等實用操作技巧合集,本文講解了字典中常見方法列表、創(chuàng)建字典的五種方法、字典中鍵值遍歷方法等內容,需要的朋友可以參考下2015-06-06selenium+python實現自動登陸QQ郵箱并發(fā)送郵件功能
這篇文章主要介紹了selenium+python實現自動登陸QQ郵箱并發(fā)送郵件功能,本文給大家分享完整實例代碼,需要的朋友可以參考下2019-12-12Python編程ContextManager上下文管理器講解
這篇文章主要介紹了Python編程中對Context Manager上下文管理器的詳解說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-09-09python中requests庫+xpath+lxml簡單使用
這篇文章主要介紹了python中requests庫+xpath+lxml簡單使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04