[英]How to display a pandas dataframe as datatable?
我想将一个表 - 一个pandas数据帧 - 显示为DataTable 。 在下面的简化示例中,我读取了用户提供的两个数字,用于确定表的行号和列号。 然后,正确显示此表的元素数,但不会显示该表。
我认为问题是我以错误的方式传递了表格。 当我尝试
return jsonify(number_elements=a * b,
my_table=df)
我收到了错误
anaconda2 / lib / python2.7 / json / encoder.py“,第184行,默认情况下引发TypeError(repr(o)+”不是JSON可序列化的“)
TypeError:0 1 2 3 0 51 35 10 84 1 30 60 79 24不是JSON可序列化的
如果我使用
return jsonify(number_elements=a * b,
my_table=df.to_json())
然后没有错误,但表仍然没有显示。
我该如何正确地做到这一点?
我的index.html
文件如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"
rel="stylesheet">
<script type=text/javascript>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON('/_get_table', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#elements").text(data.number_elements);
$("#a_nice_table").DataTable(data.my_table);
});
return false;
});
});
</script>
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Create a pretty table</h3>
</div>
<div>
<p>Number of rows</p>
<input type="text" size="5" name="a" value="2">
<p>Number of columns</p>
<input type="text" size="5" name="b" value="4">
<p><a href="javascript:void();" id="calculate">get a pretty table</a></p>
<p>Result</p>
<p>Number of elements:</p>
<span id="elements">Hallo</span><br>
<span id="a_nice_table">Here should be a table</span>
</div>
</div>
</body>
</html>
我的文件app.py
看起来像这样:
from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
# Initialize the Flask application
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/_get_table')
def get_table():
a = request.args.get('a', type=int)
b = request.args.get('b', type=int)
df = pd.DataFrame(np.random.randint(0, 100, size=(a, b)))
return jsonify(number_elements=a * b,
my_table=df)
if __name__ == '__main__':
app.run(debug=True)
这是我的实施。 我做了一些优化,例如将js文件移动到HTML的末尾:
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Create a pretty table</h3>
</div>
<div>
<p>Number of rows</p>
<input type="text" size="5" name="a" value="2">
<p>Number of columns</p>
<input type="text" size="5" name="b" value="4">
<p><a href="javascript:void();" id="calculate">get a pretty table</a></p>
<p>Result</p>
<p>Number of elements:</p>
<span id="elements">Hallo</span><br>
<table id="a_nice_table">Here should be a table</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = null;
$('a#calculate').bind('click', function() {
$.getJSON('/_get_table', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#elements").text(data.number_elements);
if (table !== null) {
table.destroy();
table = null;
$("#a_nice_table").empty();
}
table = $("#a_nice_table").DataTable({
data: data.my_table,
columns: data.columns
});
});
return false;
});
});
</script>
</body>
</html>
app.py
from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
import json
# Initialize the Flask application
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/_get_table')
def get_table():
a = request.args.get('a', type=int)
b = request.args.get('b', type=int)
df = pd.DataFrame(np.random.randint(0, 100, size=(a, b)))
return jsonify(number_elements=a * b,
my_table=json.loads(df.to_json(orient="split"))["data"],
columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]])
if __name__ == '__main__':
app.run(debug=True)
我修改了什么:
split
orient的to_json
方法生成DataTables的json数据。 columns
json字符串,这是使用to_json
后动态设置的 以下是如何使用panda的to_html
生成表格:
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Create a pretty table</h3>
</div>
<div>
<p>Number of rows</p>
<input type="text" size="5" name="a" value="2">
<p>Number of columns</p>
<input type="text" size="5" name="b" value="4">
<p><a href="javascript:void();" id="calculate">get a pretty table</a></p>
<p>Result</p>
<p>Number of elements:</p>
<span id="elements">Hallo</span><br>
<div id="mytablediv">Here should be a table</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = null;
$('a#calculate').bind('click', function() {
$.getJSON('/_get_table', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#elements").text(data.number_elements);
if (table !== null) {
table.destroy();
table = null;
$("#a_nice_table").empty();
}
$("#mytablediv").html(data.my_table);
table = $("#a_nice_table").DataTable();
});
return false;
});
});
</script>
</body>
</html>
app.py
from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
# Initialize the Flask application
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index2.html')
@app.route('/_get_table')
def get_table():
a = request.args.get('a', type=int)
b = request.args.get('b', type=int)
df = pd.DataFrame(np.random.randint(0, 100, size=(a, b)))
return jsonify(number_elements=a * b,
my_table=df.to_html(classes='table table-striped" id = "a_nice_table',
index=False, border=0))
if __name__ == '__main__':
app.run(debug=True)
与以前的实施不同:
mytablediv
。 mytablediv
的HTML内容。 此HTML内容来自to_html
输出。 DataTable
函数中,因为这将使用HTML代码处理。 app.py
,我不得不使用hackey方法为pandas生成HTML ID标记。 ID标签让JS知道要修改的元素。 我用过这里的解决方案。 app.py
,因为我现在正在生成HTML,所以我还必须明确指定其他表格样式选项,例如border=0
和index=False
以模仿前一个实现。 你不应该先生成一个html
表吗? 利用pandas.DataFrame.to_html()
函数? 实际上, DataTables的文档显示了使用html表的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.