作者:俊欣
來源:關於數據分析與可視化
今天小編帶領大家用Python自製一個自動生成探索性數據分析報告這樣的一個工具,大家只需要在瀏覽器中輸入url便可以輕鬆的訪問,如下所示
第一步
首先我們導入所要用到的模塊,設置網頁的標題、工具欄以及logo的導入,代碼如下
from st_aggrid import AgGrid
import streamlit as st
import pandas as pd
import pandas_profiling
from streamlit_pandas_profiling import st_profile_report
from pandas_profiling import ProfileReport
from PIL import Image
st.set_page_config(layout= 'wide') #Choose wide mode as the default setting
#Add a logo (optional) in the sidebar
logo = Image.open(r 'wechat_logo.jpg')
st.sidebar.image(logo, width=120)
#Add the expander to provide some information about the app
with st.sidebar.expander( "關於這個項目"):
st.write( """
該項目是將streamlit和pandas_profiling相結合,在您上傳數據集之後自動生成相關的數據分析報告,當然該項目提供了兩種模式 全量分析還是部分少量分析,這裡推薦用部分少量分析,因為計算量更少,所需要的時間更短,效率更高
""" )
#Add an app title. Use css to style the title
st.markdown( """ """ , unsafe_allow_html=True)
st.markdown( ' 請上傳您的數據集,該應用會自動生成相關的數據分析報告
output
上傳文件以及變量的篩選
緊接的是我們需要上傳 csv 文件,代碼如下
uploaded_file = st.file_uploader( "請上傳您的csv文件: ", type=[ 'csv'])
我們可以選擇針對數據集當中所有的特徵進行一個統計分析,或者只是針對部分的變量來一個數據分析,代碼如下
ifuploaded_file is not None:
df = pd.read_csv(uploaded_file)
option1 = st.sidebar.radio(
'您希望您的數據分析報告中包含哪些變量呢',
( '所有變量', '部分變量'))
ifoption1 == '所有變量':
df = df
elifoption1 == '部分變量':
var_list = list(df.columns)
要是用戶勾選的是部分變量,只是針對部分變量來進行一個分析的話,就會彈出來一個多選框來供用戶選擇,代碼如下
var_list = list(df.columns)
option3 = st.sidebar.multiselect(
'篩選出您希望在數據分析報告中包含的變量',
var_list)
df = df[option3]
用戶可以挑選到底是「簡單分析」或者是「完整分析」,要是勾選的是「完整分析」的話,會跳出相應的提示,提示「完整分析」由於涉及到更加複雜的計算操作,耗時更加地長,要是遇到大型的數據集,還會有計算失敗的情況出現
option2 = st.sidebar.selectbox(
'篩選模式,完整分析還是簡單分析',
( '簡單分析', '完整分析'))
ifoption2 == '完整分析':
mode = 'complete'
st.sidebar.warning(
'完整分析由於涉及到更加複雜的計算操作,耗時更加地長,要是遇到大型的數據集,還會有計算失敗的情況出現,這裡推薦使用簡單分析')
elifoption2 == '簡單分析':
mode = 'minimal'
grid_response = AgGrid(
df,
editable=True,
height=300,
width= '100%',
)
updated = grid_response[ 'data']
df1 = pd.DataFrame(updated)
當用戶點擊「生成報告」的時候就會自動生成一份完整的數據分析報告了,代碼如下
ifst.button( '生成報告'):
ifmode== 'complete':
profile=ProfileReport(df,
title= "User uploaded table",
progress_bar=True,
dataset={
"簡介": '歡迎關注公眾號:關於數據分析與可視化',
"作者": '俊欣',
"時間": '2022.05'
})
st_profile_report(profile)
elifmode== 'minimal':
profile=ProfileReport(df1,
minimal=True,
title= "User uploaded table",
progress_bar=True,
dataset={
"簡介": '歡迎關注公眾號:關於數據分析與可視化',
"作者": '俊欣',
"時間": '2022.05'
})
st_profile_report(profile)
最後出來的結果如下,這裡再來顯示一遍
點這裡關注我,記得標星哦~
CDA課程諮詢