python天气数据分析与处理,python天气数据分析论文

python天气数据分析与处理,python天气数据分析报告 天气预报我们每天都会关注,我们可以根据未来的天气增减衣物、安排出行,每天的气温、风速风向、相对湿度、空气质量等成为关注的焦点。本次使用python中requests和BeautifulSoup库对中国天气网当天和未来14天的数据进行爬取,保存为csv文件,之后用matplotlib、numpy、pandas对数据进行可视化处理和分析,得到温湿度度变化曲线、空气质量图、风向雷达图等结果,为获得未来天气信息提供了有效方法Python解释器的安装步骤。 阅读详情

大家好,本文将围绕python天气数据分析与处理并给出结论怎么写展开说明,python 天气数据可视化的 天气预报是一个很多人都想弄明白的事情,想搞清楚python天气数据的爬取与分析需要先了解以下几个事情。

天气预报我们每天都会关注,我们可以根据未来的天气增减衣物、安排出行,每天的气温、风速风向、相对湿度、空气质量等成为关注的焦点。

本次使用python中requests和BeautifulSoup库对中国天气网当天和未来14天的数据进行爬取,保存为csv文件,之后用matplotlib、numpy、pandas对数据进行可视化处理和分析,得到温湿度度变化曲线、空气质量图、风向雷达图等结果,为获得未来天气信息提供了有效方法PythonTurtle画扇形。

1、数据获取

请求网站链接

首先查看中国天气网的网址:http://www.weather.com.cn/weather/101280701.shtml这里就访问本地的天气网址,如果想爬取不同的地区只需修改最后的101280701地区编号即可,前面的weather代表是7天的网页,weather1d代表当天,weather15d代表未来14天。这里就主要访问7天和14天的中国天气网。

采用requests.get()方法,请求网页,如果成功访问,则得到的是网页的所有字符串文本。这就是请求过程。

def getHTMLtext(url):     
 """请求获得网页内容"""
 try:         
  r = requests.get(url, timeout = 30)         
  r.raise_for_status()         
  r.encoding = r.apparent_encoding         
  print("成功访问")         
  return r.text     
 except:         
  print("访问错误")         
  return" "

提取有用信息

这里采用BeautifulSoup库对刚刚获取的字符串进行数据提取,首先对网页进行检查,找到需要获取数据的标签:

可以发现7天的数据信息在div标签中并且id=“7d”,并且日期、天气、温度、风级等信息都在ul和li标签中,所以我们可以使用BeautifulSoup对获取的网页文本进行查找div标签id=“7d”,找出他包含的所有的ul和li标签,之后提取标签中相应的数据值,保存到对应列表中。

这里要注意一个细节就是有时日期没有最高气温,对于没有数据的情况要进行判断和处理。另外对于一些数据保存的格式也要提前进行处理,比如温度后面的摄氏度符号,日期数字的提取,和风级文字的提取,这需要用到字符查找及字符串切片处理。

def get_content(html):
"""处理得到有用信息保存数据文件"""
final = []          # 初始化一个列表保存数据
bs = BeautifulSoup(html, "html.parser")  # 创建BeautifulSoup对象
body = bs.body
data = body.find('div', {'id': '7d'})    # 找到div标签且id = 7d

下面爬取当天的数据

data2 = body.find_all('div',{'class':'left-div'})
text = data2[2].find('').string 
text = text[text.index('=')+1 :-2]   # 移除改var data=将其变为json数据
jd = json.loads(text)
dayone = jd['od']['od2']     # 找到当天的数据
final_day = []           # 存放当天的数据
count = 0
for i in dayone:
temp = []
if count <=23:
temp.append(i['od21'])     # 添加时间
temp.append(i['od22'])     # 添加当前时刻温度
temp.append(i['od24'])     # 添加当前时刻风力方向
temp.append(i['od25'])     # 添加当前时刻风级
temp.append(i['od26'])     # 添加当前时刻降水量
temp.append(i['od27'])     # 添加当前时刻相对湿度
temp.append(i['od28'])     # 添加当前时刻控制质量
#print(temp)
final_day.append(temp)
count = count +1

下面爬取7天的数据

