Image_to_Table / app.py
Phaneendrabayi's picture
Update app.py
7ddb4af verified
Raw History Blame Contribute Delete
8.64 kB
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
from scipy import stats
# Title of the app
st.title("Comprehensive EDA Tool")
# Sidebar for Navigation
st.sidebar.title("Navigation")
section = st.sidebar.radio(
"Go to",
[
"Upload Data",
"Data Overview",
"Missing Values",
"Data Cleaning",
"Feature Engineering",
"Univariate Analysis",
"Bivariate Analysis",
"Statistical Tests",
"Export Data",
],
)
# File upload section
uploaded_file = st.sidebar.file_uploader("Upload your file (JSON, CSV, XLSX)", type=["json", "csv", "xlsx"])
if uploaded_file:
# Load data based on file type
if uploaded_file.name.endswith(".csv"):
df = pd.read_csv(uploaded_file)
elif uploaded_file.name.endswith(".json"):
df = pd.read_json(uploaded_file)
elif uploaded_file.name.endswith(".xlsx"):
df = pd.read_excel(uploaded_file)
# Identify numerical and categorical columns
numerical_cols = df.select_dtypes(include=[np.number]).columns.tolist()
categorical_cols = df.select_dtypes(include=["object", "category"]).columns.tolist()
# Section: Upload Data
if section == "Upload Data":
st.write("### Uploaded Data Preview")
st.dataframe(df.head())
st.write("### Column Types")
st.write(f"Numerical Columns: {numerical_cols}")
st.write(f"Categorical Columns: {categorical_cols}")
# Section: Data Overview
elif section == "Data Overview":
st.write("### Data Overview")
st.write(f"Number of Rows: {df.shape[0]}")
st.write(f"Number of Columns: {df.shape[1]}")
st.write(f"Duplicate Rows: {df.duplicated().sum()}")
st.write("### Statistical Summary")
st.write(df.describe(include="all"))
# Section: Missing Values
elif section == "Missing Values":
st.write("### Missing Values")
missing_values = df.isnull().sum()
st.write(missing_values[missing_values > 0])
if st.checkbox("Replace missing values with Mean/Median for Numerical Columns"):
for col in numerical_cols:
if df[col].isnull().sum() > 0:
replacement = st.selectbox(
f"Replace NaN in {col} with:", ["Mean", "Median"]
)
if replacement == "Mean":
df[col].fillna(df[col].mean(), inplace=True)
elif replacement == "Median":
df[col].fillna(df[col].median(), inplace=True)
if st.checkbox("Replace missing values with Mode for Categorical Columns"):
for col in categorical_cols:
if df[col].isnull().sum() > 0:
df[col].fillna(df[col].mode()[0], inplace=True)
st.write("### Data After Handling Missing Values")
st.dataframe(df.head())
# Section: Data Cleaning
elif section == "Data Cleaning":
st.write("### Data Cleaning Options")
if st.checkbox("Remove Duplicates"):
df.drop_duplicates(inplace=True)
st.write("Duplicates removed!")
if st.checkbox("Scale Numerical Columns"):
# Manual scaling without sklearn
for col in numerical_cols:
mean = df[col].mean()
std = df[col].std()
df[col] = (df[col] - mean) / std
st.write("Numerical columns scaled!")
if st.checkbox("Encode Categorical Columns"):
# Manual label encoding without sklearn
for col in categorical_cols:
unique_values = df[col].unique()
mapping = {value: idx for idx, value in enumerate(unique_values)}
df[col] = df[col].map(mapping)
st.write("Categorical columns encoded!")
# Section: Feature Engineering
elif section == "Feature Engineering":
st.write("### Feature Engineering")
if st.checkbox("Extract Date/Time Features"):
date_col = st.selectbox("Select a Date/Time column", df.columns)
if date_col:
df[date_col] = pd.to_datetime(df[date_col])
df["Year"] = df[date_col].dt.year
df["Month"] = df[date_col].dt.month
df["Day"] = df[date_col].dt.day
df["Weekday"] = df[date_col].dt.weekday
st.write("Date/Time features extracted!")
st.dataframe(df.head())
# Section: Univariate Analysis
elif section == "Univariate Analysis":
st.write("### Univariate Analysis")
analysis_type = st.selectbox("Select Analysis Type", ["Numerical", "Categorical"])
if analysis_type == "Numerical":
for col in numerical_cols:
st.write(f"#### Distribution of {col}")
fig_hist = px.histogram(df, x=col, title=f"Histogram of {col}", marginal="box")
st.plotly_chart(fig_hist)
st.write(f"#### Violin Plot of {col}")
fig_violin = px.violin(df, y=col, title=f"Violin Plot of {col}")
st.plotly_chart(fig_violin)
elif analysis_type == "Categorical":
for col in categorical_cols:
st.write(f"#### Value Counts of {col}")
fig_bar = px.bar(df[col].value_counts(), title=f"Bar Chart of {col}")
st.plotly_chart(fig_bar)
st.write(f"#### Pie Chart of {col}")
fig_pie = px.pie(df, names=col, title=f"Pie Chart of {col}")
st.plotly_chart(fig_pie)
# Section: Bivariate Analysis
elif section == "Bivariate Analysis":
st.write("### Bivariate Analysis")
x_col = st.selectbox("Select X-axis column", numerical_cols)
y_col = st.selectbox("Select Y-axis column", numerical_cols)
if x_col and y_col:
st.write(f"#### Scatter Plot between {x_col} and {y_col}")
fig_scatter = px.scatter(df, x=x_col, y=y_col, title=f"{x_col} vs {y_col}")
st.plotly_chart(fig_scatter)
st.write("#### Pair Plot (Numerical Columns)")
if st.checkbox("Show Pair Plot"):
pair_plot = sns.pairplot(df[numerical_cols])
st.pyplot(pair_plot.fig)
st.write("#### Correlation Heatmap")
corr_matrix = df[numerical_cols].corr()
fig_heatmap = px.imshow(corr_matrix, text_auto=True, title="Correlation Matrix")
st.plotly_chart(fig_heatmap)
# Section: Statistical Tests
elif section == "Statistical Tests":
st.write("### Statistical Tests")
test_type = st.selectbox("Select Test Type", ["T-Test", "Chi-Square Test", "ANOVA"])
if test_type == "T-Test":
col1 = st.selectbox("Select First Numerical Column", numerical_cols)
col2 = st.selectbox("Select Second Numerical Column", numerical_cols)
t_stat, p_value = stats.ttest_ind(df[col1], df[col2])
st.write(f"T-Statistic: {t_stat:.4f}, P-Value: {p_value:.4f}")
elif test_type == "Chi-Square Test":
col1 = st.selectbox("Select First Categorical Column", categorical_cols)
col2 = st.selectbox("Select Second Categorical Column", categorical_cols)
contingency_table = pd.crosstab(df[col1], df[col2])
chi2, p_value, _, _ = stats.chi2_contingency(contingency_table)
st.write(f"Chi-Square Statistic: {chi2:.4f}, P-Value: {p_value:.4f}")
elif test_type == "ANOVA":
group_col = st.selectbox("Select Grouping Column", categorical_cols)
value_col = st.selectbox("Select Numerical Column", numerical_cols)
groups = [df[value_col][df[group_col] == group] for group in df[group_col].unique()]
f_stat, p_value = stats.f_oneway(*groups)
st.write(f"F-Statistic: {f_stat:.4f}, P-Value: {p_value:.4f}")
# Section: Export Data
elif section == "Export Data":
st.write("### Export Cleaned Data")
if st.button("Export Data to CSV"):
csv_data = df.to_csv(index=False)
st.download_button(label="Download CSV", data=csv_data, file_name="cleaned_data.csv", mime="text/csv")
if st.button("Export Data to Excel"):
excel_data = df.to_excel("cleaned_data.xlsx", index=False)
with open("cleaned_data.xlsx", "rb") as f:
st.download_button(label="Download Excel", data=f, file_name="cleaned_data.xlsx", mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")