如何使用 python 在 Dash 中将 html_Table 转换为 pandas 数据帧?
How to convert html_Table to pandas dataframe in Dash using python?
我在 Dash 中有一个 pandas 数据帧,它在使用以下函数被 returned 到 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 table 转换为数据框以允许我对其列执行计算。我试过这个 - [虽然没有帮助]
@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 数据帧?
此外,table 的最后一行将成为摘要行,即各列的总和。当我 return 到 Div 时,我想传递一条线将值与摘要行分开。像这样 -
Col1 Col2 Col3
1 2 3
3 2 1
----------------
4 4 4
感谢您的提前帮助。
感谢@coralvanda 的建议。使用 Dash 表解决了这个问题。
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'])
我在 Dash 中有一个 pandas 数据帧,它在使用以下函数被 returned 到 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 table 转换为数据框以允许我对其列执行计算。我试过这个 - [虽然没有帮助]
@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 数据帧?
此外,table 的最后一行将成为摘要行,即各列的总和。当我 return 到 Div 时,我想传递一条线将值与摘要行分开。像这样 -
Col1 Col2 Col3
1 2 3
3 2 1
----------------
4 4 4
感谢您的提前帮助。
感谢@coralvanda 的建议。使用 Dash 表解决了这个问题。
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'])