riyarathore1825/universal
0
1import streamlit as st2import pandas as pd3import numpy as np4import matplotlib.pyplot as plt5import seaborn as sns6 7# -------------------------8# Page config9# -------------------------10st.set_page_config(page_title="Universal Data Analytics Dashboard", layout="centered")11st.title("๐ Universal Data Analytics Dashboard")12 13# -------------------------14# File Upload15# -------------------------16uploaded_file = st.file_uploader("Upload CSV file", type=["csv"])17 18# -------------------------19# Cached Functions20# -------------------------21@st.cache_data22def load_data(file):23 return pd.read_csv(file)24 25@st.cache_data26def compute_pivot(df, row, col, val, agg):27 try:28 pivot = pd.pivot_table(df, index=row, columns=col, values=val, aggfunc=agg)29 return pivot30 except:31 return None32 33# -------------------------34# Main Logic35# -------------------------36if uploaded_file:37 df = load_data(uploaded_file)38 st.success("Dataset uploaded successfully!")39 40 # -------------------------41 # Dataset Preview & Info42 # -------------------------43 st.subheader("๐ Dataset Preview")44 st.dataframe(df.head())45 46 st.subheader("๐ Dataset Info")47 col1, col2, col3 = st.columns(3)48 col1.metric("Total Rows", df.shape[0])49 col2.metric("Total Columns", df.shape[1])50 col3.metric("Duplicate Rows", df.duplicated().sum())51 52 st.write("### Missing Values")53 st.dataframe(df.isna().sum())54 55 numeric_cols = df.select_dtypes(include=np.number).columns.tolist()56 categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()57 58 # -------------------------59 # Data Cleaning60 # -------------------------61 st.subheader("๐งน Data Cleaning Options")62 if st.checkbox("Remove Duplicate Rows"):63 before = df.shape[0]64 df = df.drop_duplicates()65 after = df.shape[0]66 st.success(f"Removed {before - after} duplicate rows.")67 68 if st.checkbox("Fill Missing Values"):69 for col in df.columns:70 if df[col].dtype in [np.float64, np.int64]:71 df[col] = df[col].fillna(df[col].median())72 else:73 df[col] = df[col].fillna(df[col].mode()[0])74 st.success("Missing values filled (numeric: median, categorical: mode).")75 76 st.write("### Cleaned Data Preview")77 st.dataframe(df.head())78 79 # -------------------------80 # Visualizations81 # -------------------------82 st.subheader("๐ Visualizations")83 chart_type = st.selectbox(84 "Choose chart type",85 ["Histogram", "Bar Chart", "Pie Chart", "Line Chart", "Scatter Plot", "Correlation Heatmap"]86 )87 88 col_x = col_y = None89 90 if chart_type in ["Histogram", "Line Chart", "Scatter Plot"]:91 if len(numeric_cols) == 0:92 st.warning("No numeric columns available for this chart.")93 else:94 col_x = st.selectbox("X Column", numeric_cols)95 if chart_type in ["Line Chart", "Scatter Plot"]:96 col_y = st.selectbox("Y Column", numeric_cols)97 98 elif chart_type in ["Bar Chart", "Pie Chart"]:99 col_x = st.selectbox("Column", df.columns)100 101 fig, ax = plt.subplots(figsize=(5,4))102 plt.tight_layout()103 104 try:105 if chart_type == "Histogram" and col_x:106 colors = sns.color_palette("pastel", 10)107 ax.hist(df[col_x].dropna(), bins=20, color=colors[0], edgecolor='black')108 ax.set_xlabel(col_x)109 ax.set_ylabel("Frequency")110 ax.set_title(f"Histogram of {col_x}", fontsize=10)111 st.pyplot(fig)112 113 elif chart_type == "Bar Chart" and col_x:114 counts = df[col_x].value_counts().head(15)115 colors = sns.color_palette("bright", len(counts))116 counts.plot(kind='bar', ax=ax, color=colors)117 ax.set_ylabel("Count")118 ax.set_title(f"Bar Chart of {col_x}", fontsize=10)119 st.pyplot(fig)120 121 elif chart_type == "Pie Chart" and col_x:122 counts = df[col_x].value_counts().head(10)123 colors = sns.color_palette("Set2", len(counts))124 counts.plot(kind='pie', autopct="%1.1f%%", ax=ax,125 textprops={"fontsize": 8}, colors=colors)126 ax.set_ylabel("")127 ax.set_title(f"Pie Chart of {col_x}", fontsize=10)128 st.pyplot(fig)129 130 elif chart_type == "Line Chart" and col_x and col_y:131 ax.plot(df[col_x], df[col_y], marker='o', linestyle='-', color='green')132 ax.set_xlabel(col_x)133 ax.set_ylabel(col_y)134 ax.grid(True, linestyle='--', alpha=0.5)135 ax.set_title(f"Line Chart: {col_x} vs {col_y}", fontsize=10)136 st.pyplot(fig)137 138 elif chart_type == "Scatter Plot" and col_x and col_y:139 ax.scatter(df[col_x], df[col_y], color='red', s=20, alpha=0.7)140 ax.set_xlabel(col_x)141 ax.set_ylabel(col_y)142 ax.grid(True, linestyle='--', alpha=0.5)143 ax.set_title(f"Scatter Plot: {col_x} vs {col_y}", fontsize=10)144 st.pyplot(fig)145 146 elif chart_type == "Correlation Heatmap":147 if len(numeric_cols) >= 2:148 sns.heatmap(df[numeric_cols].corr(), annot=True, cmap="coolwarm", ax=ax, cbar=True)149 ax.set_title("Correlation Heatmap", fontsize=10)150 st.pyplot(fig)151 else:152 st.warning("Not enough numeric columns for heatmap.")153 154 except Exception as e:155 st.error(f"Unable to create chart: {e}")156 157 # -------------------------158 # Pivot Table159 # -------------------------160 st.subheader("๐ Pivot Table")161 if len(numeric_cols) > 0 and len(df.columns) >= 2:162 row_pt = st.selectbox("Row", df.columns, key="row_pt")163 col_pt = st.selectbox("Column", df.columns, key="col_pt")164 val_pt = st.selectbox("Values", numeric_cols, key="val_pt")165 agg = st.selectbox("Aggregation", ["sum", "mean", "count", "min", "max"], key="agg_func")166 167 pivot = compute_pivot(df, row_pt, col_pt, val_pt, agg)168 if pivot is not None:169 st.dataframe(pivot)170 else:171 st.warning("Pivot table cannot be created with selected columns.")172 else:173 st.warning("Not enough numeric columns for pivot table.")174 175else:176 st.info("๐ Please upload a CSV file to start.")177 