用Python對天氣預報的資料進行資料分析

2021-09-27 04:14:01 字數 2519 閱讀 9649

對天氣資料進行抓取與分析

1、對天氣資料進行抓取

import requests

from bs4 import beautifulsoup

import pandas as pd

def getaqi(url):

headers=

response=requests.get(url,headers=headers)

soup=beautifulsoup(response.text,'lxml')

table=soup.find('table')

df=pd.read_html(table.prettify(),header=0)

return df[0]

year=2018

cities=['beijing','shanghai']#,'shenzhen']

for city in cities:

dfs=

filename=city+'-'+str(year)+'-aqi.csv'

for month in range(1,3):

url=''+city+'-'+str(year)+'%02d'%month+'.html'

data=getaqi(url)

#dataframe pandas to_sql

for df in dfs:

df.to_csv(filename,header=none,encoding='utf-8-sig',mode='a')

2、對資料進行分析

首先讀取csv檔案

%matplotlib inline

import matplotlib.pyplot as plt

import pandas as pd

import numpy as np

data=pd.read_csv(r'beijing-2018-aqi.csv',names=['date','level','aqi','rank','pm25','pm10','so2','no2','co','o3'])

data

摘取某列的資料

x=data[:31].date   # data['日期']

y=data[:31].pm25

plt.plot(x,y)

對某列進行處理,python中的map會根據提供的函式對指定的序列做對映

data['month']=data.date.map(lambda x:x[5:7])

data.head(10)

進行分組

aqi_mean=data.groupby('month')['aqi'].mean()

aqi_mean

繪圖設定橫座標的值

x=np.arange(1,13)

x_ticks=['%d月'%i for i in x]

print(x_ticks)

plt.rcparams['font.sans-serif']=['simhei']

plt.rcparams['axes.unicode_minus']=false

y=np.array(aqi_mean)

plt.xticks(x,x_ticks)

plt.plot(x,y,label='aqi per month')

plt.legend()

上面的前兩行讓畫出的圖的中文得以顯示出來,而不是顯示出亂碼。

計算資料

s1=data.query('month==["01","02","03"]').pm25.mean()

s2=data.query('month==["04","05","06"]').pm25.mean()

s3=data.query('month==["07","08","09"]').pm25.mean()

s4=data.query('month==["10","11","12"]').pm25.mean()

print(s1,s2,s3,s4)

round對浮點數進行處理,第乙個引數為需要處理的資料,第二個引數為保留的位數

s2=round(s2,2)

s3=round(s3,2)

s4=round(s4,2)

print(s1,s2,s3,s4)

畫餅圖

labels=['第%d季度'%i for i in [1,2,3,4]]

labels

pms=[s1,s2,s3,s4]

plt.pie(pms,labels=labels,autopct='%1.2f%%',explode=[0,0,0,0.3],shadow=true)

plt.axis('equal')

explode是為了突出餅圖的某一部分,shadow=true讓餅圖看上去有一些厚度

python天氣預報

1.引入requests import requests def query now 查詢實時天氣 return none query city input 請輸入要查詢的城市名稱 2.準備url位址 url query city 3.發請求,接收資料 response requests.get u...

用Python做天氣預報查詢

3.1 問題 編寫乙個display weather.py指令碼,實現以下功能 1.執行程式時,螢幕將出現你所在城市各區縣名字 2.使用者指定查詢某區縣,螢幕上將出現該區縣當前的氣溫 濕度 風向 風速等 3.2 步驟 實現此案例需要按照如下步驟進行。步驟一 找到天氣資訊規律 1.首先我們想要實現的功...

天氣預報的獲取

好久沒有寫技術文章了,2010年工作太忙,奔波在國內各地,也沒什麼時間關注一些技術方面的事情,最近有乙個專案封閉開發,有些時間來寫些瑣碎的東西,就當是整理下最近的東西吧,沒什麼技術價值,純粹玩玩而已。本篇是獲取qq天氣預報資訊,獲取的是杭州的當天天氣,如果需要獲取未來三天以及其他城市的,做成配置即可...