본문 바로가기
Python/Streamlit

[Streamlit]_쉽고 예쁘게 웹을 꾸밀 수 있다고!? - 데이터 표현하기

by ssolLEE 2023. 8. 13.
반응형

Streamlit 포스팅은  BOOKK에서 발간한 "Streamlit으로 프로젝트 한방에 끝내기 with 파이썬"이라는 책을 참고하여 저의 공부 내용을 올립니다. 저자님께 감사드립니다. 또한 streamlit doc의 코드도 일부 변형하였습니다. 감사합니다, Streamlit!

 

Data elements

st.dataframe

  • data 매개변수에 입력할 수 있는 것은 Pandas, PyArrow, Snowpark, PySpark의 데이터프레임에서 실행합니다. 그리고 numpy array, list, set, dictionary와 같이 데이터프레임으로 변환할 수 있는 다른 여러 유형 또한 표현할 수 있습니다. 
  • 30개의 행과 10개의 열을 가진 데이터프레임을 만들겠습니다. 
import streamlit as st
import pandas as pd
import numpy as np

df = pd.DataFrame(
   np.random.randn(30, 10),
   columns=('col %d' % i for i in range(10)))

st.dataframe(df)  # Same as st.write(df)

  • 여기에 다음 명령어를 입력하면, axis=0(세로, 열)기준으로 최댓값을 표시해줍니다. (axis=1 : 행 기준)
st.dataframe(df.style.highlight_max(axis=0))

  • 그리고 column_config, hide_index, column_order로 데이터프레임을 조정할 수 있습니다. 
import random
import pandas as pd
import streamlit as st

df = pd.DataFrame(
    {
        "name": ["Roadmap", "Extras", "Issues"],
        "url": ["https://roadmap.streamlit.app", "https://extras.streamlit.app", "https://issues.streamlit.app"],
        "stars": [random.randint(0, 1000) for _ in range(3)],
        "views_history": [[random.randint(0, 5000) for _ in range(30)] for _ in range(3)],
    }
)
st.dataframe(
    df,
    column_config={
        "name": "App name",
        "stars": st.column_config.NumberColumn(
            "Github Stars",
            help="Number of stars on GitHub",
            format="%d ⭐",
        ),
        "url": st.column_config.LinkColumn("App URL"),
        "views_history": st.column_config.LineChartColumn(
            "Views (past 30 days)", y_min=0, y_max=5000
        ),
    },
    hide_index=True,
)

  • use_container_width 파라미터는 container 너비를 늘려줍니다. 
import pandas as pd
import streamlit as st

# Cache the dataframe so it's only loaded once
@st.cache_data
def load_data():
    return pd.DataFrame(
        {
            "first column": [1, 2, 3, 4],
            "second column": [10, 20, 30, 40],
        }
    )

# Boolean to resize the dataframe, stored as a session state variable
st.checkbox("Use container width", value=False, key="use_container_width")

df = load_data()

# Display the dataframe and allow the user to stretch the dataframe
# across the full width of the container, based on the checkbox value
st.dataframe(df, use_container_width=st.session_state.use_container_width)

 

st.data_editor

  • data editor 위젯을 보여주는 것입니다. UI처럼 데이터프레임이나 데이터 구조를 수정할 수 있습니다.
import streamlit as st
import pandas as pd

df = pd.DataFrame(
    [
       {"command": "st.selectbox", "rating": 4, "is_widget": True},
       {"command": "st.balloons", "rating": 5, "is_widget": True},
       {"command": "st.time_input", "rating": 3, "is_widget": False},
   ]
)
edited_df = st.data_editor(df)

favorite_command = edited_df.loc[edited_df["rating"].idxmin()]["command"]
st.markdown(f"Your favorite command is **{favorite_command}** 🎈")

  • num_row="dynamic" 을 옵션에 추가하면 사용자가 row를 추가하거나 삭제할 수도 있습니다. 
import streamlit as st
import pandas as pd

df = pd.DataFrame(
    [
       {"command": "st.selectbox", "rating": 4, "is_widget": True},
       {"command": "st.balloons", "rating": 5, "is_widget": True},
       {"command": "st.time_input", "rating": 3, "is_widget": False},
   ]
)
# edited_df = st.data_editor(df)
edited_df = st.data_editor(df, num_rows="dynamic")

favorite_command = edited_df.loc[edited_df["rating"].idxmin()]["command"]
st.markdown(f"Your favorite command is **{favorite_command}** 🎈")

  • 다음과 같이 보정할 수도 있습니다.  (column_config, hide_index, column_order 또는 disabled)
df = pd.DataFrame(
    [
        {"command": "st.selectbox", "rating": 4, "is_widget": True},
        {"command": "st.balloons", "rating": 5, "is_widget": False},
        {"command": "st.time_input", "rating": 3, "is_widget": True},
    ]
)
edited_df = st.data_editor(
    df,
    column_config={
        "command": "Streamlit Command",
        "rating": st.column_config.NumberColumn(
            "Your rating",
            help="How much do you like this command (1-5)?",
            min_value=1,
            max_value=5,
            step=1,
            format="%d ⭐",
        ),
        "is_widget": "Widget ?",
    },
    disabled=["command", "is_widget"],
    hide_index=True,
)

favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"]
st.markdown(f"Your favorite command is **{favorite_command}** 🎈")

 

st.table

  • st.dataframe과 다른 점은 table이 고정되어 있다는 것입니다. 
import streamlit as st
import pandas as pd
import numpy as np

df = pd.DataFrame({'Apple' : [2, 2, 3], 'Lemon' : [4, 7, 1]})
st.table(df)

st.metric

  • 주어진 지표를 시각적으로 강조하기 위해 굵고 큰 글씨로 표시하고, 그 변화 정보를 함께 제공해줍니다. 데이터 시각화나 대시보드에 사용하면 유용한 것 중 하나입니다. 
st.metric(label="Temperature", value="70 °F", delta="-1.2 °F")

st.metric(label="Temperature", value="70 °F", delta="+1.2 °F")

  • 컬럼을 이용하여 한 줄에 여러 개를 나타낼 수도 있습니다. 
col1, col2, col3 = st.columns(3)
col1.metric("Temperature", "32℃", '2℃')
col2.metric("Wind", "9 mph", "-8%")
col3.metric("Humidity", "86%", "4%")

  • 변화량(delta)의 색도 바꾸거나 안하는 것을 선택할 수도 있습니다. 
st.metric(label="Gas price", value=4, delta=-0.5,
    delta_color="inverse")

st.metric(label="Active developers", value=123, delta=123,
    delta_color="off")

st.json

  • json string 형태로도 작성할 수 있습니다. 
st.json({
    'foo':'bar',
    'baz':'boz',
    'stuff': [
        'stuff 1',
        'stuff 3',
        'stuff 6',
        'stuff 8',
    ]
})

다음 포스팅에서는 다양한 data type으로 컬럼을 표현하는 것을 실습하겠습니다. 

감사합니다.