ul = data.find('ul')      # 找到所有的ul标签
li = ul.find_all('li')      # 找到左右的li标签
i = 0     # 控制爬取的天数
for day in li:          # 遍历找到的每一个li
if i < 7 and i > 0:
temp = []          # 临时存放每天的数据
date = day.find('h1').string     # 得到日期
date = date[0:date.index('日')]   # 取出日期号
temp.append(date)    

inf = day.find_all('p')      # 找出li下面的p标签,提取第一个p标签的值,即天气
temp.append(inf[0].string)


    tem_low = inf[1].find('i').string   # 找到最低气温

    if inf[1].find('span') is None:   # 天气预报可能没有最高气温
        tem_high = None
    else:
        tem_high = inf[1].find('span').string  # 找到最高气温
    temp.append(tem_low[:-1])
    if tem_high[-1] == '℃':
     temp.append(tem_high[:-1])
    else:
     temp.append(tem_high)
    wind = inf[2].find_all('span')  # 找到风向
    for j in wind:
     temp.append(j['title'])
    wind_scale = inf[2].find('i').string # 找到风级
    index1 = wind_scale.index('级')
    temp.append(int(wind_scale[index1-1:index1]))
    final.append(temp)
i = i + 1

return final_day,final

同样对于/weather15d:15天的信息,也做同样的处理,这里经过查看后发现他的15天网页中只有8-14天,前面的1-7天在/weather中,这里就分别访问两个网页将爬取得到的数据进行合并得到最终14天的数据。- 前面是未来14天的数据爬取过程,对于当天24小时的天气信息数据,经过查找发现他是一个json数据,可以通过json.loads()

方法获取当天的数据,进而对当天的天气信息进行提取。

保存csv文件

前面将爬取的数据添加到列表中,这里引入csv库,利用f_csv.writerow(header)和f_csv.writerows(data)方法,分别写入表头和每一行的数据,这里将1天和未来14天的数据分开存储,分别保存为weather1.csv和weather14.csv,下面是他们保存的表格图:

2.可视化分析

当天温度变化曲线图

采用matplotlib中plt.plot()方法绘制出一天24小时的温度变化曲线,并用plt.text()方法点出最高温和最低温,并画出平均温度线,下图为温度变化曲线图:(代码见附录)

分析可以发现这一天最高温度为33℃,最低温度为28℃,并且平均温度在20.4℃左右,通过对时间分析,发现昼夜温差5℃,低温分布在凌晨,高温分布在中午到下午的时间段。

当天相对湿度变化曲线图

采用matplotlib中plt.plot()方法绘制出一天24小时的湿度变化曲线,并画出平均相对湿度线,下图为湿

机器学习实战5-天气预测系列:利用数据集可视化分析数据,并预测某个城市的天气情况 大家好,我是微学AI,最近天气真的是多变啊,忽冷忽热,今天再次给大家带来天气的话题,机器学习实战5-天气预测系列,我们将探讨一个城市的气象数据集,并利用机器学习来预测该城市的天气状况。该数据集包含年平均温度和湿度等信息。 阅读详情

相关推荐

数据分析案例-气象数据分析

本实验主要目的是演示如何从原始数据获取信息。其中有些信息无法给出重要结论,而有些信息能够验证假设,增加我们对系统状态的认识,而找出这种信息也就意味着数据分析取得了成功。

m0_64336780的博客 8058

天气预报 :天气数据集爬取 + 可视化 + 13种模型预测

前几天一直在研究 Python 爬虫技术,只为从互联网上获取数据集。 本文就是利用前几天学到的爬虫知识使用 Python 爬取天气数据集,并做的一期讨论日期与最低气温能是否是最高气温的影响因素,进而判断能否精确预测第二天的天气情况。 由于本文开始写作与5月9日,当天想预测第二天也就是5月10日的气温数据,但由于内容较多,到10日下午才写完。所以数据预测的内容有些“陈旧”,还请读者多多包涵。 目录 1 天气数据集爬取 2 数据可视化 3 模型预测数据 3.1 单变量线性回归 模型一:单变量线性回归模型 3.2 多变量线性回归 模型二:基于LinearRegression实现的多变量线性回归模型

【昇腾】用MindIE(服务化方式)拉起glm4-9b-chat模型问题解决

【昇腾】用MindIE拉起glm4-9b-chat模型问题解决: LLMInferEngine failed to init LLMInferModels ERR: Failed to init endpoint! Please check the service log or console output. Killed make sure the folder's owner has execute permission.

