[Streamlit] 익히기 프로젝트/Kaggle Exploratory Analysis - Instacart 데이터 활용/ 리뷰
사용된 데이터
https://www.kaggle.com/code/philippsp/exploratory-analysis-instacart
Exploratory Analysis - Instacart
Explore and run machine learning code with Kaggle Notebooks | Using data from Instacart Market Basket Analysis
www.kaggle.com
미완성이지만 혼자 드립다 박으며한 스트림릿 배포 자료
https://market-kawyemybtg4egrbkuwxajt.streamlit.app/
미니 프로젝트의 요지
- Streamlit에서 배운걸 활용하자!
- 분석위주의 내용보다는 기능을 익히기 위한 프로젝트
- 깃허브와 스트림릿 배포 마스터!
코드
# _*_ coding:utf-8 _*_
import streamlit as st
import pandas as pd
import numpy as np
import seaborn as sns
import altair as alt
import matplotlib.pyplot as plt
import matplotlib as mpl
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import plotly as pt
@st.cache_data
def load_data():
orders_df = pd.read_csv("data/order_random.csv")
products_df = pd.read_csv("data/products.csv")
order_products_prior_df = pd.read_csv("data/order_products_prior_random.csv")
aisles_df = pd.read_csv("data/aisles.csv")
departments_df = pd.read_csv("data/departments.csv")
return orders_df, products_df, order_products_prior_df, aisles_df, departments_df
def main():
orders, products, order_products_prior, aisles, departments = load_data()
tab1, tab2, tab3, tab4, tab5 = st.tabs(['orders', 'products', 'order_products_prior', 'aisles', 'departments'])
new_data = products.merge(departments, how ='left', on = 'department_id')
#uni_new_data = new_data['product_name'].unique()
with tab1:
st.write("주문 데이터 :")
st.write(orders)
selected_category = st.sidebar.selectbox("주문데이터", ['사람들의 주문시간', '요일별 데이터'])
if selected_category == '사람들의 주문시간':
st.header("사람들의 주문시간")
fig, ax = plt.subplots()
sns.histplot(x=orders["order_hour_of_day"], kde=False, ax=ax,binwidth=1)
st.pyplot(fig)
elif selected_category == '요일별 데이터':
st.header("요일별 데이터")
fig, ax = plt.subplots()
sns.histplot(x=orders["order_dow"], kde=False, ax=ax)
st.pyplot(fig)
with tab2:
st.write("제품 데이터 :")
st.write(new_data)
selected_category = st.sidebar.selectbox("제품데이터", ['항목별 제품갯수', '항목별 제품종류'])
if selected_category == '항목별 제품갯수':
st.header("항목별 제품갯수")
fig, ax = plt.subplots()
sns.barplot(x=products["department_id"], y=products.index, ax=ax)
ax.set_xticklabels(departments["department"].tolist(), rotation=45, ha="right")
st.pyplot(fig)
elif selected_category == '항목별 제품종류':
st.header("항목별 제품종류")
options = st.selectbox('원하는 항목을 골라 주세요',('frozen','other','bakery',
'produce','alcohol','international','beverages','pets'))
uni = new_data[new_data['department']==options]
st.write('선택된 항목의 제품 종류:', uni['product_name'].unique())
with tab3:
st.write("주문 데이터 :")
st.write(order_products_prior)
with tab4:
st.write("주문 데이터 :")
st.write(aisles)
with tab5:
st.write("주문 데이터 :")
st.write(departments)
if __name__ == "__main__":
main()
order
라이브러리는 주로 사용하는 라이브러리를 이모트 해놓는 편이라 많이 써있지만 주로 사용한건 seaborn, pandas 위주 였던것 같다.
텝과 사이드 바를 통해서 유동적으로 데이터를 확인할 수 있는 스트림릿을 만들고 싶었고 상단에는 각 항목별로 탭을 만들어 데이터 셋을 넣어 주었다.
좌측에는 각 상단항목안에 카테고리를 만들어 사용 할 수 있게끔 만들어 놓았다.
목표는 상단 항목에 해당되는 사이드바만 나오게 하려 했으나 시간상 동일선상에 놓여 지게 만들었다.(추후 수정되면 좋을것 같음)
항목을 선택해서 사람들의 마켓주문시간과 요일별 마켓주문 현황을 알 수 있게 해놓았다.
요일별 데이터의 숫자들을 요일로 대체 시키면 좋을것 같다.
그리고 그래프를 그리는 툴을 Plotly를 활용하여 응답형으로 만드는게 더욱 보기 좋아 보인다.
products
products 항목에선 항목별 제품갯수와 항목별 제품 종류를 알수 있게 해놓았는데
우선 products 데이터셋에 department_id가 칼럼에 있었고 각 id는 숫자로 표기되어 있었다.
그리고 departments데이터셋에는 department_id와 department가 매칭되어 있어 둘을 합치면 용이하게 사용 할 수 있을 것 같아 번호와 항목을 매칭 시켜주었다.
이 데이터를 바탕으로 체크박스를 만들어 항목을 고르면 속해있는 제품만 나오게만들어 주었다.
항목별로 누르면 사람들이 많이 구매한 제품순으로 나오게도 만들 수 있을것 같다.
Github
코드들을 다 짜고 보니 깃허브에 용량이 100MB가 넘는 파일들이 올라가지 않는다는걸 알았다..;;
부랴부랴 100MB넘는 데이터 셋을 3000개씩 랜덤 추출을 하여 데이터셋을 만들어 다시 적용을 하고 git push를 마칠수 있었다.
https://github.com/JiHoonYoon00/market.git
GitHub - JiHoonYoon00/market
Contribute to JiHoonYoon00/market development by creating an account on GitHub.
github.com
Streamlit 배포
스트림릿 배포는 어렵지 않다
Streamlit • A faster way to build and share data apps
Streamlit is an open-source Python framework for machine learning and data science teams. Create interactive data apps in minutes.
streamlit.io
위 사이트에서 로그인을 한 뒤
New app버튼을 눌러준다.
깃허브에 있는 Repository를 불러오고 Main file path항목에 실행시킬 파일을 적어준뒤 Advanced settings...을 눌러 파이썬 버전을 선택해주면된다. 필자는 3.11버전으로 진행하였다.
Save를 누른뒤 Deploy!를 누르면 끝!
이렇게 되면 링크만으로 내가 만든 웹이 실행이 된다!!
※필자는 이 과정에서 Deploy!를 누르고 기다리다가 오류가 떴는데 경로의 문제가 있었다. 바로 절대경로와 상대경로인데 이 차이는 따로 포스팅을 해놓을 예정이다.