如何将pandas数据框显示为数据表?
我想将一个表 – 一个pandasdataframe – 显示为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
文件如下所示:
$(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; }); }); Create a pretty table
Number of rows
Number of columns
Result
Number of elements:
Hallo
Here should be a table
我的文件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
Create a pretty table
Number of rows
Number of columns
Result
Number of elements:
Hallo
Here should be a table
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)
我修改了什么:
- 添加了js文件以呈现DataTable。
- 将js文件向下移动到HTML的底部。
- 在使用新数据刷新数据时,在js中添加了一个用于销毁和清除列的检查。
- 使用带有
split
orient的to_json
方法生成DataTables的json数据。 - 还必须为DataTables添加一个
columns
json字符串,这是使用to_json
后动态设置的
以下是如何使用panda的to_html
生成表格:
的index.html
Create a pretty table
Number of rows
Number of columns
Result
Number of elements:
Hallo
Here should be a table
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)
与以前的实施不同:
- 在HTML中,我必须添加父div以保存生成的HTML表。 在这种情况下,我称之为
mytablediv
。 - 在JS方面的HTML中,我必须在生成数据后基本修改
mytablediv
的HTML内容。 此HTML内容来自to_html
输出。 - 在JS方面的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表的示例。