我有以下数据集:
import pandas as pd
import numpy as np
%matplotlib inline
df = pd.DataFrame({'movie' : ['A', 'B','C','D'],
'genres': ['Science Fiction|Romance|Family', 'Action|Romance',
'Family|Drama','Mystery|Science Fiction|Drama']},
index=range(4))
df
我的尝试
# Parse unique genre from all the movies
gen = []
for g in df['genres']:
gg = g.split('|')
gen = gen + gg
gen = list(set(gen))
print(gen)
df['genres'].value_counts().plot(kind='pie')
但我想为每种不同的风格制作饼图。
如何获得每种独特类型的电影数量计数类型?
您可以.str.split()
使用进行操作expand=True
,这将为您提供DataFrame
所有流派。如果再堆叠,您将获得所有类型的值计数。
df.genres.str.split('|', expand=True).stack().value_counts().plot(kind='pie', label='Genre')
在计算计数方面可能会比较慢,因此对于相同的绘图,更快的实现方式是(加上百分比):
from itertools import chain
from collections import Counter
import matplotlib.pyplot as plt
cts = Counter(chain.from_iterable(df.genres.str.split('|').values))
_ = plt.pie(cts.values(), labels=cts.keys(), autopct='%1.0f%%')
_ = plt.ylabel('Genres')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句