Python Dash:将 pandas 数据帧加载到数据表

本教程将介绍Python Dash:将 pandas 数据帧加载到数据表的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

Python Dash:将 pandas 数据帧加载到数据表 教程 第1张

问题描述

最近我一直在尝试用Dash构建一个应用程序,但尽管看了很多指南,我就是想不出怎么将 pandas 数据帧导入到Dash的数据表中(这本质上是 pandas 数据帧,除了网络托管和被动)。

大多数示例说明了怎么手动从已在示例中硬编码的数据帧中挑选特定的列/行,如here中所示。然而,在我的情况下,数据帧是在我的代码中构建的( pandas 是实现这一点的最简单的方法),所以我最终不得不想出一种方法将pd.Dataframe()转换为dash_table.DataTable()

我怎么才能使其工作?使用引用,我尝试了以下代码将我的数据帧的字典发送到dash_table.DataTable(),但没有显示任何内容。

我的代码:

## Imports
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table

from dash.dependencies import Input, Output, State

import datetime as dt
import pandas as pd
import numpy as np

## Custom functions that creates the pandas dataframe
from twitter_functions import old_tweets

app = dash.Dash(dev_tools_hot_reload=True)
app.scripts.config.serve_locally = True
app.config['suppress_callback_exceptions'] = True


app.layout = html.Div(children=[

 html.H3('Twitter App'),

 dcc.Input('ScreenName_Input', type='text'),

 html.Button(id='screenNames_submit_button', children='Submit'),

 dash_table.DataTable(id='tweet_table')

])

@app.callback(
 Output(component_id='tweet_table', component_property='data'),
 [Input(component_id='screenNames_submit_button', component_property='n_clicks_timestamp')],
 [State(component_id='ScreenName_Input', component_property='value')]
)
def display_tweets(submit_button, screen_names):
 tweets = old_tweets(screen_names)

 return tweets.to_dict(orient='records')

if __name__ == '__main__':
 app.run_server(debug=True)

推荐答案

在someone也在策略性论坛上回复我之后(谢天谢地),似乎最终的答案是在你的数据表中预先设置好要在某个时候进入的 pandas 数据框的列,就像这样,

dash_table.DataTable(
 id='table',
 columns=[
 {'name': 'Column 1', 'id': 'column1'},
 {'name': 'Column 2', 'id': 'column2'},
 {'name': 'Column 3', 'id': 'column3'},
 {'name': 'Column 4', 'id': 'column4'},
 {'name': 'Column 5', 'id': 'column5'}]
)

,然后发送您的 pandas 数据帧的字典。

好了关于Python Dash:将 pandas 数据帧加载到数据表的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。