MrFairWall
MrFairWall

Reputation: 158

How can I split DataFrame (pandas) on pages with django paginator?

It is easy for Series. I just pass it to paginator. But, when I use DataFrame, it is call "The truth value of a Series is ambiguous". Maybe, there are problem with count method, but I don't know how I can change it. In my project DataFrame must be split on pages by rows.

def listing(request):
    contact_list = pd.DataFrame(np.arange(12).reshape(4,3))
    paginator = Paginator(contact_list, 1)  # Show 1 row per page

page = request.GET.get('page')
try:
    contacts = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    contacts = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    contacts = paginator.page(paginator.num_pages)

return render(request, 'list.html', {'contacts': contacts})

Upvotes: 8

Views: 6335

Answers (3)

Kailegh
Kailegh

Reputation: 197

I have tested the following code with my own dataframes and it works. Just convert your dataframe to a list of dicts and the paginator should just work fine.
Sorry for the late response I just came up with this question

records = df.to_dict(orient='records')

paginator = Paginator(records, num_of_items)
page = request.GET.get('page')
records = paginator.get_page(page)
return render(request, 'list.html', {'contacts': records})

Upvotes: 1

Mat Sohani
Mat Sohani

Reputation: 21

You have to segregate your columns and then use pagination on each column and then append them together, since dataframe iterates on columns. Basically by separating each column, you give the chance to iterator to go through the rows:

contact_list = pd.DataFrame(np.arange(12).reshape(4,3))

paginator1 = Paginator(contact_list['col1'], 1)

paginator2 = Paginator(contact_list['col2'], 1)

Upvotes: 2

maxymoo
maxymoo

Reputation: 36545

The problem may be caused by the fact that by DataFrame.__iter__ iterates by column rather than row. You could call df.iterrows() or df.values if you want to get an iterator of your dataframe rows.

Upvotes: 1

Related Questions