觀影大數據分析(中)


6.Json數據轉換

**說明:**genres,keywords,production_companies,production_countries,cast,crew 這 6 列都是 json 數據,需要處理為列表進行分析。 處理方法: json 本身為字符串類型,先轉換為字典列表,再將字典列表轉換為,以’,'分割的字符串

#Json格式處理
json_column = ['genres', 'keywords', 'production_companies', 'production_countries', 'cast', 'crew']

# 1-json本身為字符串類型,先轉換為字典列表
for i in json_column:
    df[i] = df[i].apply(json.loads)

# 提取name
# 2-將字典列表轉換為以','分割的字符串
def get_name(x):
    return ','.join([i['name'] for i in x])

df['cast'] = df['cast'].apply(get_name)

# 提取derector
def get_director(x):
    for i in x:
        if i['job'] == 'Director':
            return i['name']

df['crew'] = df['crew'].apply(get_director)

for j in json_column[0:4]:
    df[j] = df[j].apply(get_name)

# 重命名
rename_dict = {'cast': 'actor', 'crew': 'director'}
df.rename(columns=rename_dict, inplace=True)
df.info()
print(df.head(5).genres)
print(df.head(5).keywords)
print(df.head(5).production_companies)
print(df.head(5).production_countries)
print(df.head(5).actor)
print(df.head(5).director)

運行結果

7.數據備份

#數據備份
org_df = df.copy()
df.reset_index().to_csv("TMDB_5000_Movie_Dataset_Cleaned.csv")

數據預處理階段完成

————————————————————————————————————————————————————————————————

8.數據分析

8.1 Why

想要探索影響票房的因素,從電影市場趨勢,觀眾喜好類型,電影導演,發行時間,評分與 關鍵詞等維度着手,給從業者提供合適的建議

8.2 What

8.2.1 電影類型:定義一個集合,獲取所有的電影類型

# 定義一個集合,獲取所有的電影類型
genre = set()
for i in df['genres'].str.split(','): # 去掉字符串之間的分隔符,得到單個電影類型
    genre = set().union(i,genre)    # 集合求並集
    # genre.update(i) #或者使用update方法

print(genre)

運行結果

8.2.2 電影類型數量,繪制條形圖

創建類型集合,更改索引為‘年份’

#將genre轉變成列表
genre_list = list(genre)

# 創建數據框-電影類型
genre_df = pd.DataFrame()

#對電影類型進行one-hot編碼
for i in genre_list:
    # 如果包含類型 i,則編碼為1,否則編碼為0
    genre_df[i] = df['genres'].str.contains(i).apply(lambda x: 1 if x else 0)

#將數據框的索引變為年份
genre_df.index = df['release_year']

繪圖

# 計算得到每種類型的電影總數目,並降序排列
grnre_sum = genre_df.sum().sort_values(ascending = False)
# 可視化
plt.rcParams['font.sans-serif'] = ['SimHei']  #用來顯示中文
grnre_sum.plot(kind='bar',label='genres',figsize=(12,9))
plt.title('電影類型數量',fontsize=20)
plt.xticks(rotation=60)
plt.xlabel('類型',fontsize=16)
plt.ylabel('數量',fontsize=16)
plt.grid(False)
plt.savefig("電影類型數量-條形圖.png",dpi=300) #在 plt.show() 之前調用 plt.savefig()
plt.show()

運行結果

8.2.3 電影類型占比,繪制餅圖

#繪制餅圖
gen_shares = grnre_sum / grnre_sum.sum()
# 設置other類,當電影類型所占比例小於%1時,全部歸到other類中
others = 0.01
gen_pie = gen_shares[gen_shares >= others]
gen_pie['others'] = gen_shares[gen_shares < others].sum()

# 設置分裂屬性
# 所占比例小於或等於%2時,增大每塊餅片邊緣偏離半徑的百分比
explode = (gen_pie <= 0.02)/10

gen_pie.plot(kind='pie',label='',explode=explode,startangle=0,shadow=False,autopct='%3.1f%%',figsize=(8,8))

plt.title('電影類型占比',fontsize=20)
plt.savefig("電影類型占比-餅圖.png",dpi=300)
plt.show()

運行結果

8.2.4 電影類型變化趨勢,繪制折線圖

繪制電影類型隨時間變化的趨勢

