此次分享一個分析連續型數據的案例。目前市場上會常用此方法去觀察金融數據,銷量數據等問題的分析。 數據真實,採集自某網站。
這裏拿過來的數據,時間字段是分開了,首先做了個預處理,把時間整合下,並添加到“datetime”字段中。然後,再以datetime爲索引,“PM_US Post”爲目標值,生成一個新的二維數組。接着進行畫圖,在畫圖的時候,發現數據太離散了,效果不好,於是進行了降採集,以星期爲單位,每個信息的目標值爲去這個星期裏的數據的平均值。數據中缺失值的地方,這裏採用刪除的方法進行處理。然後再進行繪製.
import pandas as pd
from matplotlib import pyplot as plt
file_path="./BeijingPM20100101_20151231.csv"
def Handledata(file_path):
df =pd.read_csv(file_path)
print(df.head(1))
# print(df.info())
#把分開的時間字符串通過periodindex的方法轉化爲pandas的時間類型
period=pd.PeriodIndex(year=df['year'],month=df['month'],day=df['day'],hour=df['hour'],freq='H')
df['datetime']=period
#print(df.head(1))
# print(period)
# print(type(period))
#把datetime設置爲索引
df.set_index("datetime",inplace=True)
#進行降採集
df=df.resample("7D").mean()
print(df.shape)
#處理缺失數據,刪除缺失數據
print(df['PM_US Post'])
data=df['PM_US Post'].dropna()
return data
def Draw(data,):
_x =data.index
_x = [i.strftime("%Y%m%d") for i in _x]
_y=data.values
plt.figure(figsize=(20,8),dpi=80)
plt.plot(range(len(_x)),_y,label='us_post')
plt.xticks(range(0,len(_x),10),list(_x)[::10],rotation=45)
if __name__ == '__main__':
data=Handledata(file_path)
Draw(data)
plt.legend()
plt.show()
原始數據樣式:
添加datetime字段後爲:
以datetime爲索引,PM_US Post爲目標值,再按星期降維採集後的樣式:
最後運行結果:
這個是關於pm2.5的數據,大致可以看出 每年冬天的時候,pm2.5 危害最大,所以 冬天的時候,出門得戴口罩哦!