Spaces:
Runtime error
Runtime error
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import streamlit as stimport pandas as pdimport numpy as npimport plotly.express as pximport plotly.figure_factory as fffrom scipy import stats
def analyze_dataframe(df, max_unique_for_categorical=20): """ Analyzes each column in a DataFrame and creates appropriate visualizations and statistics. Parameters: ----------- df : pandas.DataFrame The input DataFrame to analyze max_unique_for_categorical : int, default=20 Maximum number of unique values for a column to be considered categorical Returns: -------- None (displays results directly in Streamlit) """ # Function to check if a column is numeric def is_numeric(col): return pd.api.types.is_numeric_dtype(df[col]) and df[col].nunique() > max_unique_for_categorical # Function to check if a column should be treated as categorical def is_categorical(col): if pd.api.types.is_numeric_dtype(df[col]): return df[col].nunique() <= max_unique_for_categorical return True # Function to analyze numeric columns def analyze_numeric_column(col_name): 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}") st.write(f"- Mode: {stats_dict['Mode']:,.2f}") 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()] fig_hist = ff.create_distplot( hist_data, [col_name], bin_size=(df[col_name].max() - df[col_name].min()) / 30, 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("---") # Function to analyze categorical columns def analyze_categorical_column(col_name): 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, 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: # Bar chart of percentages fig_percent = px.bar( x=value_percentages.index, y=value_percentages.values, title=f"Percentage Distribution of {col_name}", labels={'x': col_name, 'y': 'Percentage (%)'} ) 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 analysis loop st.title("DataFrame Analysis") st.write(f"Total number of rows: {len(df):,}") st.write(f"Total number of columns: {len(df.columns):,}") st.markdown("---") # Process each column for column in df.columns: print(column) try: if len(df[column])>0: if is_numeric(column): analyze_numeric_column(column) elif is_categorical(column): analyze_categorical_column(column) else: st.write(f"Skipping column {column} (unsupported data type)") except: st.write(f"Skipping column {column} (Something is wrong!)")
# Streamlit app titlest.title("CSV Data Analyzer")
# File uploader for CSVuploaded_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") st.dataframe(df) # Analyze the uploaded data analyze_dataframe(df)else: st.write("Please upload a CSV file to analyze.")app.pyAdded+186