Hi there,
I am new to plotly and just started learning on the go.
So i have a pandas dataframe scrapped from a website which is actucally a table.
I am able to add sorting functionality to columns with integers but i noticed its not working properly.I tried in tweaking lot of this but nothing helped me.Please help me find the mistake happend.I dont know if i have to paste all the code or just the layout and callback.So i am posting all the code.
import dash
from dash.dependencies import Input, Output
import dash_table
import requests
import dash_html_components as html
import pandas as pd
from bs4 import BeautifulSoup
link = 'https://www.mohfw.gov.in/'
req = requests.get(link)
soup = BeautifulSoup(req.content, "html.parser")
thead = soup.find_all('thead')[-1]
head = thead.find_all('tr')
tbody = soup.find_all('tbody')[0]
body = tbody.find_all('tr')
head_rows = []
body_rows = []
for tr in head:
td = tr.find_all(['th', 'td'])
row = [i.text for i in td]
head_rows.append(row)
for tr in body:
td = tr.find_all(['th', 'td'])
row = [i.text for i in td]
body_rows.append(row)
df_bs = pd.DataFrame(data=body_rows[:len(body_rows) - 6], columns=head_rows[0])
df_bs.drop('S. No.',axis=1,inplace=True)
app = dash.Dash(__name__)
app.layout = html.Div(id='data-table',
children=[dash_table.DataTable(
id='table-paging-and-sorting',
columns=[
{'name': i, 'id': i, 'deletable': True} for i in df_bs.columns
],
data=df_bs.to_dict('records'),
page_action='custom',
sort_action='custom',
sort_mode='single',
sort_by=[],
style_cell={'textAlign':'center','padding': '5px'},
style_as_list_view=True,
style_header={
'backgroundColor': 'white',
'fontWeight': 'bold'
},
)
]
)
@app.callback(Output('table-paging-and-sorting', 'data'),
[Input('table-paging-and-sorting', 'sort_by')])
def update_table(sort_by):
if len(sort_by):
dff = df_bs.sort_values(
by=sort_by[0]['column_id'],
ascending=sort_by[0]['direction'] == 'asc',
inplace=False
)
print(sort_by[0])
else:
# No sort is applied
dff = df_bs
return dff.to_dict('records')
Thank you so much and have a nice day.Stay safe