2
$\begingroup$

I am trying to analyze the movie database using python, downloaded from imdb. While trying to generate some plots, I am running into errors which confuses me. I am trying to generate a matrix of small figures which can show me any hidden pattern etc. Here is the code:

fig, axes = plt.subplots(nrows=4, ncols=6, figsize=(12, 8), 
                         tight_layout=True)

bins = np.arange(1950,2012,3)
for ax, genre in zip(axes.ravel(), movieGenre):
    ax.hist(movieDF[movieDF['%s'%genre]==1].year, bins=bins, histtype='stepfilled', normed=True, color='r', alpha=.3, ec='None')
    ax.hist(movieDF.year, bins=bins, histtype='stepfilled', ec='None', normed=True, zorder=0, color='grey')
    ax.annotate(genre, xy=(1955, 3e-2), fontsize=14)
    ax.xaxis.set_ticks(np.arange(1950, 2013, 30))
    ax.set_yticks([])
    ax.set_xlabel('Year')

The first hist isn't working, but the second one is working when I am commenting out the first one. Here is the traceback:

 KeyError                                  Traceback (most recent call last)
<ipython-input-158-c2e7c2737372> in <module>()
      4 bins = np.arange(1950,2012,3)
      5 for ax, genre in zip(axes.ravel(), movieGenre):
----> 6     ax.hist(movieDF[movieDF['%s'%genre]==1].year, bins=bins, histtype='stepfilled', normed=True, color='r', alpha=.3, ec='None')
      7     ax.hist(movieDF.year, bins=bins, histtype='stepfilled', ec='None', normed=True, zorder=0, color='grey')
      8     ax.annotate(genre, xy=(1955, 3e-2), fontsize=14)

/Users/dt/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/axes.pyc in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
   8247         # Massage 'x' for processing.
   8248         # NOTE: Be sure any changes here is also done below to 'weights'
-> 8249         if isinstance(x, np.ndarray) or not iterable(x[0]):
   8250             # TODO: support masked arrays;
   8251             x = np.asarray(x)

/Users/dt/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/series.pyc in __getitem__(self, key)
    477     def __getitem__(self, key):
    478         try:
--> 479             result = self.index.get_value(self, key)
    480 
    481             if not np.isscalar(result):

/Users/dt/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/core/index.pyc in get_value(self, series, key)
   1169 
   1170         try:
-> 1171             return self._engine.get_value(s, k)
   1172         except KeyError as e1:
   1173             if len(self) > 0 and self.inferred_type == 'integer':



KeyError: 0

Here is the first few columns of the data:

     imdbID     title                      rating    vote      runtime  year    genre
0   tt0111161   The Shawshank Redemption    9.3      1,439,277  142    1994 [Crime, Drama]
1   tt0468569   The Dark Knight             9.0      1,410,124  152    2008 [Action, Crime, Drama]
2   tt1375666   Inception                   8.8      1,209,159  148    2010 [Action, Mystery, Sci-Fi, Thriller]
3   tt0137523   Fight Club                  8.9      1,123,462  139    1999 [Drama]
4   tt0110912   Pulp Fiction                8.9      1,117,193  154    1994 [Crime, Drama]

movieGenre is basically collecting all the different genres from 'genre' column with duplicates removed: movieGenre = set(movieDF.genre.sum()) . I then added a single column to movieDF data frame for each genre such that if a particular movie belong to that genre, then that cell is True otherwise it is False. So for example, for the movie Inception, the Action column is marked True but Crime column is marked False and so forth.

Thanks.

$\endgroup$
3
$\begingroup$

First of all, since you only seem to want to know about the Python error, your question is probably better suited for Stack Overflow.

Secondly, this is not fun to answer with the information you've provided. This is certainly not a minimal working example (MWE) - I can't copy your code as is, and run it myself. I'm left to guess many things:

  • Are you importing matplotlib?
  • Did you rename matplotlib.pyplot as plt?
  • Are you importing numpy and did you rename it np?
  • Does your traceback literally end in KeyError is 0 or is it KeyError: 0 or KeyError: False? Can you show the full traceback? The traceback for a MWE is typically not long.

In the positional argument (movieDF[movieDF['%s'%genre]==1].year) on your problematic line, you ask for a key (movieDF['%s'%genre]==1) that looks like it should evaluate to a Boolean. Is this never 0? I'm forced to grasp at straws because you haven't provided a sample dataset; I shouldn't have to download from IMDb myself.

Edit:

Just to troubleshoot, can you place x = movieDF[movieDF['%s'%genre]==1].year on a line by itself and tell me what x[0] is? What type would that x be? Is it a dictionary, where the .hist() method is expecting a list or other array? This documentation makes it sound like the method will not accept a dictionary...what type is movieDF.year?

|improve this answer|||||
$\endgroup$
  • $\begingroup$ Thanks for your comments and my apology for not providing more information. The answer to the first three questions of yours is 'yes' and the keyError is given as KeyError: 0 However, following your remark, I am going to provide you with few lines of the dataset, and what movieGenre is. Also, I will include the traceback but it is kinda large. $\endgroup$ – user62198 Apr 30 '15 at 18:36
  • 1
    $\begingroup$ @user62198 well that's sort of what i'm getting at. you should be able to minimize traceback length by pulling a small portion of your code out into another script - a script that demonstrates your problem but is standalone/removes most of the code that is not causing the problem. $\endgroup$ – aeroNotAuto Apr 30 '15 at 18:50
  • $\begingroup$ @user62198 i edited to include some potential troubleshooting steps. can you use that to provide more information? $\endgroup$ – aeroNotAuto Apr 30 '15 at 19:33
  • $\begingroup$ Thanks a lot @aeroNotAuto. I am going to try it out soon and let you know. $\endgroup$ – user62198 May 1 '15 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.