当前位置:首页 > 系统运维

用Python分析元旦旅游热门城市

 元旦马上就要到了,用P游热难得的析元3天小长假,玩肯定是旦旅要去玩的,但去哪儿玩是门城个问题。于是用P游热,笔者以旅游热门城市厦门为例,析元用Python获取了去哪儿网的旦旅相关景点数据,包括景点名称、门城地区、用P游热评分、析元销量、旦旅价格、门城坐标等字段,用P游热对数据进行可视化并作简单分析,析元以求找到性价比较高的旦旅景点。

数据获取

去哪儿网数据采集相对简单,找到真实url后,构造参数拼接,用request请求到json数据,以追加模式将数据存储为csv文件即可。

爬虫核心代码如下: 

# -*- coding = uft-8 -*-  # @Time : 2020/12/25 9:47 下午  # @Author : 公众号 菜J学Python  # @File : 去哪儿.py  import requests  import random  from time import sleep  import csv  import pandas as pd  from fake_useragent import UserAgent  def get_data(keyword,page):      ua = UserAgent(verify_ssl=False)      headers = { "User-Agent": ua.random}      url = fhttp://piao.qunar.com/ticket/list.json?keyword={ keyword}&region=&from=mpl_search_suggest&page={ page}      res = requests.request("GET", url,headersheaders=headers)      sleep(random.uniform(1, 2))      try:          resres_json = res.json()          #print(res_json)          sight_List = res_json[data][sightList]          print(sight_List)      except:          pass  if __name__ == __main__:      keyword = "厦门"      for page in range(1,100): #控制页数          print(f"正在提取第{ page}页")          sleep(random.uniform(1, 2))          get_data(keyword,page) 

数据处理

导入相关包

首先导入数据处理和数据可视化相关第三方库,便于后续操作。 

import pandas as pd   import numpy as np  import matplotlib.pyplot as plt  import seaborn as sns  %matplotlib inline  plt.rcParams[font.sans-serif] = [SimHei]  # 设置加载的字体名  plt.rcParams[axes.unicode_minus] = False   # 解决保存图像是负号-显示为方块的问题   import jieba  import re  from pyecharts.charts import *  from pyecharts import options as opts   from pyecharts.globals import ThemeType    import stylecloud  from IPython.display import Image 

导入景点数据

用pandas读取爬取的csv格式景点数据并预览。服务器托管 

df = pd.read_csv("/菜J学Python/旅游/厦门旅游景点.csv",names=[name, star, score,qunarPrice,saleCount,districts,point,intro])  df.head() 

删除重复数据

网站存在一定的重复数据,需要进行剔除。 

dfdf = df.drop_duplicates() 

查看数据信息

查看字段类型和缺失值情况,符合分析需要,无需另作处理。 

df.info()     <class pandas.core.frame.DataFrame>     Int64Index: 422 entries, 0 to 423     Data columns (total 8 columns):      #   Column      Non-Null Count  Dtype       ---  ------      --------------  -----        0   name        422 non-null    object       1   star        422 non-null    object       2   score       422 non-null    float64      3   qunarPrice  422 non-null    float64      4   saleCount   422 non-null    int64        5   districts   422 non-null    object       6   point       422 non-null    object       7   intro       377 non-null    object      dtypes: float64(2), int64(1), object(5)     memory usage: 29.7+ KB 

描述性统计

从描述性统计表可知,剔除重复数据后,剩余424个景点,门票均价为40元。 

color_map = sns.light_palette(orange, as_cmap=True)  # light_palette调色板  df.describe().style.background_gradient(color_map) 

可视化分析

景点介绍

通过对厦门景点介绍文本进行词云图绘制,我们很容易看出厦门的特点。典型的海滨休闲城市,帆船、鼓浪屿、游艇等词被大量提及,建筑、博物馆等词也有一定提及,体现出厦门浓厚的人文气息。 