gen_year_sum = genre_df.sort_index(ascending = False).groupby('release_year').sum()
gen_year_sum_sub = gen_year_sum[['Drama','Comedy','Thriller','Action','Adventure','Crime','Romance','Science Fiction']]
gen_year_sum_sub.plot(figsize=(12,9))
plt.legend(gen_year_sum_sub.columns)
plt.xticks(range(1915,2018,10))
plt.xlabel('年份', fontsize=16)
plt.ylabel('數量', fontsize=16)
plt.title('電影類型變化趨勢', fontsize=20)

plt.grid(False)
plt.savefig("電影類型變化趨勢-折線圖.png",dpi=600)
plt.show()

運行結果

8.2.5 不同電影類型預算/利潤,繪制組合圖

首先計算不同類型的電影利潤

# Step1-創建profit_dataframe
profit_df = pd.DataFrame()
profit_df = pd.concat([genre_df.reset_index(), df['revenue']], axis=1)
# Step2-創建profit_series,橫坐標為genre
profit_s=pd.Series(index=genre_list)
# Step3-求出每種genre對應的利潤均值
for i in genre_list:
    profit_s.loc[i]=profit_df.loc[:,[i,'revenue']].groupby(i, as_index=False).mean().loc[1,'revenue']
profit_s = profit_s.sort_values(ascending = True)

再計算不同類型的電影預算

# 計算不同類型電影的budget
# Step1-創建profit_dataframe
budget_df = pd.DataFrame()
budget_df = pd.concat([genre_df.reset_index(), df['budget']], axis=1)
# Step2-創建budget_series,橫坐標為genre
budget_s=pd.Series(index=genre_list)
# Step3-求出每種genre對應的預算均值
for j in genre_list:
    budget_s.loc[j]=budget_df.loc[:,[j,'budget']].groupby(j, as_index=False).mean().loc[1,'budget']

合並結果集

profit_budget = pd.concat([profit_s, budget_s], axis=1)
profit_budget.columns = ['revenue', 'budget']

計算利潤率(利潤/預算*100%)

profit_budget['rate'] = (profit_budget['revenue']/profit_budget['budget'])*100

美觀圖像,根據預算降序排序

profit_budget_sort=profit_budget.sort_values(by='budget',ascending = False)

開始繪圖:

(1)組合圖(條形預算+折現利潤率)

# 繪制不同類型電影平均預算和利潤率(組合圖)
x = profit_budget_sort.index
y1 = profit_budget_sort.budget
y2 = profit_budget_sort.rate
# 返回profit_budget的行數
length = profit_budget_sort.shape[0]

fig = plt.figure(figsize=(12,9))
# 左軸
ax1 = fig.add_subplot(1,1,1)
plt.bar(range(0,length),y1,color='b',label='平均預算')
plt.xticks(range(0,length),x,rotation=90, fontsize=12)  # 更改橫坐標軸名稱
ax1.set_xlabel('年份')                   # 設置x軸label ,y軸label
ax1.set_ylabel('平均預算',fontsize=16)
ax1.legend(loc=2,fontsize=12)

#右軸
# 共享x軸,生成次坐標軸
ax2 = ax1.twinx()
ax2.plot(range(0,length),y2,'ro-.')
ax2.set_ylabel('平均利潤率',fontsize=16)
ax2.legend(loc=1,fontsize=12)

# 將利潤率坐標軸以百分比格式顯示
import matplotlib.ticker as mtick
fmt='%.1f%%'
yticks = mtick.FormatStrFormatter(fmt)
ax2.yaxis.set_major_formatter(yticks)

# 設置圖片title
ax1.set_title('電影類型的平均預算和利潤率',fontsize=20)
ax1.grid(False)
ax2.grid(False)
plt.savefig("電影類型的平均預算和利潤率-組合圖.png",dpi=300)
plt.show()

(2)不同電影類型的預算和收入,條形圖

# 繪制不同類型電影預算和收入(條形圖)
profit_budget_sort.iloc[:,0:2].plot(kind='bar', figsize=(12,9),color = ['darkorange','b'])
plt.title('平均預算(budget)與平均收入(revenue)',fontsize = 20)
plt.xlabel('len',fontsize = 16)
plt.grid(False)
plt.savefig('電影類型的平均預算和平均收入-條形圖.png',dpi=300)
plt.show()

8.2.6 電影關鍵詞,詞雲圖

#keywords關鍵詞分析
keywords_list = []
for i in df['keywords']:
    keywords_list.append(i)
# print(keywords_list)
#把字符串列表連接成一個長字符串
lis = ''.join(keywords_list)
lis.replace('\'s','')
#設置停用詞
stopwords = set(STOPWORDS)
stopwords.add('film')
stopwords.add('based')
wordcloud = WordCloud(
                background_color = 'black',
                random_state=9, # 設置一個隨機種子,用於隨機着色
                stopwords = stopwords,
                max_words = 3000,
                scale=1).generate(lis)
