How to Show a Pandas Dataframe into a Existing Flask HTML Table

How to show a pandas dataframe into a existing flask html table?

working example:

python code:

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>

or else use

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

and remove {{titles[loop.index]}} line from html

if you inspect element on 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>

Show pandas dataframe in an existing flask html table, and send in parameter for subset in get?

You just need to query your dataframe before making the table.

#not sure why you need POST but Okay
@app.route('/<id>',methods=("POST", "GET"))
def page(id):
subset_id = id
df_filtered = df.loc[df["<id_column_name>"]==subset_id]
return render_template('simple.html', tables=[df_filtered.to_html(classes='data')], titles=df.columns.values)

Flask: How can I add a table with pandas dataframe

panda work with flask its not an issue..
This is the syntax what i used and it works fine...
render_template('index.html') without slash and template is in 'templates' folder

def index():
data = pd.read_csv("data.csv")
data.set_index(['Name'], inplace=True)
data.index.name=None

df = data.loc[data.Sex=='male']
df = df[['Sex']]
return render_template('index.html',tables=[df.to_html(header=False)],titles=['na','Males'])

How to show a pandas dataframe as a flask-boostrap table?

The problem here is with the data.csv file. When you do read_csv() on it:

In [45]: pd.read_csv("/tmp/a.csv")
Out[45]:
Name Birth Month Origin Age Gender
0 Carly Jan Uk 10 F
1 Rachel Sep UK 20 F
2 Nicky Sep MEX 30 F
3 Wendy Oct UK 40 F
4 Judith Nov MEX 39 F

In [46]: df = pd.read_csv("/tmp/a.csv")

In [47]: df.columns
Out[47]: Index([u'Name Birth Month Origin Age Gender'], dtype='object')

As you can see, there is only one column, instead of four, because it can't understand that 'Birth Month' is supposed to be one column. To fix this, you can open the file and change the first line to:

"Name" "Birth Month" "Origin"  "Age" "Gender"

And, then while reading the csv:

In [62]: pd.read_csv("/tmp/a.csv", sep='\s+', quotechar='"')
Out[62]:
Name Birth Month Origin Age Gender
0 Carly Jan Uk 10 F
1 Rachel Sep UK 20 F
2 Nicky Sep MEX 30 F
3 Wendy Oct UK 40 F
4 Judith Nov MEX 39 F

Or you could have also just changed Birth Month to Birth_Month

For the '404 Not Found' error, the problem is that you have not defined any route for '/'. So, (after editing the header of the csv) I would do something like:

from flask import *
import pandas as pd
app = Flask(__name__)

@app.route("/tables")
def show_tables():
data = pd.read_csv("/tmp/a.csv", sep='\s+', quotechar='"')
data.set_index(['Name'], inplace=True)
data.index.name=None
females = data.loc[data.Gender=='F']
return render_template('view.html',tables=[females.to_html(classes='female')],

titles = ['na', 'Female surfers'])

@app.route("/")
def show_home():
return "Hello Guys! Visit: <a href='/tables'> this link </a>"

if __name__ == "__main__":
app.run(debug=True)

Pandas Dataframe display on a webpage

The following should work:

@app.route('/analysis/<filename>')
def analysis(filename):
x = pd.DataFrame(np.random.randn(20, 5))
return render_template("analysis.html", name=filename, data=x.to_html())
# ^^^^^^^^^

Check the documentation for additional options like CSS styling.

Additionally, you need to adjust your template like so:

{% extends "base.html" %}
{% block content %}
<h1>{{name}}</h1>
{{data | safe}}
{% endblock %}

in order to tell Jinja you're passing in markup. Thanks to @SeanVieira for the tip.

Flask return pd dataframe groupby - how to delete column that is used to group?

Try this:

import io
import pandas

from flask import Flask, jsonify

# Create a flask app
app = Flask(__name__)


@app.route("/")
def index():

# Your data
data = io.StringIO(
"""
id VALUE1 VALUE2 VALUE3
1 1 11 abc
2 1 22 def
3 2 33 ghi
4 2 44 jkl
"""
)
df = pandas.read_table(data, sep="\s+")

# Create a placeholder for the output
output = {}

# Loop all the groups in your groupby
for group_id, group in df.groupby('VALUE1'):

# Add a dict representation of the group to the output, without the columns you don't want
output[group_id] = group.drop(columns=["VALUE1", "id"]).to_dict(orient="records")


# Return the output in JSON format
return jsonify(output)


if __name__ == "__main__":
app.run(debug=True)

Output:

{
"1": [
{
"VALUE2": 11,
"VALUE3": "abc"
},
{
"VALUE2": 22,
"VALUE3": "def"
}
],
"2": [
{
"VALUE2": 33,
"VALUE3": "ghi"
},
{
"VALUE2": 44,
"VALUE3": "jkl"
}
]
}

pandas/flask: buttons to download dataframes

What ended up working was including the file-creation commands in the first view along with the dataframes, then setting a session variable to pass the file name of the output file to the download view.

def df_test():
df1 = pd.DataFrame(
{
'terms' : ['term1','term2'],
'code1': ['1234x', '4321y'],
'code2': ['2345x','5432y'],
'code3': ['3456x','6543y']
}
)
df2 = pd.DataFrame(
{
'name': ['Dan','Sara','Conroy'],
'rate': ['3','3.5','5.2'],
'location': ['FL','OH','NM'],
'code': ['4444g','6543y','2345x']
})
writer = pd.ExcelWriter(output_file, engine='xlsxwriter')
df1.to_excel(writer, sheet_name="Codes")
df2.to_excel(writer, sheet_name="People")
workbook = writer.book
worksheet1 = writer.sheets['Codes']
worksheet2 = writer.sheets['People']
writer.save()
return render_template('view.html',tables=[df1.to_html(classes='female'), df2.to_html(classes='male')],
titles = ['na', 'Codes', 'People'])
output_file = 'codes_people.xlsx'

session['otpt_file'] = 'tmp/' + output_file


def download_df():
output_file = session.get('otpt_file', None)
#return output_file
return send_file(output_file, attachment_filename='output.xlsx', as_attachment=True,mimetype='text/xlsx')


Related Topics



Leave a reply



Submit