【问题标题】:Pandas: How to plot the imdb movie total budget versus the separate genre in pandas?Pandas:如何绘制 imdb 电影总预算与 pandas 中的单独类型?
【发布时间】:2019-02-07 12:45:44
【问题描述】:

这实际上是我上一个问题的后续问题。

pandas: How to plot the pie diagram for the movie counts versus genre of IMDB movies in pandas?

在那个问题中,我们绘制了电影的独特类型的数量。 我的问题是:如何在pandas 中获得'budget''genres' 的图?

这里是示例代码:

import pandas as pd
import numpy as np 
%matplotlib inline

df = pd.DataFrame({'movie' : ['A', 'B','C','D'],
                   'budget': [1000, 2000, 3000, 4000],
                   'genres': ['Science Fiction|Romance|Family', 'Action|Romance',
                              'Family|Drama','Mystery|Science Fiction|Drama']},
                  index=range(4))
df

这里的流派Science Fiction|Romance|Family实际上是三个独立的流派。

Science Fiction 出现在电影AB 中,所以Science Fiction 类型的预算应该是1000+4000=5000 等等。

【问题讨论】:

  • 使用df.plot(x='genres', y='budget') 绘制简单的线图。请通过this 了解更多详情。
  • 你应该试着在第一时间把你的问题和你想要的更清楚。这样可以节省每个人的编辑时间。

标签: python pandas


【解决方案1】:

您可以通过以下方式绘制每种类型的总预算:

genres = (df.genres.str.split('|', expand=True)
            .stack()
            .to_frame(name='genre'))


genres.index = genres.index.droplevel(1)

所以genres 变成:

        genre
0   Science Fiction
0   Romance
0   Family
1   Action
1   Romance
2   Family
2   Drama
3   Mystery
3   Science Fiction
3   Drama

现在执行 join 和 groupby 以首先获取预算信息,然后对类型求和:

(genres.join(df['budget'])
       .groupby('genre')
       .sum()
       .plot(kind='bar'))

输出:

【讨论】:

    猜你喜欢
    • 2019-02-07
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2020-03-18
    • 2020-09-11
    • 2011-12-05
    相关资源
    最近更新 更多