web-dev-qa-db-fra.com

Comment afficher un pandas dataframe dans un tableau existant flask html?

Cela peut sembler une question de noob, mais je suis coincé avec comme Python n'est pas l'un de mes meilleurs langages.

J'ai une page html avec un tableau à l'intérieur et j'aimerais afficher un fichier de données pandas. Quelle est la meilleure façon de le faire? Utilisez pandasdataframe.to_html?

py

from flask import Flask;
import pandas as pd;
from pandas import DataFrame, read_csv;

file = r'C:\Users\myuser\Desktop\Test.csv'
df = pd.read_csv(file)
df.to_html(header="true", table_id="table")

html

<div class="table_entrances" style="overflow-x: auto;">

  <table id="table">

    <thead></thead> 
    <tr></tr>

  </table>

</div>
13
Motta

exemple de travail:

code python:

from flask import Flask, request, render_template, session, redirect
import numpy as np
import pandas as pd


app = Flask(__name__)

df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                   'B': [5, 6, 7, 8, 9],
                   'C': ['a', 'b', 'c--', 'd', 'e']})


@app.route('/', methods=("POST", "GET"))
def html_table():

    return render_template('simple.html',  tables=[df.to_html(classes='data')], titles=df.columns.values)



if __name__ == '__main__':
    app.run(Host='0.0.0.0')

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% for table in tables %}
            {{titles[loop.index]}}
            {{ table|safe }}
{% endfor %}
</body>
</html>

ou bien utiliser

return render_template('simple.html',  tables=[df.to_html(classes='data', header="true")])

et retirez {{titles[loop.index]}} ligne de html

si vous inspectez élément sur html

<html lang="en"><head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body style="">


            <table border="1" class="dataframe data">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>0</td>
      <td>5</td>
      <td>a</td>
    </tr>
    <tr>
      <th>1</th>
      <td>1</td>
      <td>6</td>
      <td>b</td>
    </tr>
    <tr>
      <th>2</th>
      <td>2</td>
      <td>7</td>
      <td>c--</td>
    </tr>
    <tr>
      <th>3</th>
      <td>3</td>
      <td>8</td>
      <td>d</td>
    </tr>
    <tr>
      <th>4</th>
      <td>4</td>
      <td>9</td>
      <td>e</td>
    </tr>
  </tbody>
</table>


</body></html>

comme vous pouvez le voir, il a tbody et thead avec dans le tableau html. afin que vous puissiez facilement appliquer css.

16
Nihal
# Declare table
class SomeTable(Table):
    status = Col('Customer')
    city = Col('City')
    product_price = Col('Country')    

# Convert the pandas Dataframe into dictionary structure
output_dict = output.to_dict(orient='records')  

# Populate the table
table = SomeTable(output_dict)

return (table.__html__())

ou as pandas retourne un fichier HTML statique que vous pouvez rendre en tant que page en utilisant Flask

@app.route('/<string:filename>/')
def render_static(filename):
    return render_template('%s.html' % filename)

C'est l'idée de comment nous pouvons le faire dans Flask. J'espère que vous pouvez comprendre cela et laissez-moi savoir si cela ne vous aide pas!

Mise à jour:

import pandas as pd

df = pd.DataFrame({'col1': ['abc', 'def', 'tre'],
                   'col2': ['foo', 'bar', 'stuff']})


from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return df.to_html(header="true", table_id="table")

if __name__ == '__main__':
    app.run(Host='0.0.0.0', debug=True)

Output

Mais je choisirais avec Flask HTML plutôt que DataFrame to HTML (en raison du style)

8
CSMaverick

Au cas où quelqu'un trouverait cela utile. J'ai opté pour une alternative car j'avais besoin de plus de personnalisation, y compris la possibilité d'ajouter des boutons dans la table effectuant des actions. De plus, je n'aime vraiment pas le formatage standard des tableaux car il est très moche à mon humble avis.

...

df = pd.DataFrame({'Patient Name': ["Some name", "Another name"],
                       "Patient ID": [123, 456],
                       "Misc Data Point": [8, 53]})
...

# link_column is the column that I want to add a button to
return render_template("patient_list.html", column_names=df.columns.values, row_data=list(df.values.tolist()),
                           link_column="Patient ID", Zip=zip)

Code HTML: Ceci convertit dynamiquement n'importe quel DF dans un tableau HTML personnalisable

<table>
    <tr>
        {% for col in column_names %}
        <th>{{col}}</th>
        {% endfor %}
    </tr>
    {% for row in row_data %}
    <tr>
        {% for col, row_ in Zip(column_names, row) %}
        {% if col == link_column %}
        <td>
            <button type="submit" value={{ row_ }} name="person_id" form="patient_form" class="patient_button">
                {{ row_ }}
            </button>
        </td>
        {% else %}
        <td>{{row_}}</td>
        {% endif %}
        {% endfor %}
    </tr>
    {% endfor %}

</table>

Code CSS

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}

Il fonctionne très bien et semble beaucoup mieux que le .to_html sortie.

3
Chris Farr

Pour moi en utilisant Jinja pour la boucle

{% for table in tables %}
            {{titles[loop.index]}}
            {{ table|safe }}
{% endfor %}

ne fonctionnait pas car il imprimait simplement chaque caractère 1 sur 1. Je devais simplement utiliser

{{ table|safe }}
1
Biarys