簡體   English   中英

如何使用python在Dash中將html_Table轉換為pandas數據幀?

[英]How to convert html_Table to pandas dataframe in Dash using python?

我在 Dash 中有一個 Pandas 數據框,它在使用以下函數返回到 html.Div() 之前被轉換為 HTML -

def generate_table(dataframe, max_rows=10):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

這將再次成為回調中的輸入,我需要將 html 表轉換為數據框以允許我對其列執行計算。 我試過這個 - [雖然沒有幫助]

@app.callback(
    [Output("newtable", "children")],
    [Input("mastertable", "children"),
     ])
def performcalc(x):
    if not x is None:
        tb = pd.read_html(str([x])) # this is not working
        ## Perfomr calculations on dataframe ##
        return [tb]
    return None

如何將 html 輸入轉換為 Pandas 數據框?

此外,表格的最后一行將是匯總行,即各列的總和。 當我將它返回到 Div 時,我想傳遞一條將值與摘要行分開的行。 像這樣的東西——

Col1  Col2  Col3
 1     2     3
 3     2     1
----------------
 4     4     4

感謝您的幫助是提前。

謝謝@coralvanda 的建議。 使用破折號表解決了這個問題。

import pandas as pd
import dash_table as dt

## Render dataframe as datatable
# Where, DF = pd.DataFrame object
dt.DataTable(
    columns=[{"name": i, "id": i} for i in DF.columns],
    data=DF.to_dict('records')
)
## Convert datatable from an Input in callback function to dataframe.
# Where x is callback input

finalDF = pd.DataFrame(x['props']['data'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM