Pandas實現(xiàn)對日期的快速處理

Pandas日期處理的作用:將2018-01-01、1/1/2018等多種日期格式映射成統(tǒng)一的格式對象,在該對象上提供強大的功能支持


image.png

幾個概念:

  1. pd.to_datetime:pandas的一個函數(shù),能將字符串、列表、series變成日期形式
  2. Timestamp:pandas表示日期的對象形式
  3. DatetimeIndex:pandas表示日期的對象列表形式

其中:

  • DatetimeIndex是Timestamp的列表形式
  • pd.to_datetime對單個日期字符串處理會得到Timestamp
  • pd.to_datetime對日期字符串列表處理會得到DatetimeIndex
一、統(tǒng)計得到每周、每月、每季的最高溫度
1、讀取天氣數(shù)據(jù)到dataframe
import pandas as pd
import matplotlib.pyplot as plt  #畫圖需要的包

fpath = r"D:\node\nd\Pandas_study\pandas_test\beijing_tianqi_2018.csv"
df = pd.read_csv(fpath)
# 替換掉溫度的后綴℃
df.loc[:, "bWendu"] = df["bWendu"].str.replace("℃", "").astype('int32')
df.loc[:, "yWendu"] = df["yWendu"].str.replace("℃", "").astype('int32')
print(df.head())
image.png
2、將日期列轉(zhuǎn)換成pandas的日期
df.set_index(pd.to_datetime(df["ymd"]),inplace = True)
print(df.head())
print(df.index)
image.png
3、方便的對DatetimeIndex進行查詢

獲取某個日期

a = df.loc["2018-01-01"]
print(a)

image.png

日期區(qū)間

b = df.loc["2018-01-05":"2018-01-10"]
print(b)

image.png

按月份前綴篩選

c = df.loc["2018-03"].head()
print(c)

image.png

按月份區(qū)間篩選

d = df.loc["2018-07":"2018-09"].index
print(d)

image.png

按年份前綴篩選

d = df.loc["2018"].index
print(d)
image.png
4、方便的獲取周、月、季度

獲取周

a = df.index.isocalendar().week
print(a)

image.png

獲取月

b = df.index.month
print(b)

image.png

獲取季度

c = df.index.quarter
print(c)
image.png
5、統(tǒng)計每周、每月、每季的最高溫度

每周最高溫度

a = df.groupby(df.index.isocalendar().week)["bWendu"].max().head()
b = df.groupby(df.index.isocalendar().week)["bWendu"].max().plot()
plt.show()
print(a)

image.png

image.png

統(tǒng)計每個月最高溫度

b = df.groupby(df.index.month)["bWendu"].max().head()
c = df.groupby(df.index.month)["bWendu"].max().plot()
plt.show()
print(b)
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容