现有数据,需要将genre这列,电影分类数据统计出来,如下: 首先导入库,读取数据:
import pandas as pd
import numpy as np
data = pd. read_csv( "IMDB-Movie-Data.csv" )
data. head( )
需要注意的是一部电影可能会有多个分类,所以我们需要将该列数据进行处理,使用str.split()方法将字符串用逗号分割,取值:
genres_list = data[ "Genre" ] . str . split( "," ) . values
genres_list
使用列表推导式提取每一个列表中的类别,然后使用集合去重,再转换为列表:
new_genres_list = list ( set ( [ genre for genres in list ( genres_list) for genre in genres] ) )
new_genres_list
创建一个列索引为电影分类,行数和data一致,并填充数据为0的DataFrame
genre_df = pd. DataFrame( np. zeros( ( data. shape[ 0 ] , len ( new_genres_list) ) ) , columns= new_genres_list)
genre_df
遍历genre_df中的每一行,同时取出genres_list中相同索引的列表,这个列表即列索引,取出 genre_df中对应的分类赋值为1
for i in range ( data. shape[ 0 ] ) :
genre_df. loc[ i, genres_list[ i] ] = 1
genre_df
对数据的每一列进行求和,即得到了所有电影的类别个数
genre_sum = genre_df. sum ( axis= 0 )
genre_sum. sort_values( inplace= True , ascending= False )
画一个条形图就大功告成了,可以看到分类最多的是drama,最少的是musical
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl. rcParams[ 'font.family' ] = 'SimHei'
mpl. rcParams[ 'axes.unicode_minus' ] = False
plt. figure( figsize= ( 12 , 8 ) , dpi= 100 )
y = genre_sum. values
x = range ( len ( genre_sum) )
x_label = genre_sum. index
plt. bar( x, y, color= "orange" )
plt. xticks( x, x_label, rotation= 45 )
plt. title( "1000部电影的类型数量" , fontsize= 20 , fontstyle= "italic" )
for x, y in zip ( x, y) :
plt. text( x - 0.2 , y + 5 , int ( y) , color= "grey" )
plt. xlabel( "类别" , fontsize= 18 )
plt. show( )