注:这里使用的是pyecharts1.7版本
一、数据清洗
1、导入模块
import jieba
import jieba
.analyse
import pandas
as pd
import numpy
as np
import re
from pyecharts
.charts
import Line
import matplotlib
.pyplot
as plt
from pyecharts
.charts
import *
from pyecharts
import options
as opts
from pyecharts
.globals import ThemeType
import stylecloud
from IPython
.display
import Image```
```python
data
= pd
.read_csv
('Travel.csv')
data
3、删除重复项
data
.drop_duplicates
(inplace
=True)
4、观察每列数据
地点、短评、出发时间、天数、人均费用、人物、玩法、浏览量
data
['地点'].value_counts
()
data
['天数'].value_counts
()
5、使用isin()逆函数过滤脏数据
通过查询数据发现,地点,天数中出现不同类型的脏数据,然后通过ison进行过滤
data
= data
[~data
['天数'].isin
(['99+'])]
data
= data
[~data
['地点'].isin
(['攻略'])]
data
= data
[~data
['天数'].isin
(['天数'])]
data
6、转换数据类型
在处理数据的时候发现数据类型的不同,然后进行了数据转换
data
['天数'] = data
['天数'].astype
(int)
data
['人均费用'] = data
['人均费用'].astype
(int)
7、重置索引
去重,过滤后进行重置索引
data
= data
.reset_index
(drop
=True)
data
8、分割出发时间,新建列旅游月份
def Month(e
):
m
= str(e
).split
('/')[2]
if m
=='01':
return '一月'
if m
=='02':
return '二月'
if m
=='03':
return '三月'
if m
=='04':
return '四月'
if m
=='05':
return '五月'
if m
=='06':
return '六月'
if m
=='07':
return '七月'
if m
=='08':
return '八月'
if m
=='09':
return '九月'
if m
=='10':
return '十月'
if m
=='11':
return '十一月'
if m
=='12':
return '十二月'
新增一列旅游月份
data
['旅行月份'] = data
['出发时间'].apply(Month
)
data
['旅行月份']
data
['出发时间']=pd
.to_datetime
(data
['出发时间'])
data
9、定义函数,统一旅游量的结构
def Look(e
):
if '万' in e
:
num1
= re
.findall
('(.*?)万',e
)
return float(num1
[0])*10000
else:
return float(e
)
data
['浏览次数'] = data
['浏览量'].apply(Look
)
data
.drop
(['浏览量'],axis
= 1,inplace
= True)
data
['浏览次数'] = data
['浏览次数'].astype
(int)
data
.head
()
二、 绘制图表
1、目的地前十的人均费用
data1
= data
data1
['地点'].value_counts
().head
(10)
loc
= data1
['地点'].value_counts
().head
(10).index
.tolist
()
print(loc
)
loc_data
= data1
[data1
['地点'].isin
(loc
)]
price_mean
= round(loc_data
['人均费用'].groupby
(loc_data
['地点']).mean
(),1)
print(price_mean
)
price_mean2
= [1670.7,1698.8,1864.4,1790.1,1516.2,2031.8,1946.9,1239.4,1651.2,1720.6]
bar
= Bar
(init_opts
=opts
.InitOpts
(theme
=ThemeType
.CHALK
,bg_color
='#040f3c'))
bar
.add_xaxis
(loc
)
bar
.add_yaxis
("",price_mean2
)
bar
.set_global_opts
(title_opts
=opts
.TitleOpts
(title
="目的地Top10人均费用",subtitle
="数据来源:去哪儿网",pos_top
="2%",pos_left
= 'center'),
xaxis_opts
=opts
.AxisOpts
(axislabel_opts
=opts
.LabelOpts
(font_size
=16,color
='white')),
yaxis_opts
=opts
.AxisOpts
(axislabel_opts
=opts
.LabelOpts
(font_size
=16,color
='white'))
)
bar
.set_series_opts
(label_opts
=opts
.LabelOpts
(font_size
=16,position
='top',color
='white'),
itemstyle_opts
=opts
.ItemStyleOpts
(color
='#0000ff'),
)
bar
.render_notebook
()
2、出游方式占比
person
=data1
['人物'].value_counts
()[:7]
person_zip
=[i
for i
in zip(person
.index
.tolist
(),person
.values
.tolist
())]
person_zip
piel
=Pie
(init_opts
=opts
.InitOpts
(theme
=ThemeType
.CHALK
,bg_color
='#040f3c'))
piel
.add
("",person_zip
,radius
=['35%','60%'])
piel
.set_colors
(["white", "green", "yellow", "red", "pink", "orange", " gold"])
piel
.set_global_opts
(title_opts
=opts
.TitleOpts
(title
="出游方式占比",subtitle
="数据来源:去哪儿网",pos_top
="2%",pos_left
= 'center'),
legend_opts
=opts
.LegendOpts
(orient
='vertical',pos_top
='15%',pos_left
='2%'),
)
piel
.set_series_opts
(label_opts
=opts
.LabelOpts
(formatter
="{b}: {c}"))
piel
.render_notebook
()
3、目的地的热度
m2
= data1
['地点'].value_counts
().head
(10).index
.tolist
()
n2
= data1
['地点'].value_counts
().head
(10).values
.tolist
()
bar
= Bar
(init_opts
=opts
.InitOpts
(theme
=ThemeType
.CHALK
,bg_color
='#040f3c'))
bar
.add_xaxis
(m2
)
bar
.add_yaxis
("",n2
)
bar
.set_global_opts
(title_opts
=opts
.TitleOpts
(title
="目的地TOP10",subtitle
="数据来源:去哪儿网",pos_top
="2%",pos_left
= 'center'),
xaxis_opts
=opts
.AxisOpts
(axislabel_opts
=opts
.LabelOpts
(font_size
=16,color
='white')),
yaxis_opts
=opts
.AxisOpts
(axislabel_opts
=opts
.LabelOpts
(font_size
=16,color
='white'))
)
bar
.set_series_opts
(label_opts
=opts
.LabelOpts
(font_size
=16,position
='top',color
='white'),
itemstyle_opts
=opts
.ItemStyleOpts
(color
='#0000ff'),
)
bar
.render_notebook
()
4、出游玩法
word_list
= []
for i
in data1
['玩法']:
s
= re
.split
('\xa0',i
)
word_list
.append
(s
)
dict = {}
for j
in range(len(word_list
)):
for i
in word_list
[j
]:
if i
not in dict:
dict[i
] = 1
else:
dict[i
]+=1
list = []
for item
in dict.items
():
list.append
(item
)
for i
in range(1,len(list)):
for j
in range(0,len(list)-1):
if list[j
][1]<list[j
+1][1]:
list[j
],list[j
+1] = list[j
+1],list[j
]
print(list)
形成列表
m5
= []
n5
= []
for i
in range(20):
m5
.append
(list[i
][0])
n5
.append
(list[i
][1])
m5
.reverse
()
m6
= m5
n5
.reverse
()
n6
= n5
bar
= Bar
(init_opts
=opts
.InitOpts
(theme
=ThemeType
.CHALK
,bg_color
='#040f3c'))
bar
.add_xaxis
(m5
)
bar
.add_yaxis
("",n5
)
bar
.set_global_opts
(title_opts
=opts
.TitleOpts
(title
="出游玩法",subtitle
="数据来源:去哪儿网",pos_top
="2%",pos_left
= 'center'),
xaxis_opts
=opts
.AxisOpts
(axislabel_opts
=opts
.LabelOpts
(font_size
=14,color
='white')),
yaxis_opts
=opts
.AxisOpts
(axislabel_opts
=opts
.LabelOpts
(font_size
=14,color
='white'))
)
bar
.set_series_opts
(label_opts
=opts
.LabelOpts
(font_size
=16,position
='right',color
='white'),
itemstyle_opts
=opts
.ItemStyleOpts
(color
='#0000ff'),
)
bar
.reversal_axis
()
bar
.render_notebook
()
分割短评形成简介一列
punc
= '~`!#$%^&*()_+-=|\';":/.,?><~·!@#¥%……&*()——+-=“:’;、。,?》《{}【】'
def remove_fuhao(e
):
short
= re
.sub
(r
"[%s]+" % punc
, " ", e
)
return short
def cut_word(text
):
text
= jieba
.cut_for_search
(str(text
))
return ' '.join
(text
)
data2
= data1
data2
['简介'] = data2
['短评'].apply(remove_fuhao
).apply(cut_word
)
data2
.head
()
5、生成停词表,把简介写入text中
word
= data2
['简介'].values
.tolist
()
fb
= open(r
'.\travel_text.txt','w',encoding
='utf-8')
for i
in range(len(word
)):
fb
.write
(word
[i
])
with open(r
'.\travel_text.txt','r',encoding
='utf-8')as f
:
words
= f
.read
()
f
.close
jieba
.analyse
.set_stop_words
(r
'.\travel_text.txt')
new_words
= jieba
.analyse
.textrank
(words
, topK
=30, withWeight
=True)
print(new_words
)
定义分词函数
def get_cut_words(content_series
):
stop_words
= []
with open("travel_text.txt", 'r', encoding
='utf-8') as f
:
lines
= f
.readlines
()
for line
in lines
:
stop_words
.append
(line
.strip
())
my_words
= ['美食','好玩','实惠']
for i
in my_words
:
jieba
.add_word
(i
)
my_stop_words
= ['攻略','打死']
stop_words
.extend
(my_stop_words
)
word_num
= jieba
.lcut
(content_series
.str.cat
(sep
='。'), cut_all
=False)
word_num_selected
= [i
for i
in word_num
if i
not in stop_words
and len(i
)>=2]
return word_num_selected
text
= get_cut_words
(content_series
=data2
['简介'])
text
[:10]
6、绘制词云图
stylecloud
.gen_stylecloud
(
text
=' '.join
(text
),
collocations
=False,
font_path
=r
'simhei.ttf',
icon_name
='fas fa-heart',
size
=600,
background_color
="#040f3c",
output_name
='简介词云分析.png'
)
Image
(filename
='简介词云分析.png')
7、根据不同需求定制旅游方案
the_list
= []
keyword
= input('请输入旅行月份:')
data5
= data4
[data4
['旅行月份'] == str(keyword
)]
keyword1
= input('请输入结伴出游方式:')
data6
= data5
[data5
['人物'] == str(keyword1
)]
price
= int(input('请输入预期价格上限:'))
data7
= data6
[data6
['人均费用']<=price
]
day1
= int(input('请输入旅行时长下限:'))
day2
= int(input('请输入旅行时长上限:'))
data8
= data7
[(data7
['天数']>=day1
)&(data7
['天数']<=day2
)]
data8