Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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})
like image 602
MrFairWall Avatar asked Nov 21 '16 19:11

MrFairWall


People also ask

How do you take a slice of pandas DataFrame?

Slicing a DataFrame in Pandas includes the following steps:Ensure Python is installed (or install ActivePython) Import a dataset. Create a DataFrame. Slice the DataFrame.

How do you split with pandas?

Split column by delimiter into multiple columnsApply the pandas series str. split() function on the “Address” column and pass the delimiter (comma in this case) on which you want to split the column. Also, make sure to pass True to the expand parameter.

How do you split a DataFrame into two DataFrames in Python?

In the above example, the data frame 'df' is split into 2 parts 'df1' and 'df2' on the basis of values of column 'Weight'. Method 2: Using Dataframe. groupby(). This method is used to split the data into groups based on some criteria.

How do I split a DataFrame using ILOC?

Using the iloc() function to split DataFrame in Python We can use the iloc() function to slice DataFrames into smaller DataFrames. The iloc() function allows us to access elements based on the index of rows and columns. Using this function, we can split a DataFrame based on rows or columns.


2 Answers

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)

like image 130
Mat Sohani Avatar answered Sep 21 '22 05:09

Mat Sohani


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.

like image 24
maxymoo Avatar answered Sep 19 '22 05:09

maxymoo