# dataframe + time ``` import pandas as pd ### 載入 ### path="D:\Book5.csv" # df1=pd.read_csv(path,encoding = 'unicode_escape') df1=pd.read_csv(path,encoding = 'big5') ### 民國轉西元 ### # 將日期取出前四碼(民國0110)轉int,加1911,再轉回str,置換回去 d = df1['日期'] for i in range(len(df1)): d.iloc[i]=d.iloc[i].replace(d.iloc[i][0:4], str(int(d.iloc[i][0:4]) + 1911)) ### 確認型態 ### df1['日期'].dtype ### str轉datetime ### # 1.自動化預測格式,年月日設為今天 df1['時間']=pd.to_datetime(df1['時間']) # 2.把時間依格式讀取, 但年月日被標1900-01-01 df1['時間']=pd.to_datetime(df1['時間'],format='%H:%M:%S') ### datetime轉str ### # dt.time 抽時分秒 # dt.date 抽日月年 # dt.year 抽年 ; month 抽月 ; day 抽日 df1['時間']=df1['時間'].dt.time ## 依照指定格式轉 ## # 抽日月年用date ; 抽時分秒用time df1['時間']=df1['時間'].dt.time.apply(lambda x: x.strftime('%H:%M:%S')) df1['時間']=df1['時間'].dt.date.apply(lambda x: x.strftime('%Y-%m-%d')) ### shift時間 ### ## 對於str 加上年月日 ## year_part = "2022-09-01" df1['時間'] = df1['時間'].apply(lambda x: year_part+" "+x) ## 對於datetime shift時間 ## from datetime import timedelta as td time_diff = td(days=365*5) df1['時間'] = df1['時間'].apply(lambda x: x+time_diff) # 使用df1['時間'].dt.date.apply()會順便轉成str ### 將「日期」列設置為索引。 ### df1 = df1.set_index(['日期'], drop=True) ### reset index ### df1.reset_index(inplace=True, drop=True) # 排序之後將index reset df1=df1.sort_values(['時間'],ascending=True) df1.reset_index(inplace=True, drop=True) ### 挑選日期 ### ## 把日期設為datetime型態&index後 ## # 單年 # df1['2021'] # 多年(先小後大) # df1['2020':'2021'] # 單月 # df1['2021-01'] # 單日,要用slice # df1['2021-01-04':'2021-01-04'] # series法,不好用 # s = pd.Series(df1['單價'], index=df1.index) # s['2021-01-04'] # 在某日之前,之後 # slice 好用 # df1['2013-11':] # df1[:'2022-11'] # truncate 不直觀 # df1.truncate(before = '2013-11') # 在'2013-11'之後!! # df1.truncate(after = '2022-11') # 在'2022-11'之前!! ## 把日期設為datetime型態但不是index ## # 挑單月 df1[df1['日期'].dt.month.isin([1])] # 挑1月~2月 df1[df1['日期'].dt.month.isin(range(1,3))] # 挑區間 con1=df1['日期']>='2021-01-04' con2=df1['日期']<'2021-01-05' df1[con1&con2] ### 挑選時間 ### ## 把時間設為datetime型態&index後 ## # 兩端等於都收 df1['時間']=pd.to_datetime(df1['時間']) df1 = df1.set_index(['時間'], drop=True) df1.between_time("11:30:03","12:29:47") ## 把時間設為datetime型態但不是index ## # 11點~12點 df1[df1['時間'].dt.hour.isin(range(11,13))] # 挑區間,要加上日期才能挑(參考:對於str 加上年月日) con1=df1['時間']>='2022-07-01 11:30' con2=df1['時間']<'2022-07-01 12:30' df1[con1&con2] ### 分組不統計 ### # Period(把日期歸類進 月/季/年) # M=月 Q=季 A=年 # df_period = df1.to_period('A') #按月显示,但不统计 # print(type(df_period.index)) # 请注意df.index的数据类型是DatetimeIndex; # df_peirod.index的数据类型是PeriodIndex ### 分組統計 ### # 基本統計法 : std() mean() max() min() median() # 分組法 : by周=w ; by月=M/MS(M=月尾日表示 MS=月首日表示) ; by季=Q ; 年=A/AS # df1.resample('AS').sum().head() # 常見統計概述 #df1.describe() # 組合技 # 以年統計完, 用年度表示 # df1.resample('AS').mean().to_period('A') # 挑多欄 # df1.resample('AS').mean().to_period('A')[['單價','價金']] # 挑欄by區間 # df1.resample('AS').mean().to_period('A').loc[:,'單價':'價金'] ```