Spaces:
Runtime error

JoyB commited on
Commit
5608985
·
verified ·
1 Parent(s): 2b7916a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -0
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.express as px
5
+ import plotly.figure_factory as ff
6
+ from scipy import stats
7
+
8
+ def analyze_dataframe(df, max_unique_for_categorical=20):
9
+ """
10
+ Analyzes each column in a DataFrame and creates appropriate visualizations and statistics.
11
+
12
+ Parameters:
13
+ -----------
14
+ df : pandas.DataFrame
15
+ The input DataFrame to analyze
16
+ max_unique_for_categorical : int, default=20
17
+ Maximum number of unique values for a column to be considered categorical
18
+
19
+ Returns:
20
+ --------
21
+ None (displays results directly in Streamlit)
22
+ """
23
+
24
+ # Function to check if a column is numeric
25
+ def is_numeric(col):
26
+ return pd.api.types.is_numeric_dtype(df[col]) and df[col].nunique() > max_unique_for_categorical
27
+
28
+ # Function to check if a column should be treated as categorical
29
+ def is_categorical(col):
30
+ if pd.api.types.is_numeric_dtype(df[col]):
31
+ return df[col].nunique() <= max_unique_for_categorical
32
+ return True
33
+
34
+ # Function to analyze numeric columns
35
+ def analyze_numeric_column(col_name):
36
+ st.write(f"### Analysis of {col_name}")
37
+
38
+ # Calculate statistics
39
+ stats_dict = {
40
+ "Count": df[col_name].count(),
41
+ "Mean": df[col_name].mean(),
42
+ "Median": df[col_name].median(),
43
+ "Mode": df[col_name].mode().iloc[0] if not df[col_name].mode().empty else None,
44
+ "Std Dev": df[col_name].std(),
45
+ "Variance": df[col_name].var(),
46
+ "Skewness": df[col_name].skew(),
47
+ "Kurtosis": df[col_name].kurtosis(),
48
+ "Minimum": df[col_name].min(),
49
+ "Maximum": df[col_name].max(),
50
+ "Q1 (25%)": df[col_name].quantile(0.25),
51
+ "Q3 (75%)": df[col_name].quantile(0.75),
52
+ "IQR": df[col_name].quantile(0.75) - df[col_name].quantile(0.25)
53
+ }
54
+
55
+ # Display statistics in columns
56
+ col1, col2 = st.columns(2)
57
+
58
+ with col1:
59
+ st.write("**Measures of Central Tendency**")
60
+ st.write(f"- Count: {stats_dict['Count']:,.0f}")
61
+ st.write(f"- Mean: {stats_dict['Mean']:,.2f}")
62
+ st.write(f"- Median: {stats_dict['Median']:,.2f}")
63
+ st.write(f"- Mode: {stats_dict['Mode']:,.2f}")
64
+
65
+ with col2:
66
+ st.write("**Measures of Dispersion**")
67
+ st.write(f"- Standard Deviation: {stats_dict['Std Dev']:,.2f}")
68
+ st.write(f"- Variance: {stats_dict['Variance']:,.2f}")
69
+ st.write(f"- IQR: {stats_dict['IQR']:,.2f}")
70
+ st.write(f"- Range: {stats_dict['Maximum'] - stats_dict['Minimum']:,.2f}")
71
+
72
+ # Create visualizations
73
+ col1, col2 = st.columns(2)
74
+
75
+ with col1:
76
+ # Box plot
77
+ fig_box = px.box(df, y=col_name, title=f"Box Plot of {col_name}")
78
+ st.plotly_chart(fig_box, use_container_width=True)
79
+
80
+ with col2:
81
+ # Histogram with KDE
82
+ hist_data = [df[col_name].dropna()]
83
+ fig_hist = ff.create_distplot(
84
+ hist_data,
85
+ [col_name],
86
+ bin_size=(df[col_name].max() - df[col_name].min()) / 30,
87
+ show_rug=False
88
+ )
89
+ fig_hist.update_layout(title=f"Distribution of {col_name}")
90
+ st.plotly_chart(fig_hist, use_container_width=True)
91
+
92
+ # Add missing values information
93
+ missing_count = df[col_name].isnull().sum()
94
+ missing_percent = (missing_count / len(df)) * 100
95
+ st.write(f"**Missing Values**: {missing_count:,} ({missing_percent:.2f}%)")
96
+
97
+ st.markdown("---")
98
+
99
+ # Function to analyze categorical columns
100
+ def analyze_categorical_column(col_name):
101
+ st.write(f"### Analysis of {col_name}")
102
+
103
+ # Calculate value counts and percentages
104
+ value_counts = df[col_name].value_counts()
105
+ value_percentages = df[col_name].value_counts(normalize=True) * 100
106
+
107
+ # Display basic statistics
108
+ st.write(f"**Number of unique values**: {df[col_name].nunique()}")
109
+
110
+ # Create visualizations
111
+ col1, col2 = st.columns(2)
112
+
113
+ with col1:
114
+ # Bar chart of counts
115
+ fig_count = px.bar(
116
+ x=value_counts.index,
117
+ y=value_counts.values,
118
+ title=f"Count of {col_name}",
119
+ labels={'x': col_name, 'y': 'Count'}
120
+ )
121
+ st.plotly_chart(fig_count, use_container_width=True)
122
+
123
+ with col2:
124
+ # Bar chart of percentages
125
+ fig_percent = px.bar(
126
+ x=value_percentages.index,
127
+ y=value_percentages.values,
128
+ title=f"Percentage Distribution of {col_name}",
129
+ labels={'x': col_name, 'y': 'Percentage (%)'}
130
+ )
131
+ st.plotly_chart(fig_percent, use_container_width=True)
132
+
133
+ # Display frequency table
134
+ freq_df = pd.DataFrame({
135
+ 'Count': value_counts,
136
+ 'Percentage (%)': value_percentages
137
+ }).round(2)
138
+
139
+ st.write("**Frequency Table:**")
140
+ st.dataframe(freq_df)
141
+
142
+ # Add missing values information
143
+ missing_count = df[col_name].isnull().sum()
144
+ missing_percent = (missing_count / len(df)) * 100
145
+ st.write(f"**Missing Values**: {missing_count:,} ({missing_percent:.2f}%)")
146
+
147
+ st.markdown("---")
148
+
149
+ # Main analysis loop
150
+ st.title("DataFrame Analysis")
151
+ st.write(f"Total number of rows: {len(df):,}")
152
+ st.write(f"Total number of columns: {len(df.columns):,}")
153
+ st.markdown("---")
154
+
155
+ # Process each column
156
+ for column in df.columns:
157
+ print(column)
158
+ try:
159
+ if len(df[column])>0:
160
+ if is_numeric(column):
161
+ analyze_numeric_column(column)
162
+ elif is_categorical(column):
163
+ analyze_categorical_column(column)
164
+ else:
165
+ st.write(f"Skipping column {column} (unsupported data type)")
166
+ except:
167
+ st.write(f"Skipping column {column} (Something is wrong!)")
168
+
169
+ # Streamlit app title
170
+ st.title("CSV Data Analyzer")
171
+
172
+ # File uploader for CSV
173
+ uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])
174
+
175
+ if uploaded_file is not None:
176
+ # Read the uploaded CSV file
177
+ df = pd.read_csv(uploaded_file)
178
+
179
+ # Display the uploaded data
180
+ st.write("### Uploaded Data")
181
+ st.dataframe(df)
182
+
183
+ # Analyze the uploaded data
184
+ analyze_dataframe(df)
185
+ else:
186
+ st.write("Please upload a CSV file to analyze.")