#绘制词云图  text1 = get_cut_words(content_series=df[intro])  stylecloud.gen_stylecloud(text= .join(text1), max_words=100,                            collocations=False,                            font_path=simhei.ttf,                            icon_name=fas fa-heart,                            size=653,                            #palette=matplotlib.Inferno_9,                            output_name=./offer.png)  Image(filename=./xiamen.png) 

景点分布

利用kepler.gl绘制厦门市旅游景点分布地图,同时以圆圈的大小表示门票月销量的大小,我们可以很清晰的看到,厦门市景点集中分布在思明区和湖里区,其他区域分布较为分散。尤其是思明区,门票销量遥遥领先其他区域。源码下载 

df["lon"] = df["point"].str.split(",",expand=True)[0]   df["lat"] = df["point"].str.split(",",expand=True)[1]   df.to_csv("/菜J学Python/data.csv") 

评分TOP10景点

从景点评分来看,厦门大学评分最高,5分满分。其次是鼓浪屿和南普陀寺,分别为4.9分和4.6分。难怪有人说,没去过厦大和鼓浪屿,相当于没来过厦门。 

dfdf_score = df.pivot_table(index=name,values=score)  df_score.sort_values(score,inplace=True,ascending=False)  df_score[:10] 

月销量TOP10景点

从门票月销量来看,鼓浪屿排第一,月销量1230,其次是厦门园林植物园和鼓浪屿往返轮渡。厦门方特梦幻王国也有600以上的月销量。 

dfdf_saleCount = df.pivot_table(index=name,values=saleCount)  df_saleCount.sort_values(saleCount,inplace=True,ascending=False)  df_saleCount[:10] 

价格TOP20景点

从景点价格来看,玩游艇、直升机、帆船类的活动花销较大,另外,厦门方特价格也不便宜,如果对价格不敏感可以考虑,如果是穷游可以提前避开。 

dfdf_qunarPrice = df.pivot_table(index=name,values=qunarPrice)  df_qunarPrice.sort_values(qunarPrice,inplace=True,ascending=False)  df_qunarPrice[:20] 

月销售额TOP20景点

由于厦门近一个月景点销量的变化幅度小于价格的变化幅度,销售额受价格影响更大。从以下图中也可以看出,月销售额较大的景点仍然是云南idc服务商游艇、方特之类。 

df["saleTotal"] = df["qunarPrice"]*df["saleCount"]  dfdf_saleTotal = df.pivot_table(index=name,values=saleTotal)  df_saleTotal.sort_values(saleTotal,inplace=True,ascending=False)  df_saleTotal[:20] 

景点等级分布

从厦门景点等级分布来看,3A以上等级景点占比不到5%。 

dfdf_star = df["star"].value_counts() df_stardf_star = df_star.sort_values(ascending=False)  #print(df_star)  c = (          Pie(init_opts=opts.InitOpts(theme=ThemeType.WALDEN))          .add(              "",              [list(z) for z in zip(df_star.index.to_list(),df_star.to_list())]          )          .set_global_opts(legend_opts = opts.LegendOpts(is_show = False),title_opts=opts.TitleOpts(title="景点等级分布",subtitle="数据来源:去哪儿网\n制图:菜J学Python",pos_top="0.5%",pos_left = left))          .set_series_opts(label_opts=opts.LabelOpts(formatter="{ b}:{ d}%",font_size=16))      )  c.render_notebook() 

 

df[df["star"]!=无].sort_values("star",ascending=False) 

以下为筛选出的部分3A及以上景点:

小结

通过以上简单的分析,我们大致可以获得以下几点启发: 

1.厦门是典型的海滨休闲城市,具有丰富的海洋和人文景观;

2.厦门旅游景点主要集中分布在思明区,其他区域较为分散;

3.厦门大学口碑最高,其次才是鼓浪屿;

4.鼓浪屿门票销量遥遥领先厦门其他景点;

5.消费较高的景点或活动包括游艇、帆船和方特。

温馨提示:疫情还未完全散去,元旦游玩尽量避开风险区域。 

分享到:

滇ICP备2023006006号-16