pandas:如何在 pandas 中绘制电影数量与 IMDB 电影类型的饼图? [英] pandas: How to plot the pie diagram for the movie counts versus genre of IMDB movies in pandas?
本文介绍了pandas:如何在 pandas 中绘制电影数量与 IMDB 电影类型的饼图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据集:
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')
我得到了这张图片:
但是我想为每种不同的类型绘制饼图.
But I would like to pie chart for each separate genres.
我们如何获得每个独特流派的电影数量的流派?
How we get the genres for number count of movies for each unique genres?
推荐答案
你可以用 expand=True
做 .str.split()
,这会给你一个所有流派的 DataFrame
.如果您将其堆叠起来,您将获得所有类型的价值计数.
You can do .str.split()
with expand=True
, which will give you a DataFrame
of all the genres. If you then stack that, you will get the value counts for all of the genres.
df.genres.str.split('|', expand=True).stack().value_counts().plot(kind='pie', label='Genre')
这在计算计数方面可能有点慢,因此对同一图的更快实现是(添加百分比):
That can be a bit on the slower side to calculate the counts, so a faster implementation for the same plot would be (adding the percentages):
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')
这篇关于pandas:如何在 pandas 中绘制电影数量与 IMDB 电影类型的饼图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文