enacimie commited on
Commit
094716a
Β·
verified Β·
1 Parent(s): 1727fe9

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +194 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,196 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.express as px
5
+ from scipy import stats
6
+ import io
7
+
8
+ # Metadata
9
+ AUTHOR = "Eduardo Nacimiento GarcΓ­a"
10
+ EMAIL = "enacimie@ull.edu.es"
11
+ LICENSE = "Apache 2.0"
12
+
13
+ # Page config
14
+ st.set_page_config(
15
+ page_title="SimpleStats",
16
+ page_icon="πŸ“Š",
17
+ layout="wide",
18
+ initial_sidebar_state="expanded",
19
+ )
20
+
21
+ # Title and credits
22
+ st.title("πŸ“Š SimpleStats")
23
+ st.markdown(f"**Author:** {AUTHOR} | **Email:** {EMAIL} | **License:** {LICENSE}")
24
+
25
+ st.write("""
26
+ Upload a CSV file or try the built-in demo dataset to perform statistical analysis: summary, charts, hypothesis tests, and more.
27
+ """)
28
+
29
+ # Generate demo dataset
30
+ @st.cache_data
31
+ def create_demo_data():
32
+ np.random.seed(42)
33
+ n = 200
34
+ data = {
35
+ "Age": np.random.normal(35, 12, n).astype(int),
36
+ "Income": np.random.normal(45000, 15000, n),
37
+ "Satisfaction": np.random.randint(1, 11, n), # scale 1-10
38
+ "Group": np.random.choice(["A", "B", "C"], n),
39
+ "Gender": np.random.choice(["M", "F"], n, p=[0.6, 0.4]),
40
+ "Purchase": np.random.choice([0, 1], n, p=[0.7, 0.3])
41
+ }
42
+ df = pd.DataFrame(data)
43
+ # Introduce some nulls for demo
44
+ df.loc[np.random.choice(df.index, 10), "Income"] = np.nan
45
+ df.loc[np.random.choice(df.index, 5), "Age"] = np.nan
46
+ return df
47
+
48
+ demo_df = create_demo_data()
49
+
50
+ # Button to load demo data
51
+ if st.button("πŸ§ͺ Load Demo Dataset"):
52
+ st.session_state['uploaded_file'] = demo_df.to_csv(index=False).encode('utf-8')
53
+ st.session_state['file_name'] = "demo_data.csv"
54
+ st.success("βœ… Demo dataset loaded. Explore the features!")
55
+
56
+ # File uploader
57
+ uploaded_file = st.file_uploader("πŸ“‚ Upload your CSV file", type=["csv"])
58
+
59
+ # Determine data source
60
+ if 'uploaded_file' in st.session_state and not uploaded_file:
61
+ # Use demo if no file uploaded
62
+ csv_bytes = st.session_state['uploaded_file']
63
+ file_name = st.session_state['file_name']
64
+ df = pd.read_csv(io.BytesIO(csv_bytes))
65
+ st.info(f"Using demo dataset: `{file_name}`")
66
+ elif uploaded_file is not None:
67
+ df = pd.read_csv(uploaded_file)
68
+ st.success("βœ… File uploaded successfully.")
69
+ else:
70
+ df = None
71
+
72
+ if df is not None:
73
+ # Show data preview
74
+ with st.expander("πŸ” Data Preview (first 10 rows)"):
75
+ st.dataframe(df.head(10))
76
+
77
+ # Basic info
78
+ st.subheader("πŸ“Œ Dataset Information")
79
+ col1, col2, col3 = st.columns(3)
80
+ col1.metric("Rows", df.shape[0])
81
+ col2.metric("Columns", df.shape[1])
82
+ col3.metric("Missing Values", df.isnull().sum().sum())
83
+
84
+ # Identify numeric and categorical columns
85
+ numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
86
+ categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
87
+
88
+ if len(numeric_cols) == 0:
89
+ st.warning("⚠️ No numeric columns found for statistical analysis.")
90
+ else:
91
+ st.subheader("πŸ“ˆ Descriptive Statistics")
92
+ st.dataframe(df[numeric_cols].describe())
93
+
94
+ # Histogram
95
+ st.subheader("πŸ“Š Histogram")
96
+ selected_col = st.selectbox("Select a numeric column for histogram:", numeric_cols)
97
+ fig_hist = px.histogram(df, x=selected_col, nbins=30, title=f"Histogram of {selected_col}", marginal="box")
98
+ st.plotly_chart(fig_hist, use_container_width=True)
99
+
100
+ # Scatter plot
101
+ if len(numeric_cols) >= 2:
102
+ st.subheader("πŸ“‰ Scatter Plot")
103
+ col_x = st.selectbox("Select X-axis column:", numeric_cols, key="x")
104
+ col_y = st.selectbox("Select Y-axis column:", numeric_cols, key="y")
105
+ color_by = st.selectbox("Color by (optional):", [None] + categorical_cols, key="color")
106
+ if col_x != col_y:
107
+ fig_scatter = px.scatter(df, x=col_x, y=col_y, color=color_by, title=f"{col_x} vs {col_y}")
108
+ st.plotly_chart(fig_scatter, use_container_width=True)
109
+ else:
110
+ st.warning("⚠️ Please select two different columns.")
111
+
112
+ # Correlation matrix
113
+ st.subheader("πŸ”— Correlation Matrix")
114
+ corr = df[numeric_cols].corr()
115
+ fig_corr = px.imshow(corr, text_auto=".2f", aspect="auto", title="Correlation Matrix", color_continuous_scale='RdBu_r')
116
+ st.plotly_chart(fig_corr, use_container_width=True)
117
+
118
+ # Missing values per column
119
+ st.subheader("πŸ•³οΈ Missing Values by Column")
120
+ nulls = df.isnull().sum()
121
+ if nulls.sum() > 0:
122
+ fig_nulls = px.bar(nulls, title="Missing Values by Column", labels={'value': 'Count', 'index': 'Column'}, color=nulls)
123
+ st.plotly_chart(fig_nulls, use_container_width=True)
124
+ else:
125
+ st.success("βœ… No missing values in the dataset.")
126
+
127
+ # === STATISTICAL TESTS ===
128
+ st.header("πŸ§ͺ Statistical Tests")
129
+
130
+ # Independent T-Test (for 2 groups)
131
+ if len(numeric_cols) > 0 and len(categorical_cols) > 0:
132
+ st.subheader("Independent T-Test (2 groups)")
133
+ t_num_col = st.selectbox("Numeric variable:", numeric_cols, key="t_num")
134
+ t_cat_col = st.selectbox("Categorical variable (must have exactly 2 groups):",
135
+ [col for col in categorical_cols if df[col].nunique() == 2],
136
+ key="t_cat")
137
+ if t_cat_col:
138
+ groups = df[t_cat_col].unique()
139
+ if len(groups) == 2:
140
+ group1 = df[df[t_cat_col] == groups[0]][t_num_col].dropna()
141
+ group2 = df[df[t_cat_col] == groups[1]][t_num_col].dropna()
142
+ t_stat, p_val = stats.ttest_ind(group1, group2, equal_var=False)
143
+ st.write(f"**T-Test result between `{groups[0]}` and `{groups[1]}` for `{t_num_col}`:**")
144
+ st.write(f"- **T-statistic:** {t_stat:.4f}")
145
+ st.write(f"- **P-value:** {p_val:.4f}")
146
+ if p_val < 0.05:
147
+ st.success("🟒 Statistically significant difference (p < 0.05)")
148
+ else:
149
+ st.error("πŸ”΄ No statistically significant difference (p >= 0.05)")
150
+ else:
151
+ st.warning("Selected categorical variable does not have exactly 2 groups.")
152
+
153
+ # ANOVA (for 3+ groups)
154
+ if len(numeric_cols) > 0 and len(categorical_cols) > 0:
155
+ st.subheader("ANOVA (3 or more groups)")
156
+ anova_num_col = st.selectbox("Numeric variable:", numeric_cols, key="anova_num")
157
+ anova_cat_col = st.selectbox("Categorical variable (3 or more groups):",
158
+ [col for col in categorical_cols if df[col].nunique() >= 3],
159
+ key="anova_cat")
160
+ if anova_cat_col:
161
+ groups = [df[df[anova_cat_col] == group][anova_num_col].dropna() for group in df[anova_cat_col].unique()]
162
+ if len(groups) >= 3:
163
+ f_stat, p_val = stats.f_oneway(*groups)
164
+ st.write(f"**ANOVA result for `{anova_num_col}` grouped by `{anova_cat_col}`:**")
165
+ st.write(f"- **F-statistic:** {f_stat:.4f}")
166
+ st.write(f"- **P-value:** {p_val:.4f}")
167
+ if p_val < 0.05:
168
+ st.success("🟒 At least one group is significantly different (p < 0.05)")
169
+ else:
170
+ st.error("πŸ”΄ No significant differences between groups (p >= 0.05)")
171
+
172
+ # Chi-Square Test (between two categorical variables)
173
+ if len(categorical_cols) >= 2:
174
+ st.subheader("Chi-Square Test (Association between categorical variables)")
175
+ chi_col1 = st.selectbox("First categorical variable:", categorical_cols, key="chi1")
176
+ chi_col2 = st.selectbox("Second categorical variable:", [col for col in categorical_cols if col != chi_col1], key="chi2")
177
+ if chi_col1 and chi_col2:
178
+ contingency_table = pd.crosstab(df[chi_col1], df[chi_col2])
179
+ chi2, p_val, dof, expected = stats.chi2_contingency(contingency_table)
180
+ st.write(f"**Chi-Square result between `{chi_col1}` and `{chi_col2}`:**")
181
+ st.write(f"- **ChiΒ² statistic:** {chi2:.4f}")
182
+ st.write(f"- **P-value:** {p_val:.4f}")
183
+ st.write(f"- **Degrees of freedom:** {dof}")
184
+ if p_val < 0.05:
185
+ st.success("🟒 Variables are associated (p < 0.05)")
186
+ else:
187
+ st.error("πŸ”΄ No evidence of association between variables (p >= 0.05)")
188
+ with st.expander("πŸ“‹ Contingency Table"):
189
+ st.dataframe(contingency_table)
190
+
191
+ else:
192
+ st.info("πŸ‘† Upload a CSV file or click 'Load Demo Dataset' to get started.")
193
 
194
+ # Footer
195
+ st.markdown("---")
196
+ st.caption(f"Β© {AUTHOR} | License {LICENSE} | Contact: {EMAIL}")