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

1,282 views
Skip to first unread message

Pepsodent Cola

unread,
May 31, 2014, 2:15:16 PM5/31/14
to django...@googlegroups.com
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)
#_______________________________________________________________________________



Pepsodent Cola

unread,
Jun 1, 2014, 4:51:03 AM6/1/14
to django...@googlegroups.com
Never mind it seems using a tuple instead of a list solved my problem.

    subset = df[[0, 1, 2, 'FRACTION']]
    tuples = [tuple(x) for x in subset.values]
Reply all
Reply to author
Forward
0 new messages