plt.figure(figsize=(10,6))
plt.imshow(wordcloud)
plt.axis('off')
plt.savefig('詞雲圖.png',dpi=300)
plt.show()

8.3 When

8.3.1 修改數據類型

查看runtime數據類型

print(df.runtime.head(5))

發現是Object類型

先將其轉換為數值類型,float64,便於數字統計

df.runtime = df.runtime.astype(float)
print(df.runtime.head(5))

8.3.2 繪制電影時長直方圖

sns.set_style('white')
sns.distplot(df.runtime,bins = 20)
sns.despine(left = True) # 使用despine()方法來移除坐標軸,默認移除頂部和右側坐標軸
plt.xticks(range(50,360,20))
plt.savefig('電影時長直方圖.png',dpi=300)
plt.show()

8.3.3 繪制每月電影數量和單片平均票房

fig = plt.figure(figsize=(8,6))

x = list(range(1,13))
y1 = df.groupby('release_month').revenue.size()
y2 = df.groupby('release_month').revenue.mean()# 每月單片平均票房

# 左軸
ax1 = fig.add_subplot(1,1,1)
plt.bar(x,y1,color='b',label='電影數量')
plt.grid(False)
ax1.set_xlabel(u'月份')# 設置x軸label ,y軸label
ax1.set_ylabel(u'每月電影數量',fontsize=16)
ax1.legend(loc=2,fontsize=12)

# 右軸
ax2 = ax1.twinx()
plt.plot(x,y2,'ro--',label=u'單片平均票房')
ax2.set_ylabel(u'每月單片平均票房',fontsize=16)
ax2.legend(loc=1,fontsize=12)

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.savefig('每月電影數量和單片平均票房.png',dpi=300)
plt.rc("font",family="SimHei",size="15")
plt.show()

8.4 Where

本數據集收集的是美國地區的電影數據,對於電影的制作公司以及制作國家,在本次的故事 背景下不作分析。

8.5 Who

8.5.1 分析票房分布及票房 Top10 的導演

#票房分布及票房Top10的導演
# 創建數據框 - 導演
director_df = pd.DataFrame()

director_df = df[['director','revenue','budget','vote_average']]
director_df['profit'] = (director_df['revenue']-director_df['budget'])

director_df = director_df.groupby(by = 'director').mean().sort_values(by='revenue',ascending = False) # 取均值
director_df.info()

# 繪制票房分布直方圖
director_df['revenue'].plot.hist(bins=100, figsize=(8,6))
plt.xlabel('票房')
plt.ylabel('頻數')
plt.title('導演的票房分布直方圖')
plt.savefig('導演的票房分布直方圖.png',dpi = 300)
plt.show()

# 票房均值Top10的導演
director_df.revenue.sort_values(ascending = True).tail(10).plot(kind='barh',figsize=(8,6))
plt.xlabel('票房',fontsize = 16)
plt.ylabel('導演',fontsize = 16)
plt.title('票房排名Top10的導演',fontsize = 20)
plt.savefig('票房排名Top10的導演.png',dpi = 300)
plt.show()

8.5.2 分析評分分布及評分 Top10 的導演

#評分分布及評分Top10的導演
# 繪制導演評分直方圖
director_df['vote_average'].plot.hist(bins=18, figsize=(8,6))
plt.xlabel('評分')
plt.ylabel('頻數')
plt.title('導演的評分分布直方圖')
plt.savefig('導演的評分分布直方圖.png',dpi = 300)
plt.show()

# 評分均值Top10的導演
director_df.vote_average.sort_values(ascending = True).tail(10).plot(kind='barh',figsize=(8,6))
plt.xlabel('評分',fontsize = 16)
plt.ylabel('導演',fontsize = 16)
plt.title('評分排名Top10的導演',fontsize = 20)
plt.savefig('評分排名Top10的導演.png',dpi = 300)
plt.show()

運行結果

8.6 How

8.6.1 原創 VS 改編占比(餅圖)

#原創 VS 改編占比(餅圖)
# 創建數據框
original_df = pd.DataFrame()
original_df['keywords'] = df['keywords'].str.contains('based on').map(lambda x: 1 if x else 0)
original_df['profit'] = df['revenue'] - df['budget']
original_df['budget'] = df['budget']

