File size: 6,755 Bytes
92a085a
 
f076a08
cc89531
 
92a085a
f076a08
cc89531
23711c4
cc89531
 
1a09a89
1d927a2
1a09a89
1d927a2
1a09a89
1d927a2
 
f076a08
 
 
 
 
 
 
 
cc89531
f076a08
 
 
 
cc89531
 
f076a08
 
 
d089e25
900c0ad
f076a08
1a09a89
900c0ad
d089e25
f076a08
 
900c0ad
cc89531
900c0ad
cc89531
900c0ad
cc89531
900c0ad
 
cc89531
 
 
900c0ad
cc89531
900c0ad
cc89531
900c0ad
cc89531
900c0ad
 
cc89531
900c0ad
 
 
 
cc89531
900c0ad
cc89531
f076a08
900c0ad
 
71227fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eacbd49
900c0ad
cc89531
f076a08
71227fd
 
 
 
 
 
cc89531
 
71227fd
f076a08
cc89531
 
71227fd
f076a08
cc89531
 
 
f076a08
cc89531
f076a08
eacbd49
 
 
 
 
 
 
 
23711c4
eacbd49
 
 
23711c4
 
 
 
 
 
 
eacbd49
 
 
23711c4
 
 
 
 
 
 
 
 
 
 
cc89531
92a085a
eacbd49
 
 
 
92a085a
900c0ad
cc89531
92a085a
cc89531
92a085a
cc89531
 
f076a08
 
 
 
 
 
 
 
1a09a89
 
 
 
d089e25
1a09a89
 
92a085a
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from io import StringIO
import openpyxl
import matplotlib.font_manager as fm
from scipy import stats

# ν•œκΈ€ 폰트 μ„€μ •
def set_font():
    font_path = "Pretendard-Bold.ttf"  # μ‹€μ œ 폰트 파일 경둜둜 λ³€κ²½ν•΄μ£Όμ„Έμš”
    fm.fontManager.addfont(font_path)
    return {'font.family': 'Pretendard-Bold', 'axes.unicode_minus': False}

# 폰트 섀정을 κ°€μ Έμ˜΅λ‹ˆλ‹€
font_settings = set_font()

def load_data(file):
    file_extension = file.name.split('.')[-1].lower()
    if file_extension == 'csv':
        data = pd.read_csv(file)
    elif file_extension in ['xls', 'xlsx']:
        data = pd.read_excel(file)
    else:
        st.error("μ§€μ›λ˜μ§€ μ•ŠλŠ” 파일 ν˜•μ‹μž…λ‹ˆλ‹€. CSV, XLS, λ˜λŠ” XLSX νŒŒμΌμ„ μ—…λ‘œλ“œν•΄μ£Όμ„Έμš”.")
        return None
    return data

def manual_data_entry():
    st.subheader("μˆ˜λ™ 데이터 μž…λ ₯")
    col_names = st.text_input("μ—΄ 이름을 μ‰Όν‘œλ‘œ κ΅¬λΆ„ν•˜μ—¬ μž…λ ₯ν•˜μ„Έμš”:").split(',')
    col_names = [name.strip() for name in col_names if name.strip()]
    
    if col_names:
        num_rows = st.number_input("초기 ν–‰μ˜ 수λ₯Ό μž…λ ₯ν•˜μ„Έμš”:", min_value=1, value=5)
        data = pd.DataFrame(columns=col_names, index=range(num_rows))
        
        edited_data = st.data_editor(data, num_rows="dynamic")
        
        return edited_data
    return None

def preprocess_data(data):
    st.subheader("데이터 μ „μ²˜λ¦¬")
    
    # 결츑치 처리
    if data.isnull().sum().sum() > 0:
        st.write("결츑치 처리:")
        for column in data.columns:
            if data[column].isnull().sum() > 0:
                method = st.selectbox(f"{column} μ—΄μ˜ 처리 방법 선택:", 
                                      ["제거", "ν‰κ· μœΌλ‘œ λŒ€μ²΄", "μ€‘μ•™κ°’μœΌλ‘œ λŒ€μ²΄", "μ΅œλΉˆκ°’μœΌλ‘œ λŒ€μ²΄"])
                if method == "제거":
                    data = data.dropna(subset=[column])
                elif method == "ν‰κ· μœΌλ‘œ λŒ€μ²΄":
                    data[column].fillna(data[column].mean(), inplace=True)
                elif method == "μ€‘μ•™κ°’μœΌλ‘œ λŒ€μ²΄":
                    data[column].fillna(data[column].median(), inplace=True)
                elif method == "μ΅œλΉˆκ°’μœΌλ‘œ λŒ€μ²΄":
                    data[column].fillna(data[column].mode()[0], inplace=True)
    
    # 데이터 νƒ€μž… λ³€ν™˜
    for column in data.columns:
        if data[column].dtype == 'object':
            try:
                data[column] = pd.to_numeric(data[column])
                st.write(f"{column} 열을 μˆ«μžν˜•μœΌλ‘œ λ³€ν™˜ν–ˆμŠ΅λ‹ˆλ‹€.")
            except ValueError:
                st.write(f"{column} 열은 λ²”μ£Όν˜•μœΌλ‘œ μœ μ§€λ©λ‹ˆλ‹€.")
    
    return data

