Spaces:
Runtime error
Runtime error
Update app.py
Browse files4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851 unmodified line1871881891901911921931941951961971984 unmodified linesimport plotly.figure_factory as fffrom scipy import statsdef analyze_dataframe(df, max_unique_for_categorical=20):"""Analyzes each column in a DataFrame and creates appropriate visualizations and statistics.Parameters:-----------df : pandas.DataFrameThe input DataFrame to analyzemax_unique_for_categorical : int, default=20Maximum number of unique values for a column to be considered categoricalReturns:--------None (displays results directly in Streamlit)"""# Function to check if a column is numericdef 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 categoricaldef is_categorical(col):if pd.api.types.is_numeric_dtype(df[col]):return df[col].nunique() <= max_unique_for_categoricalreturn True# Function to analyze numeric columnsdef analyze_numeric_column(col_name):st.write(f"### Analysis of {col_name}")# Calculate statisticsstats_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 columnscol1, 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 visualizationscol1, col2 = st.columns(2)with col1:# Box plotfig_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 KDEhist_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 informationmissing_count = df[col_name].isnull().sum()missing_percent = (missing_count / len(df)) * 100st.write(f"**Missing Values**: {missing_count:,} ({missing_percent:.2f}%)")st.markdown("---")# Function to analyze categorical columnsdef analyze_categorical_column(col_name):st.write(f"### Analysis of {col_name}")# Calculate value counts and percentagesvalue_counts = df[col_name].value_counts()value_percentages = df[col_name].value_counts(normalize=True) * 100# Display basic statisticsst.write(f"**Number of unique values**: {df[col_name].nunique()}")# Create visualizationscol1, col2 = st.columns(2)with col1:# Bar chart of countsfig_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)with col2:# Pie chart of percentagesfig_percent = px.pie(names=value_percentages.index,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 tablefreq_df = pd.DataFrame({'Count': value_counts,'Percentage (%)': value_percentages}).round(2)st.write("**Frequency Table:**")st.dataframe(freq_df)# Add missing values informationmissing_count = df[col_name].isnull().sum()missing_percent = (missing_count / len(df)) * 100st.write(f"**Missing Values**: {missing_count:,} ({missing_percent:.2f}%)")st.markdown("---")# Main analysis loopst.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 columnfor 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("Auto Data Visualizer - Analyse CSV Data")# File uploader for CSVuploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])1 unmodified lineif uploaded_file is not None:# Read the uploaded CSV filedf = pd.read_csv(uploaded_file)# Display the uploaded datast.write("### Uploaded Data")st.dataframe(df)# Analyze the uploaded dataanalyze_dataframe(df)else:st.write("Please upload a CSV file to analyze.")4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571 unmodified line1591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392404 unmodified linesimport plotly.figure_factory as fffrom 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 valuesthan max_unique_for_categorical."""return pd.api.types.is_numeric_dtype(df[col]) and df[col].nunique() > max_unique_for_categoricaldef 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 numericbut 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_categoricalreturn 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 statisticsstats_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 columnscol1, 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 Modest.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 visualizationscol1, col2 = st.columns(2)with col1:# Box plotfig_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 KDEhist_data = [df[col_name].dropna()]# Calculate bin_size robustly to avoid division by zero or too many bins for constant datacol_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 informationmissing_count = df[col_name].isnull().sum()missing_percent = (missing_count / len(df)) * 100st.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 percentagesvalue_counts = df[col_name].value_counts()value_percentages = df[col_name].value_counts(normalize=True) * 100# Display basic statisticsst.write(f"**Number of unique values**: {df[col_name].nunique()}")# Create visualizationscol1, col2 = st.columns(2)with col1:# Bar chart of countsfig_count = px.bar(x=value_counts.index.astype(str), # Ensure x-axis is string for consistent plottingy=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 percentagesfig_percent = px.pie(names=value_percentages.index.astype(str), # Ensure names are stringsvalues=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 tablefreq_df = pd.DataFrame({'Count': value_counts,'Percentage (%)': value_percentages}).round(2)st.write("**Frequency Table:**")st.dataframe(freq_df)# Add missing values informationmissing_count = df[col_name].isnull().sum()missing_percent = (missing_count / len(df)) * 100st.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 CSVuploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])1 unmodified lineif uploaded_file is not None:# Read the uploaded CSV filedf = pd.read_csv(uploaded_file)# Display the uploaded datast.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 presentif 'column_configs' not in st.session_state:st.session_state.column_configs = {}for col in df.columns:# Determine initial auto-detected typeinitial_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 configurationfor col_name in df.columns:with st.expander(f"Configure Column: **{col_name}** (Current Type: {df[col_name].dtype})"):# Checkbox to show/hide analysisst.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 typest.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 analysisif st.button("Run Analysis"):st.write("### Data Analysis Results")for column in df.columns:try:# Check if analysis for this column should be shownif 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 selectioneffective_type_is_numeric = Falseeffective_type_is_categorical = Falseif 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 = Trueelif selected_type == "Categorical":effective_type_is_categorical = True# Perform analysis based on effective typeif len(df[column]) > 0: # Ensure column is not emptyif 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.")
app.py+220-178