I like to filter my df based on dates. What I’m aiming for is to have a calendar wherein I can choose the dates from and based on the dates chosen, the df will filter the result, which is the sum of the same values (in this case, ‘Name’). Here’s how my df looks like.
Here’s my code:
from datetime import datetime as dt
import dash
from dash.dependencies import Input, Output, State
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
raw = [['tom', 10, pd.to_datetime('2021-01-01')], ['tom', 5, pd.to_datetime('2021-01-01')], ['nick', 15, pd.to_datetime('2021-01-01')], ['nick', 8, pd.to_datetime('2021-01-01')], ['juli', 14, pd.to_datetime('2021-01-01')],['juli', 7, pd.to_datetime('2021-01-01')],
['tom', 8, pd.to_datetime('2021-01-02')], ['tom', 3, pd.to_datetime('2021-01-02')], ['nick', 4, pd.to_datetime('2021-01-02')], ['nick', 1, pd.to_datetime('2021-01-02')],['juli', 12, pd.to_datetime('2021-01-02')], ['juli', 6, pd.to_datetime('2021-01-02')]]
df = pd.DataFrame(raw, columns=['Name', 'Apples Gathered', 'date'])
df['date'] = df['date'].dt.strftime('%Y-%m-%d')
#App layout
app = dash.Dash(__name__, prevent_initial_callbacks=True, suppress_callback_exceptions=True)
app.layout = html.Div([
dcc.DatePickerRange(
id='datepicker',
display_format='DD-MM-YYYY',
first_day_of_week=1,
min_date_allowed=dt(2021, 1, 1),
max_date_allowed=dt(2021,1,5),
),
])
dash_table.DataTable(
id='datatable',
columns=[
{'id': 'Name', 'name': 'Name'},
{'id': 'Apples Gathered', 'name': 'Apples Gathered'},
{'id': 'date', 'name': 'date'}],
data = df.to_dict('records'),
)
@app.callback(
[Output('datatable', 'data'), Output('datatable', 'columns')],
[Input('datepicker', 'start_date'),
Input('date-picker', 'end_date')]
)
def update_table(start_date, end_date):
#dff = [(df['date'].dt.date.astype(str) > start_date) & (df['date'].dt.date.astype(str) < end_date)]
data = (df.groupby(['Name']).sum())
fdata = data.to_dict('records')
columns = [
{'id': 'Name', 'name': 'Name'},
{'id': 'Apples Gathered', 'name': 'Apples Gathered'}]
return fdata, columns
if __name__ == '__main__':
app.run_server(debug=True)
When I ran that code, the date column is still in the df and the calendar is not linked. How do I fix the callback function so I can filter based on the dates.