def create_slicers(data):
    slicers = {}
    categorical_columns = data.select_dtypes(include=['object', 'category']).columns

    for col in categorical_columns:
        if data[col].nunique() <= 10:  # κ³ μœ κ°’μ΄ 10개 μ΄ν•˜μΈ κ²½μš°μ—λ§Œ μŠ¬λΌμ΄μ„œ 생성
            slicers[col] = st.multiselect(f"{col} 선택", options=sorted(data[col].unique()), default=sorted(data[col].unique()))
    
    return slicers

def apply_slicers(data, slicers):
    for col, selected_values in slicers.items():
        if selected_values:
            data = data[data[col].isin(selected_values)]
    return data


def perform_analysis(data):
    st.header("탐색적 데이터 뢄석")
    
    # μŠ¬λΌμ΄μ„œ 생성
    slicers = create_slicers(data)
    
    # μŠ¬λΌμ΄μ„œ 적용
    filtered_data = apply_slicers(data, slicers)
    
    # μš”μ•½ 톡계
    st.write("μš”μ•½ 톡계:")
    st.write(filtered_data.describe())

    # 상관관계 히트맡
    st.write("상관관계 히트맡:")
    numeric_data = filtered_data.select_dtypes(include=['float64', 'int64'])
    if not numeric_data.empty:
        fig = px.imshow(numeric_data.corr(), color_continuous_scale='RdBu_r', zmin=-1, zmax=1)
        fig.update_layout(title='상관관계 히트맡')
        st.plotly_chart(fig)
    else:
        st.write("상관관계 νžˆνŠΈλ§΅μ„ 그릴 수 μžˆλŠ” μˆ«μžν˜• 열이 μ—†μŠ΅λ‹ˆλ‹€.")

    # μ‚¬μš©μžκ°€ μ„ νƒν•œ 두 λ³€μˆ˜μ— λŒ€ν•œ 산점도 및 νšŒκ·€ 뢄석
    st.subheader("두 λ³€μˆ˜ κ°„μ˜ 관계 뢄석")
    numeric_columns = filtered_data.select_dtypes(include=['float64', 'int64']).columns
    x_var = st.selectbox("XμΆ• λ³€μˆ˜ 선택", options=numeric_columns)
    y_var = st.selectbox("YμΆ• λ³€μˆ˜ 선택", options=[col for col in numeric_columns if col != x_var])

    if x_var and y_var:
        fig = px.scatter(filtered_data, x=x_var, y=y_var, color='반' if '반' in filtered_data.columns else None)
        
        # νšŒκ·€μ„  μΆ”κ°€
        x = filtered_data[x_var]
        y = filtered_data[y_var]
        slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
        line_x = np.array([x.min(), x.max()])
        line_y = slope * line_x + intercept
        fig.add_trace(go.Scatter(x=line_x, y=line_y, mode='lines', name='νšŒκ·€μ„ '))
        
        r_squared = r_value ** 2
        fig.update_layout(
            title=f'{x_var}와 {y_var}의 관계 (R-squared: {r_squared:.4f})',
            xaxis_title=x_var,
            yaxis_title=y_var,
            annotations=[
                dict(
                    x=0.5,
                    y=1.05,
                    xref='paper',
                    yref='paper',
                    text=f'R-squared: {r_squared:.4f}',
                    showarrow=False,
                )
            ]
        )
        st.plotly_chart(fig)

        # μΆ”κ°€ 톡계 정보
        st.write(f"μƒκ΄€κ³„μˆ˜: {r_value:.4f}")
        st.write(f"p-value: {p_value:.4f}")
        st.write(f"ν‘œμ€€ 였차: {std_err:.4f}")

def main():
    st.title("μΈν„°λž™ν‹°λΈŒ EDA νˆ΄ν‚·")

    data_input_method = st.radio("데이터 μž…λ ₯ 방법 선택:", ("파일 μ—…λ‘œλ“œ", "μˆ˜λ™ μž…λ ₯"))
    
    if data_input_method == "파일 μ—…λ‘œλ“œ":
        uploaded_file = st.file_uploader("CSV, XLS, λ˜λŠ” XLSX νŒŒμΌμ„ μ„ νƒν•˜μ„Έμš”", type=["csv", "xls", "xlsx"])
        if uploaded_file is not None:
            data = load_data(uploaded_file)
        else:
            data = None
    else:
        data = manual_data_entry()
    
    if data is not None:
        st.subheader("데이터 미리보기 및 μˆ˜μ •")
        st.write("데이터λ₯Ό ν™•μΈν•˜κ³  ν•„μš”ν•œ 경우 μˆ˜μ •ν•˜μ„Έμš”:")
        edited_data = st.data_editor(data, num_rows="dynamic")
        
        if st.button("데이터 뢄석 μ‹œμž‘"):
            processed_data = preprocess_data(edited_data)
            perform_analysis(processed_data)

if __name__ == "__main__":
    main()