本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,如有問題請及時聯系我們以作處理,
以下文章來源于菜J學Python ,作者J哥
在找Python的實戰專案學習?
爬蟲、資料分析、網站開發案例講解在線觀看
https://space.bilibili.com/523606542

前言
元旦馬上就要到了,難得的3天小長假,玩肯定是要去玩的,但去哪兒玩是個問題,于是,以旅游熱門城市廈門為例,用Python獲取了去哪兒網的相關景點資料,包括景點名稱、地區、評分、銷量、價格、坐標等欄位,對資料進行可視化并作簡單分析,以求找到性價比較高的景點,
資料獲取
去哪兒網資料采集相對簡單,找到真實url后,構造引數拼接,用request請求到json資料,以追加模式將資料存盤為csv檔案即可,
爬蟲核心代碼如下:
# -*- coding = uft-8 -*- 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 = f'http://piao.qunar.com/ticket/list.json?keyword={keyword}?ion=&from=mpl_search_suggest&page={page}' res = requests.request("GET", url,headers=headers) sleep(random.uniform(1, 2)) try: res_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("/旅游/廈門旅游景點.csv",names=['name', 'star', 'score','qunarPrice','saleCount','districts','point','intro']) df.head()
洗掉重復資料
網站存在一定的重復資料,需要進行剔除,
df = 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("/data.csv")
評分TOP10景點
從景點評分來看,廈門大學評分最高,5分滿分,其次是鼓浪嶼和南普陀寺,分別為4.9分和4.6分,難怪有人說,沒去過廈大和鼓浪嶼,相當于沒來過廈門,
df_score = df.pivot_table(index='name',values='score') df_score.sort_values('score',inplace=True,ascending=False) df_score[:10]
月銷量TOP10景點
從門票月銷量來看,鼓浪嶼排第一,月銷量1230,其次是廈門園林植物園和鼓浪嶼往返輪渡,廈門方特夢幻王國也有600以上的月銷量,
df_saleCount = df.pivot_table(index='name',values='saleCount') df_saleCount.sort_values('saleCount',inplace=True,ascending=False) df_saleCount[:10]
價格TOP20景點
從景點價格來看,玩游艇、直升機、帆船類的活動花銷較大,另外,廈門方特價格也不便宜,如果對價格不敏感可以考慮,如果是窮游可以提前避開,
df_qunarPrice = df.pivot_table(index='name',values='qunarPrice') df_qunarPrice.sort_values('qunarPrice',inplace=True,ascending=False) df_qunarPrice[:20]
月銷售額TOP20景點
由于廈門近一個月景點銷量的變化幅度小于價格的變化幅度,銷售額受價格影響更大,從以下圖中也可以看出,月銷售額較大的景點仍然是游艇、方特之類,
df["saleTotal"] = df["qunarPrice"]*df["saleCount"] df_saleTotal = df.pivot_table(index='name',values='saleTotal') df_saleTotal.sort_values('saleTotal',inplace=True,ascending=False) df_saleTotal[:20]
景點等級分布
從廈門景點等級分布來看,3A以上等級景點占比不到5%,
df_star = df["star"].value_counts() df_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.消費較高的景點或活動包括游艇、帆船和方特,
溫馨提示:疫情還未完全散去,元旦游玩盡量避開風險區域,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/242693.html
標籤:Python
上一篇:DRF認證流程及原始碼分析
下一篇:Python練習題
