我有以下数据集:
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')
I got this image:
但我想要每个不同类型的饼图。
我们如何获得每种独特类型的电影数量?
因此,单行解决方案:
df.genres.str.get_dummies().sum().plot.pie(label='Genre', autopct='%1.0f%%')
Result:
TL;DR
首先,将您的类别列转换为虚拟列:
df = pd.concat([df.drop('genres', axis=1), df.genres.str.get_dummies()], axis=1)
Result:
movie a b c d e f g
0 A 1 1 1 0 0 0 0
1 B 0 0 1 0 1 0 0
2 C 0 0 0 0 0 1 1
3 D 1 1 0 1 1 0 0
然后计算每个类别出现的次数:
counts = df.drop('movie', axis=1).sum()
Result:
a 2
b 2
c 2
d 1
e 2
f 1
g 1
最后绘制饼图:
counts.plot.pie()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)