Issue
I am working on a django project where I render a pandas dataframe in the context. I then iterate through this dataframe to display it in a table td td (html below).
I would like to get this as a fixed size with horizontal and vertical scrollbars instead when the dataframe is too large.
How can I do this?
<table style="margin-left: auto; margin-right: auto;">
<tr>
{% for col in df.columns %}
<td>
<b>{{col}}</b>
</td>
{% endfor %}
</tr>
{% for index, row in df.iterrows %}
<tr>
{% for cell in row %}
<td>
{{cell}}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Solution
Your code is almost there. Simply wrap the table in a div tag where you can specify the style; height, width, scrollbars etc. Also iterrows
is an incredibly slow way to iterate over a dataframe. A much faster alternative is itertuples
which includes the index as a first element which can be skipped (or included if so desired).
<div style="height:300px; width:700px; overflow:auto;">
<table class="table table-bordered table-light" style="margin-left:auto; margin-right:auto;">
<thead>
<tr>
{% for col in df.columns %}
<th style="text-align:center">{{col}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in df.itertuples %}
<tr>
{% for cell in row|slice:"1:" %}
<td style="text-align:center">{{cell}}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
Then it renders a page that looks like which has the scrollbars if necessary.
Btw, the function in view.py used to pass the dataframe through context looks like:
def mypage(request):
df = pd.DataFrame(np.random.default_rng(0).random(size=(100,10))).add_prefix('col')
return render(request, 'mypage.html', {'df': df})
and I used <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
bootstrap in the base.html which the mypage.html page extends.
Answered By - cottontail
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.