【问题标题】:pandas: How to plot the pie diagram for the movie counts versus genre of IMDB movies in pandas?pandas:如何在 pandas 中绘制电影数量与 IMDB 电影类型的饼图?
【发布时间】:2019-02-07 12:29:15
【问题描述】:

我有以下数据集:

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')

我得到了这张图片:

但我想为每个单独的流派制作饼图。

我们如何获得每种独特类型的电影数量的类型?

【问题讨论】:

    标签: python pandas matplotlib plot imdb


    【解决方案1】:

    所以,单线解决方案:

    df.genres.str.get_dummies().sum().plot.pie(label='Genre', autopct='%1.0f%%')
    

    结果:


    TL;DR

    首先,将您的类别列转换为虚拟对象:

    df = pd.concat([df.drop('genres', axis=1), df.genres.str.get_dummies()], axis=1)
    

    结果:

      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()
    

    结果:

    a    2
    b    2
    c    2
    d    1
    e    2
    f    1
    g    1
    

    最后绘制饼图:

    counts.plot.pie()
    

    【讨论】:

      【解决方案2】:

      您可以将.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')
      

      【讨论】:

      • 我们也可以在饼图中显示百分比数字吗?
      • @astro123 是的,请参阅编辑。使用matplotlib,您只需将autopct='%1.0f%%' 参数添加到饼图。
      • 太棒了!感谢一百万@ALollz。 Quich 问题,这仅计算类型。如果我们必须为 df.budget 与 df.genre_unique_like_this 绘制类似的图,我们该怎么做?
      • 如果这需要是一个不同的问题,我会发布它。
      • @astro123 我认为对于不同的问题可能会更好!很遗憾,我现在也没有时间回答。不过我可以稍后再查看。
      猜你喜欢
      • 2019-02-07
      • 1970-01-01
      • 2011-12-05
      • 2020-03-18
      • 2021-12-31
      • 1970-01-01
      • 2011-04-12
      • 2017-01-01
      • 2016-06-19
      相关资源
      最近更新 更多