|
1 | 1 | import pandas as pd |
2 | 2 |
|
3 | | -from shiny import App, Inputs, Outputs, Session, render, ui |
| 3 | +from shiny import App, Inputs, Outputs, Session, reactive, render, ui |
4 | 4 | from shiny.types import FileInfo |
5 | 5 |
|
6 | 6 | app_ui = ui.page_fluid( |
7 | | - ui.layout_sidebar( |
8 | | - ui.panel_sidebar( |
9 | | - ui.input_file("file1", "Choose CSV File", accept=[".csv"], multiple=False), |
10 | | - ui.input_checkbox("header", "Header", True), |
11 | | - width=5, |
12 | | - ), |
13 | | - ui.panel_main( |
14 | | - ui.output_ui("contents"), |
15 | | - ), |
| 7 | + ui.input_file("file1", "Choose CSV File", accept=[".csv"], multiple=False), |
| 8 | + ui.input_checkbox_group( |
| 9 | + "stats", |
| 10 | + "Summary Stats", |
| 11 | + choices=["Row Count", "Column Count", "Column Names"], |
| 12 | + selected=["Row Count", "Column Count", "Column Names"], |
16 | 13 | ), |
| 14 | + ui.output_table("summary"), |
17 | 15 | ) |
18 | 16 |
|
19 | 17 |
|
20 | 18 | def server(input: Inputs, output: Outputs, session: Session): |
| 19 | + @reactive.Calc |
| 20 | + def parsed_file(): |
| 21 | + file: list[FileInfo] = input.file1() |
| 22 | + if file is None: |
| 23 | + return pd.DataFrame() |
| 24 | + return pd.read_csv(file[0]["datapath"]) |
| 25 | + |
21 | 26 | @output |
22 | | - @render.ui |
23 | | - def contents(): |
24 | | - if input.file1() is None: |
25 | | - return "Please upload a csv file" |
26 | | - f: list[FileInfo] = input.file1() |
27 | | - df = pd.read_csv(f[0]["datapath"], header=0 if input.header() else None) |
28 | | - return ui.HTML(df.to_html(classes="table table-striped")) |
| 27 | + @render.table |
| 28 | + def summary(): |
| 29 | + df = parsed_file() |
| 30 | + |
| 31 | + if df.empty: |
| 32 | + return pd.DataFrame() |
| 33 | + |
| 34 | + # Get the row count, column count, and column names of the DataFrame |
| 35 | + row_count = df.shape[0] |
| 36 | + column_count = df.shape[1] |
| 37 | + names = df.columns.tolist() |
| 38 | + column_names = ", ".join(str(name) for name in names) |
| 39 | + |
| 40 | + # Create a new DataFrame to display the information |
| 41 | + info_df = pd.DataFrame( |
| 42 | + { |
| 43 | + "Row Count": [row_count], |
| 44 | + "Column Count": [column_count], |
| 45 | + "Column Names": [column_names], |
| 46 | + } |
| 47 | + ) |
| 48 | + |
| 49 | + # input.stats() is a list of strings; subset the columns based on the selected |
| 50 | + # checkboxes |
| 51 | + return info_df.loc[:, input.stats()] |
29 | 52 |
|
30 | 53 |
|
31 | 54 | app = App(app_ui, server) |
0 commit comments