# 計算
novel_cnt = original_df['keywords'].sum() # 改編作品數量
original_cnt = original_df['keywords'].count() - original_df['keywords'].sum() # 原創作品數量
# 按照 是否原創 分組
original_df = original_df.groupby('keywords', as_index = False).mean() # 注意此處計算的是利潤和預算的平均值
# 增加計數列
original_df['count'] = [original_cnt, novel_cnt]
# 計算利潤率
original_df['profit_rate'] = (original_df['profit'] / original_df['budget'])*100

# 修改index
original_df.index = ['original', 'based_on_novel']
# 計算百分比
original_pie = original_df['count'] / original_df['count'].sum()

# 繪制餅圖
original_pie.plot(kind='pie',label='',startangle=90,shadow=False,autopct='%2.1f%%',figsize=(8,8))
plt.title('改編 VS 原創',fontsize=20)
plt.legend(loc=2,fontsize=10)
plt.savefig('改編VS原創-餅圖.png',dpi=300)
plt.show()

8.6.2 原創 VS 改編預算/利潤率(組合圖)

#原創VS改編 預算/利潤率(組合圖)
x = original_df.index
y1 = original_df.budget
y2 = original_df.profit_rate

fig= plt.figure(figsize = (8,6))

# 左軸
ax1 = fig.add_subplot(1,1,1)
plt.bar(x,y1,color='b',label='平均預算',width=0.25)
plt.xticks(rotation=0, fontsize=12)  # 更改橫坐標軸名稱
ax1.set_xlabel('原創 VS 改編')                   # 設置x軸label ,y軸label
ax1.set_ylabel('平均預算',fontsize=16)
ax1.legend(loc=2,fontsize=10)

#右軸
# 共享x軸,生成次坐標軸
ax2 = ax1.twinx()
ax2.plot(x,y2,color='r',label='平均利潤率')
ax2.set_ylabel('平均利潤率',fontsize=16)
ax2.legend(loc=1,fontsize=10) # loc=1,2,3,4分別表示四個角,和四象限順序一致

# 將利潤率坐標軸以百分比格式顯示
import matplotlib.ticker as mtick
fmt='%.1f%%'
yticks = mtick.FormatStrFormatter(fmt)
ax2.yaxis.set_major_formatter(yticks)

plt.savefig('改編VS原創的預算以及利潤率-組合圖.png',dpi=300)
plt.show()

8.7 How much

8.7.1 計算相關系數(票房相關系數矩陣)

revenue_corr = df[['runtime','popularity','vote_average','vote_count','budget','revenue']].corr()

sns.heatmap(
            revenue_corr,
            annot=True, # 在每個單元格內顯示標注
            cmap="Blues", # 設置填充顏色:黃色,綠色,藍色
            cbar=True,  # 顯示color bar
            linewidths=0.5, # 在單元格之間加入小間隔,方便數據閱讀
           )
plt.savefig('票房相關系數矩陣.png',dpi=300)
plt.show()

8.7.2 票房影響因素散點圖

fig = plt.figure(figsize=(17,5))

ax1 = plt.subplot(1,3,1)
ax1 = sns.regplot(x='budget', y='revenue', data=df, x_jitter=.1,color='r',marker='x')
# marker: 'x','o','v','^','<'
# jitter:抖動項,表示抖動程度
ax1.text(1.6e8,2.2e9,'r=0.7',fontsize=16)
plt.title('budget-revenue-scatter',fontsize=20)
plt.xlabel('budget',fontsize=16)
plt.ylabel('revenue',fontsize=16)

ax2 = plt.subplot(1,3,2)
ax2 = sns.regplot(x='popularity', y='revenue', data=df, x_jitter=.1,color='g',marker='o')
ax2.text(500,3e9,'r=0.59',fontsize=16)
plt.title('popularity-revenue-scatter',fontsize=18)
plt.xlabel('popularity',fontsize=16)
plt.ylabel('revenue',fontsize=16)

ax3 = plt.subplot(1,3,3)
ax3 = sns.regplot(x='vote_count', y='revenue', data=df, x_jitter=.1,color='b',marker='v')
ax3.text(7000,2e9,'r=0.75',fontsize=16)
plt.title('voteCount-revenue-scatter',fontsize=20)
plt.xlabel('vote_count',fontsize=16)
plt.ylabel('revenue',fontsize=16)
plt.savefig('revenue.png',dpi=300)
plt.show()

散點圖:

數據分析結束

————————————————————————————————————————————————————————————————

結論明天再分析

 

 

相關:

觀影大數據分析(上) - Arisf - 博客園 (cnblogs.com)

觀影大數據分析(中) - Arisf - 博客園 (cnblogs.com)

觀影大數據分析(下) - Arisf - 博客園 (cnblogs.com)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM