Spaces:
Runtime error
Runtime error
Download utils.py from Archon/streamlit-parent: direct link, hf CLI and curl.
- Browser
- Download file 2.56 kB
-
https://huggingface.co/spaces/Archon/streamlit-parent/resolve/main/utils.py
- Command line
-
hf download hf://spaces/Archon/streamlit-parent/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/Archon/streamlit-parent/resolve/main/utils.py
2.56 kB
| import os | |
| import pandas as pd | |
| import streamlit as st | |
| from pandas.api.types import ( | |
| is_categorical_dtype, | |
| is_datetime64_any_dtype, | |
| is_numeric_dtype, | |
| ) | |
| def get_absolute_path(python__file__: str, sub_path: str) -> str: | |
| """ | |
| Get absolute path of a sub-path relative to the python file. | |
| :param python__file__: | |
| :param sub_path: | |
| :return: | |
| """ | |
| if not os.path.isabs(sub_path): | |
| sub_path = os.path.join(os.path.dirname(python__file__), sub_path) | |
| return sub_path | |
| def add_filter_widget_and_filter_dataframe( | |
| df: pd.DataFrame, columns: list[str] = None | |
| ) -> pd.DataFrame: | |
| """ | |
| Adds a UI on top of a dataframe to let viewers filter columns | |
| Args: | |
| :param df: Original dataframe | |
| :param columns: filter columns | |
| Returns: | |
| pd.DataFrame: Filtered dataframe | |
| """ | |
| if columns is None: | |
| columns = df.columns | |
| for column in columns: | |
| # Treat columns with < 10 unique values as categorical | |
| if is_categorical_dtype(df[column]) or df[column].nunique() < 10: | |
| user_cat_input = st.multiselect( | |
| f"请选择: {column}", | |
| df[column].unique(), | |
| default=list(df[column].unique()), | |
| ) | |
| df = df[df[column].isin(user_cat_input)] | |
| elif is_numeric_dtype(df[column]): | |
| _min = float(df[column].min()) | |
| _max = float(df[column].max()) | |
| step = (_max - _min) / 100 | |
| user_num_input = st.slider( | |
| f"请选择: {column}", | |
| _min, | |
| _max, | |
| (_min, _max), | |
| step=step, | |
| ) | |
| df = df[df[column].between(*user_num_input)] | |
| elif is_datetime64_any_dtype(df[column]): | |
| user_date_input = st.date_input( | |
| f"请选择: {column}", | |
| value=( | |
| df[column].min(), | |
| df[column].max(), | |
| ), | |
| ) | |
| if len(user_date_input) == 2: | |
| user_date_input = tuple(map(pd.to_datetime, user_date_input)) | |
| start_date, end_date = user_date_input | |
| df = df.loc[df[column].between(start_date, end_date)] | |
| else: | |
| user_text_input = st.text_input( | |
| f"Substring or regex in {column}", | |
| ) | |
| if user_text_input: | |
| df = df[df[column].str.contains(user_text_input)] | |
| return df | |