u014448841的博客 5127

立创EDA + AI 生成 STM32 原理图教程1

AI辅助立创EDA设计STM32原理图教程摘要 本教程系统介绍如何利用AI工具(如Claude Code、DeepSeek等)与立创EDA专业版结合,实现STM32原理图的智能生成与优化。主要内容包括: 技术架构:采用分层设计,AI生成结构化网表数据,由立创EDA执行确定性绘图,确保可审查性 环境搭建:详细说明立创EDA专业版、Node.js等工具的安装配置 五种AI集成方案:包括官方AI Skill、MCP Server等不同实现方式 核心功能: 自动提取STM32引脚定义 智能元件选型与LCSC编号匹配

shihui2003的博客 1832

Google 人机验证(reCaptcha)无法显示解决方案

Google 人机验证无法显示解决方案第一步 安装插件Chrome/Edge 电脑版Firefox 电脑版第二步 配置插件原理参考文章 前言:为了防止机器人攻击,国外很多网站都使用了 Google reCaptcha 验证码。reCaptcha 对于国外用户非常的友好,但是… 对于国内用户就不怎么友好了。究其原因,则是国内网络全线屏蔽 Google 服务,导致 reCaptcha 完全加载不出来。这样,国内玩家就无法在对应的网站进行下一步操作了。本方案可以解决 reCaptcha 无法加载的问题。 适用

qq_40713201的博客 8万+

浏览器解析HTML的过程及编程实现

需要注意的是,上述示例代码只是简化的演示,并未涵盖浏览器解析HTML的所有细节和复杂性。实际上,浏览器的HTML解析引擎还会处理一系列的特殊情况、错误容错和性能优化等方面的内容,以确保能够正确解析各种类型的HTML代码。HTML(超文本标记语言)是构建网页的基础语言,浏览器负责将HTML代码解析并渲染成可视化的网页。本文将详细介绍浏览器解析HTML的过程,并提供相应的编程示例代码。希望以上内容能帮助您理解浏览器解析HTML的过程,并通过提供的示例代码更好地了解如何在编程中实现这一过程。

ByteJolt的博客 326

华为OD机试E卷 -猜字谜(Java & Python& JS & C++ & C )

小王设计了一个简单的猜字谜游戏,游戏的谜面是一个错误的单词,比如nesw,玩家需要猜出谜底库中正确的单词。猜中的要求如下:请你写一个程序帮忙在谜底库中找到正确的谜底。谜面是多个单词,都需要找到对应的谜底,如果找不到的话,返回”not found”

算法大师! 3491

大数据在电力行业的应用案例解析 -【电力技术】(十)电力数字化运营与大数据精准服务体系建设

电力数字化运营,是大数据在电力行业从技术场景走向业务价值的最终落点。它以数据为纽带,将用户、设备、服务、收益、风险全部纳入统一闭环,实现从 “管好电” 向 “运营好能源资产” 升级。在新型电力系统与市场化改革双重驱动下,谁能用好数据、建好闭环、做好运营,谁就能在服务、成本、效益、安全上建立长期优势。

getusushu的博客 78

嵌入式软件工程师面试题目整理(一)

文章目录嵌入式软件工程师面试题目整理(一)Arm有多少32位寄存器?Arm2440和6410有什么区别CPU,MPU,MCU,SOC,SOPC联系与差别上拉&下拉&高阻态串口协议讲一讲RS232和RS485通讯接口有什么区别IIC时序图画一下,IIC有哪些状态,给一个字节,将它发送出去。IIC有什么注意事项?有没有用I/O模拟IIC,如果有需要注意什么?为什么2440的内存起始地址是3后面7个0呢?为什么6410的内存起始地址是5后面7个0呢?内存管理有什么看法?(MMU)锁有哪些?有什么注

嵌入式与Linux那些事的博客 7886

详解Xilinx FPGA高速串行收发器GTX/GTP(6)--Pattern Generator/Pattern Checker

详解Xilinx FPGA高速串行收发器GTX/GTP(6)--Pattern Generator/Pattern Checker

孤独的单刀 1637

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 写代码python用什么笔记本,python编程用什么笔记本
下一篇: python生成可视化操作界面,python做可视化数据图表
jaskonyee
博客等级 码龄3年 7508粉丝 623原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值