Spaces:
Runtime error

JoyB's picture
Update app.py
521ad21 verified
Raw History Blame Contribute Delete
9.73 kB
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.figure_factory as ff
from scipy import stats
# --- Helper Functions for Column Type Detection ---
def is_numeric_auto(df, col, max_unique_for_categorical=20):
"""
Automatically determines if a column should be treated as numeric (continuous).
A column is considered numeric if it's a numeric dtype and has more unique values
than max_unique_for_categorical.
"""
return pd.api.types.is_numeric_dtype(df[col]) and df[col].nunique() > max_unique_for_categorical
def is_categorical_auto(df, col, max_unique_for_categorical=20):
"""
Automatically determines if a column should be treated as categorical.
A column is considered categorical if it's not purely numeric, or if it's numeric
but has unique values less than or equal to max_unique_for_categorical.
"""
if pd.api.types.is_numeric_dtype(df[col]):
return df[col].nunique() <= max_unique_for_categorical
return True # Non-numeric types are always treated as categorical
# --- Analysis Functions ---
def analyze_numeric_column(df, col_name):
"""
Analyzes a numeric (continuous) column and displays statistics and visualizations.
"""
st.write(f"### Analysis of {col_name}")
# Calculate statistics
stats_dict = {
"Count": df[col_name].count(),
"Mean": df[col_name].mean(),
"Median": df[col_name].median(),
"Mode": df[col_name].mode().iloc[0] if not df[col_name].mode().empty else None,
"Std Dev": df[col_name].std(),
"Variance": df[col_name].var(),
"Skewness": df[col_name].skew(),
"Kurtosis": df[col_name].kurtosis(),
"Minimum": df[col_name].min(),
"Maximum": df[col_name].max(),
"Q1 (25%)": df[col_name].quantile(0.25),
"Q3 (75%)": df[col_name].quantile(0.75),
"IQR": df[col_name].quantile(0.75) - df[col_name].quantile(0.25)
}
# Display statistics in columns
col1, col2 = st.columns(2)
with col1:
st.write("**Measures of Central Tendency**")
st.write(f"- Count: {stats_dict['Count']:,.0f}")
st.write(f"- Mean: {stats_dict['Mean']:,.2f}")
st.write(f"- Median: {stats_dict['Median']:,.2f}")
# Handle potential None for Mode
st.write(f"- Mode: {stats_dict['Mode']:,.2f}" if stats_dict['Mode'] is not None else "- Mode: N/A")
with col2:
st.write("**Measures of Dispersion**")
st.write(f"- Standard Deviation: {stats_dict['Std Dev']:,.2f}")
st.write(f"- Variance: {stats_dict['Variance']:,.2f}")
st.write(f"- IQR: {stats_dict['IQR']:,.2f}")
st.write(f"- Range: {stats_dict['Maximum'] - stats_dict['Minimum']:,.2f}")
# Create visualizations
col1, col2 = st.columns(2)
with col1:
# Box plot
fig_box = px.box(df, y=col_name, title=f"Box Plot of {col_name}")
st.plotly_chart(fig_box, use_container_width=True)
with col2:
# Histogram with KDE
hist_data = [df[col_name].dropna()]
# Calculate bin_size robustly to avoid division by zero or too many bins for constant data
col_range = df[col_name].max() - df[col_name].min()
bin_size = col_range / 30 if col_range > 0 else 1 # Default to 1 if range is 0 (constant data)
fig_hist = ff.create_distplot(
hist_data,
[col_name],
bin_size=bin_size,
show_rug=False
)
fig_hist.update_layout(title=f"Distribution of {col_name}")
st.plotly_chart(fig_hist, use_container_width=True)
# Add missing values information
missing_count = df[col_name].isnull().sum()
missing_percent = (missing_count / len(df)) * 100
st.write(f"**Missing Values**: {missing_count:,} ({missing_percent:.2f}%)")
st.markdown("---")
def analyze_categorical_column(df, col_name):
"""
Analyzes a categorical column and displays statistics and visualizations.
"""
st.write(f"### Analysis of {col_name}")
# Calculate value counts and percentages
value_counts = df[col_name].value_counts()
value_percentages = df[col_name].value_counts(normalize=True) * 100
# Display basic statistics
st.write(f"**Number of unique values**: {df[col_name].nunique()}")
# Create visualizations
col1, col2 = st.columns(2)
with col1:
# Bar chart of counts
fig_count = px.bar(
x=value_counts.index.astype(str), # Ensure x-axis is string for consistent plotting
y=value_counts.values,
title=f"Count of {col_name}",
labels={'x': col_name, 'y': 'Count'}
)
st.plotly_chart(fig_count, use_container_width=True)
with col2:
# Pie chart of percentages
fig_percent = px.pie(
names=value_percentages.index.astype(str), # Ensure names are strings
values=value_percentages.values,
title=f"Percentage Distribution",
hole=0.3 # Optional: to make it a donut chart
)
st.plotly_chart(fig_percent, use_container_width=True)
# Display frequency table
freq_df = pd.DataFrame({
'Count': value_counts,
'Percentage (%)': value_percentages
}).round(2)
st.write("**Frequency Table:**")
st.dataframe(freq_df)
# Add missing values information
missing_count = df[col_name].isnull().sum()
missing_percent = (missing_count / len(df)) * 100
st.write(f"**Missing Values**: {missing_count:,} ({missing_percent:.2f}%)")
st.markdown("---")
# --- Main Streamlit Application ---
st.title("Auto Data Visualizer - Analyze CSV Data")
st.markdown("Upload your CSV file, configure column types and visibility, then run the analysis.")
# File uploader for CSV
uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])
if uploaded_file is not None:
# Read the uploaded CSV file
df = pd.read_csv(uploaded_file)
# Display the uploaded data
st.write("### Uploaded Data Preview")
st.dataframe(df.head())
st.write(f"Total number of rows: {len(df):,}")
st.write(f"Total number of columns: {len(df.columns):,}")
st.markdown("---")
st.write("### Column Configuration")
st.markdown("Adjust the data type for each column and choose whether to show its analysis.")
# Initialize session state for column configurations if not already present
if 'column_configs' not in st.session_state:
st.session_state.column_configs = {}
for col in df.columns:
# Determine initial auto-detected type
initial_type = "Continuous" if is_numeric_auto(df, col) else "Categorical"
st.session_state.column_configs[col] = {
'show_analysis': True,
'selected_type': "Auto" # Default to Auto
}
# UI for column configuration
for col_name in df.columns:
with st.expander(f"Configure Column: **{col_name}** (Current Type: {df[col_name].dtype})"):
# Checkbox to show/hide analysis
st.session_state.column_configs[col_name]['show_analysis'] = st.checkbox(
f"Show analysis for {col_name}",
value=st.session_state.column_configs[col_name]['show_analysis'],
key=f"show_analysis_{col_name}"
)
# Selectbox for data type
st.session_state.column_configs[col_name]['selected_type'] = st.selectbox(
f"Treat '{col_name}' as:",
["Auto", "Continuous", "Categorical"],
index=["Auto", "Continuous", "Categorical"].index(st.session_state.column_configs[col_name]['selected_type']),
key=f"type_selection_{col_name}"
)
st.markdown("---")
# Button to run analysis
if st.button("Run Analysis"):
st.write("### Data Analysis Results")
for column in df.columns:
try:
# Check if analysis for this column should be shown
if st.session_state.column_configs[column]['show_analysis']:
selected_type = st.session_state.column_configs[column]['selected_type']
# Determine the effective type based on user selection
effective_type_is_numeric = False
effective_type_is_categorical = False
if selected_type == "Auto":
effective_type_is_numeric = is_numeric_auto(df, column)
effective_type_is_categorical = is_categorical_auto(df, column)
elif selected_type == "Continuous":
effective_type_is_numeric = True
elif selected_type == "Categorical":
effective_type_is_categorical = True
# Perform analysis based on effective type
if len(df[column]) > 0: # Ensure column is not empty
if effective_type_is_numeric:
analyze_numeric_column(df, column)
elif effective_type_is_categorical:
analyze_categorical_column(df, column)
else:
st.write(f"Skipping column {column}: Could not determine type or column is empty.")
else:
st.write(f"Skipping column {column}: No data to analyze.")
except Exception as e:
st.error(f"An error occurred while analyzing column '{column}': {e}")
st.write(f"Skipping column {column} due to an error.")
else:
st.info("Please upload a CSV file to begin the analysis.")