File size: 2,557 Bytes
bc3dac0
 
1f2a564
 
 
 
 
 
 
 
bc3dac0
2a377cc
bc3dac0
2a377cc
 
 
 
bc3dac0
2a377cc
 
 
1f2a564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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