簡體   English   中英

檢查大量輸入組合的最優雅的方法是什么?

[英]What is the most elegant way to check a large combination of inputs?

我有一個顯示 11 個復選框的 web 應用程序。 選中后,應用程序會返回與所選框對應的數據圖表。

因為最終用戶可以 select 這些框的任何變體,並且應該期望只看到那些選擇的圖形,所以必須聲明每個可能的組合。

目前,我的實現如下。 它非常簡單,可能需要幾個小時,所以你可以明白我為什么要尋找更多的東西......柔順?

Discretionary = st.sidebar.checkbox(label = 'Consumer Discretionary', value = False)
Consumer_Staples = st.sidebar.checkbox(label = 'Consumer Staples', value = False)
Energy = st.sidebar.checkbox(label = 'Energy', value = False)
Financials = st.sidebar.checkbox(label = 'Financials', value = False)
Healthcare = st.sidebar.checkbox(label = 'Healthcare', value = False)
Industrials = st.sidebar.checkbox(label = 'Industrials', value = False)
Materials = st.sidebar.checkbox(label = 'Materials', value = False)
Real_Estate = st.sidebar.checkbox(label = 'Real Estate', value = False)
Technology = st.sidebar.checkbox(label = 'Technology', value = False)
Utilities = st.sidebar.checkbox(label = 'Utilities', value = False)


Placeholder = st.empty()

for a in range(0, 500):
    try:
        Data = pd.read_csv('Mydata')
        Data = Data.set_index('Time')
    except:
        pass    
    
    if Communications == True and Discretionary == True:
    
        with Placeholder.container():             
            st.line_chart(data = Data[['Communications','CD Consumer Discretionary']] * 100)
            
    elif Communications == True and Discretionary == False:
    
    
        with Placeholder.container():     
            st.line_chart(data = Data['Communications'] * 100)
            
    elif Discretionary == True and Communications == False:
    
        with Placeholder.container():
            st.line_chart(data = Data['CD Consumer Discretionary'] * 100)```

這個問題不是關於排列/組合(不需要),而是關於過濾

我將以以下簡化的 dataframe 為例,用於本文的 rest。

import pandas as pd
import streamlit as st

df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})

您可以做的第一件事是簡化事情,將您的復選框重新組合在字典中。 如果您有 20 列,它可以讓您免於編寫 20 行代碼,並且使您以后更容易適應新列

checkboxes = {
    col_name: st.sidebar.checkbox(label=col_name, value=False)
    for col_name in df.columns
}

然后,您可以定義一個過濾數據的 function,只保留選中復選框的列:

def filter_columns(df: pd.DataFrame, checkboxes: dict[str, bool]):
    selected_cols = [col for col, sel in checkboxes.items() if sel]
    return df[selected_cols]

然后過濾您的數據並顯示它:

df_filtered = filter_columns(df, checkboxes)
st.dataframe(df_filtered)

如果您復制此示例的所有代碼塊,您應該有一個功能正常的流式應用程序。 您現在只需使數據集適應您的特定需求。

過濾數據后,創建圖表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM