Sathish Sridhar
Sathish Sridhar

Reputation: 55

How to change dataframe to html table in django ?

I am sending this dataframe from django views to template html file

Forecast Date 2018-01-22 05:30:00 147.01 2018-01-23 05:30:00 139.67 2018-01-24 05:30:00 140.51 2018-01-25 05:30:00 144.68 2018-01-26 05:30:00 142.97 2018-01-27 05:30:00 151.83 2018-01-28 05:30:00 151.93 2018-01-29 05:30:00 142.88 2018-01-30 05:30:00 157.31 2018-01-31 05:30:00 145.67

In this above data frame the forecast is the column and date and the values are rows , but i want the the date to be in a column and the forecast values to be in another column.

This is the HTML file where i am trying to change the dataframe to html table.

`<html>
<body>
<table>
    <table>
{% for r in table %}
     {% cycle '<tr>' '' '' '' %}tr>
        <td>{{r.content}}</td>      
    <{% cycle '' '' '' '</tr>' %}
{% endfor %}
</table>
{{accuracy}}
</html>`

Upvotes: 0

Views: 4290

Answers (1)

Rakesh
Rakesh

Reputation: 82785

You can use the to_html method to convert the dataframe to a html table and then render that to your html.

Example

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
import pandas as pd

myst="""
2018-01-22 05:30:00    147.01
2018-01-23 05:30:00    139.67
2018-01-24 05:30:00    140.51
2018-01-25 05:30:00    144.68
2018-01-26 05:30:00    142.97
2018-01-27 05:30:00    151.83
2018-01-28 05:30:00    151.93
2018-01-29 05:30:00    142.88
2018-01-30 05:30:00    157.31
2018-01-31 05:30:00145.67
"""

df = pd.read_csv(myf, sep=r"\s\s+", names=["Forecast", "Date"])
print(df.to_html())   #print(df.to_html(index=False)) Without Index

Output:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Forecast</th>
      <th>Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>2018-01-22 05:30:00</td>
      <td>147.01</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2018-01-23 05:30:00</td>
      <td>139.67</td>
    </tr>
    <tr>
      <th>2</th>
      <td>2018-01-24 05:30:00</td>
      <td>140.51</td>
    </tr>
    <tr>
      <th>3</th>
      <td>2018-01-25 05:30:00</td>
      <td>144.68</td>
    </tr>
    <tr>
      <th>4</th>
      <td>2018-01-26 05:30:00</td>
      <td>142.97</td>
    </tr>
    <tr>
      <th>5</th>
      <td>2018-01-27 05:30:00</td>
      <td>151.83</td>
    </tr>
    <tr>
      <th>6</th>
      <td>2018-01-28 05:30:00</td>
      <td>151.93</td>
    </tr>
    <tr>
      <th>7</th>
      <td>2018-01-29 05:30:00</td>
      <td>142.88</td>
    </tr>
    <tr>
      <th>8</th>
      <td>2018-01-30 05:30:00</td>
      <td>157.31</td>
    </tr>
    <tr>
      <th>9</th>
      <td>2018-01-31 05:30:00145.67</td>
      <td>NaN</td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Related Questions