Saturday, May 31, 2014

UnboundLocalError - How do I convert my pandas DataFrame into a list that Django can work with?

Exception Type: UnboundLocalError
Exception Value:
local variable 'list' referenced before assignment


Hi, I'm trying to convert my pandas DataFrame into a simple list in Views.py and send it to template.  But Django complains and I don't know how to make it happy.  Because when I do "global list" then I get the below error instead which says that I cannot use variable list when I google for it.  How do I convert my DataFrame into a list that Django can work with?


Exception Type: TypeError
Exception Value:
'list' object is not callable

#_______________________________________________________________________________
...
...
from django.db.models import Count

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('max_columns', 50)

from magazine.models import Publication, Article
#_______________________________________________________________________________

def index(request):

    # Publication list
    publications = Publication.objects.all()

    # Articles list with Many-to-many relationship to Publication table
    # for counting how many publications each article was in.
    articles = Article.objects.all().annotate(num_publications=Count('publications'))

    # There is a total of 5 Publications in the database.
    total_publicists = Publication.objects.all().count()

#--------------------------------------------
### Leo magic
    articles_list = [(article, float(article.num_publications)/total_publicists*100) for article in articles]
#--------------------------------------------

    articles_list3 = [(article.id, article, float(article.num_publications)/total_publicists*100) for article in articles]

    df = pd.DataFrame(articles_list3)

    df['FRACTION'] = df[2]-df[0]

    #global list
    b = map(list, df.values)


...
...

    context = {'articles_list':articles_list, 'publications':publications,
               'total_publicists':total_publicists, 'articles':articles,
               'uncommented_publications':uncommented_publications,
               'articles_list2':articles_list2, 'b':b}
    return render(request, 'magazine/index.html', context)
#_______________________________________________________________________________



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/202816f5-3039-4386-90a3-5e82ec1a5108%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment