如何将 pandas 数据框显示为数据表? [英] How to display a pandas dataframe as datatable?

查看:102
本文介绍了如何将 pandas 数据框显示为数据表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示一个表格-这是一个熊猫数据框-作为 DataTable DataTable .在下面的简化示例中,我读取了用户提供的两个数字,这些数字确定了表的行号和列号.然后可以正确显示该表的元素数,但是,该表没有出现.

I want to display a table - which is a pandas dataframe - as a DataTable. In the simplified example below, I read two numbers provided by a user, that determine the row and column number of the table. The number of elements of this table is then displayed correctly, however, the table does not appear.

我认为问题是我以错误的方式传递了表格.当我尝试

The problem is, I think, that I pass the table in the wrong way. When I try

return jsonify(number_elements=a * b,
                   my_table=df)

我得到了错误

anaconda2/lib/python2.7/json/encoder.py",默认情况下,第184行 引发TypeError(repr(o)+不是JSON可序列化的")

anaconda2/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable")

TypeError:0 1 2 3 0 51 35 10 84 1 30 60 79 24不是JSON 可序列化

TypeError: 0 1 2 3 0 51 35 10 84 1 30 60 79 24 is not JSON serializable

如果我使用

return jsonify(number_elements=a * b,
                   my_table=df.to_json())

那么就没有错误,但是表格仍然没有显示.

then there is no error but the table is still not displayed.

我该如何正确执行此操作?

How would I do this correctly?

我的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看起来像这样:

And my file app.py looks like this:

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的末尾:

Here's my implementation. I did some optimizations such as moving your js files to the end of the 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)

我修改了什么

  1. 添加了js文件以呈现数据表.
  2. 将js文件下移到HTML的底部.
  3. 在js中添加了一项检查,以在用新数据刷新数据时销毁和清除列.
  4. 使用to_json方向的to_json方法为DataTables生成json数据.
  5. 还必须添加一个columns json字符串以供DataTable使用,该字符串在使用to_json
  6. 后会动态设置
  1. Added the js file to render the DataTable.
  2. Moved the js files down to the bottom of the HTML.
  3. Added a check in the js to destroy and clear columns when refreshing the data with new data.
  4. Used the to_json method with orient of split to generate the json data for DataTables.
  5. Also had to add a columns json string for DataTables to consume, which is dynamically set after using to_json


以下是使用熊猫的to_html生成表格的方法:


Here's how to use panda's to_html for generating the table:

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)

与以前的实现方式不同:

Differences from former implementation:

  1. 在HTML中,我必须添加一个父div才能容纳生成的HTML表.在这种情况下,我将其称为mytablediv.
  2. 在JS端的HTML中,生成数据后,我必须基本上修改mytablediv的HTML内容.这些HTML内容来自to_html输出.
  3. 在JS端的HTML中,我不必再将数据传递到DataTable函数中,因为这将由HTML代码处理.
  4. app.py中,我不得不对熊猫使用hackey方法来生成HTML ID标签. ID标签使JS知道要修改的元素.我从此处使用了该解决方案.
  5. app.py中,因为我现在正在生成HTML,所以我还必须显式指定其他表样式选项(例如border=0index=False)以模仿以前的实现.
  1. In the HTML, I had to add a parent div in order to hold the generated HTML table. In this case, I called it mytablediv.
  2. In the HTML on the JS side, I have to basically modify the HTML content of the mytablediv after I generate my data. This HTML content comes from the to_html output.
  3. In the HTML on the JS side, I didn't have to pass anymore data into the DataTable function because that would be handled with HTML code.
  4. In app.py, I had to use a hackey method for pandas to generate an HTML ID tag. The ID tag lets JS know what element to modify. I used the solution from here.
  5. In app.py, because I'm now generating HTML, I have to also explicitly specify other table style options like border=0 and index=False to mimic the former implementation.

这篇关于如何将 pandas 数据框显示为数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