各类型电影的数量如何随着时间的推移发生变化的?建立包含年份与电影类型数量的关系数据框 提取2000-2016年的各电影类型数量 ,用pyecharts实现热力图可视化
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import HeatMap
df = pd.read_excel('第12周课后作业(预处理后的数据)T1.xlsx')
df.dropna(inplace=True)
#建立genres列表,提取电影的类型
genres_set = set()
for genre in df['genres'].str.split('|'):
for item in genre:
genres_set.add(item)
genres_list = list(genres_set)
#显示genres_list内容
genres_list
#显示genres_list内容
['Drama', 'Adventure', 'Mystery', 'Family', 'History', 'Fantasy', 'Music', 'Animation', 'Horror', 'Foreign', 'Science Fiction', 'Thriller', 'Western', 'Comedy', 'Documentary', 'Romance', 'TV Movie', 'Crime', 'Action', 'War']
for genre in genres_list:
#判断每行 有这个类型,在对应类型的列下面添个1
df[genre] = df['genres'].str.contains(genre).apply(lambda x: 1 if x else 0)
genre_year = df.loc[:,genres_list]
#将年份作为索引标签
genre_year.index = df['year']
#将数据集按年份分组求和,得出每个年份,各电影类型的电影总数
genresdf = genre_year.groupby('year').sum()
#显示包含年份与电影类型数量的DataFrame genresdf
genresdf
genresdf内容显示
#取2000-2016年电影类型数量
datas = genresdf.iloc[-18:-1:1,:]
datas
datas内容显示
#电影类型
kind = list(datas.columns)
kind
#kind为电影类型 ['Drama', 'Adventure', 'Mystery', 'Family', 'History', 'Fantasy', 'Music', 'Animation', 'Horror', 'Foreign', 'Science Fiction', 'Thriller', 'Western', 'Comedy', 'Documentary', 'Romance', 'TV Movie', 'Crime', 'Action', 'War']
#提取出年份
year = list(datas.index)
year
#year为年份 [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016]
#遍历出每个年份各电影类型对应的电影数量
value = [[i,j,int(datas.iloc[i,j])]for i in range(len(year))for j in range(len(kind))]
value
#value内容显示如下,由于内容过长,只显示一部分
#数据格式:前两个数是数据所在位置坐标,第三个数是要填进去的具体数据
#画图
c = (
HeatMap(init_opts=opts.InitOpts(width='1000px',height='580px'))
.add_xaxis(year)
.add_yaxis("",kind,value,
label_opts=opts.LabelOpts(
is_show=True,color="#fff",position="inside",horizontal_align="50%"))
.set_global_opts(
title_opts=opts.TitleOpts(title="2000-2016年各电影类型数量",
title_textstyle_opts=opts.TextStyleOpts(font_size=30),
pos_right="center"),
legend_opts=opts.LegendOpts(is_show=True),
#x轴
xaxis_opts=opts.AxisOpts(
name="年份",
name_location="center",
name_gap=30,
name_textstyle_opts=opts.TextStyleOpts(font_size=20),
#这里的type_一定要写"category",否则显示不了数据
type_="category",
splitarea_opts=opts.SplitAreaOpts(
is_show=True,
areastyle_opts=opts.AreaStyleOpts(opacity=1)
),
),
#y轴
yaxis_opts=opts.AxisOpts(
name="电影类型",
name_location="center",
name_gap=750,
name_textstyle_opts=opts.TextStyleOpts(font_size=20),
#这里的type_一定要写"category",否则显示不了数据
type_="category",
splitarea_opts=opts.SplitAreaOpts(
is_show=True,
areastyle_opts=opts.AreaStyleOpts(opacity=1)
),
),
#显示图例
visualmap_opts=opts.VisualMapOpts(
min_=0,max_=60,is_calculable=True,orient="vertical",
pos_left="90%",pos_bottom="center"
),
)
)
c.render("2000-2016年各电影类型数量T1.html")
#热力图效果
pyecharts热力图:2000-2016年各电影类型数量T1.html