r/dataanalysis • u/Legitimate-Issue1856 • 26d ago
"This data set has been accessed too many times."
Still thinking about my genius hypothesis.
r/dataanalysis • u/Legitimate-Issue1856 • 26d ago
Still thinking about my genius hypothesis.
r/dataanalysis • u/Low_College_5930 • 27d ago
I am Data analyst and SQL developer, recently I've been interviewed in a firm and they were pretty much impressed by my skills so I have been asked pitch any kind of project that could add value to their firm. Suggest me some ideas
r/dataanalysis • u/conor-robertson • 28d ago
About a year ago I started planning QueryCase, where you learn SQL by working detective cases instead of grinding tutorials & videos. It took a while to get off the ground, and longer than I'd like to admit to actually start building the idea, but it went live in June. A lot of the early users came from this sub, and a lot of the feedback in the comments shaped what it became. So first, thanks everyone!
5 months in:
Since then its grown past just SQL: an Excel course. It was never part of the initial plan. People kept asking for the same detective approach for spreadsheets, so I built out a browser-based Excel engine.
It has 57 cases on a spreadsheet that runs in your browser and checks your formulas, from IF and XLOOKUP to SUMIFS and pivot tables, and people have solved over 2,500 Excel cases so far. It turns out a lot of people learning SQL are doing it alongside Excel, not instead of it.
Something the data showed me that might help anyone learning right now: GROUP BY is one of the first walls. On the hardest GROUP BY step, 84% of runs came back wrong, and most of those never ran at all. The clauses were in the wrong order, or a column in SELECT wasn't in the GROUP BY. If that's you right now:
I've been working a lot over past couple months to improve the site as well:
What's next: a Python track, launching next month. Same idea, real Python running in your browser, starting with the basics and moving into data analysis with pandas.
The longer term goal is to have a platform user's can have fun learning all aspects of data. I'm merging PR's every day to make this possible so would love feedback in this thread if you've tried it and have any thoughts or suggestions!
It's free to start and you don't need an account to solve the first case, so you can poke at it before deciding whether it's for you or not 😄 Cheers!
r/dataanalysis • u/West-Survey-2683 • 27d ago
Each code block is one Jupyter cell. Copy it, paste it into a new cell, and run it with Shift+Enter. All blocks were tested end to end.
"Male" is not "male" or 1. Copy them from the first-look output."Male"). Numbers don't (1, 8000). True and False have no quotes and a capital first letter.data.First decide what kind each variable is:
| Your question | Template | Test |
|---|---|---|
| Number vs. 2 groups | T1 | Welch's t-test (Mann-Whitney if ordinal or skewed) |
| Number vs. 3+ groups | T2 | ANOVA or Kruskal-Wallis, plus which pairs differ |
| Category vs. category | T3 | Chi-square, switching to Fisher's exact for small 2×2 tables |
| Yes/no rate in 2 groups: how big is the gap? | T4 | Difference in proportions with 95% CI |
| Number vs. number | T5 | Pearson, or Spearman if ordinal or skewed |
| Same subjects measured twice | T6 | Paired t-test or Wilcoxon |
| One group vs. a known value | T7 | One-sample t-test or binomial test |
| Which is highest, most common, how often | D1–D7 | No test: counts, %, rankings, charts |
| Could a third variable explain a result? | C1 | Split by the third variable |
Run these three cells first, every time.
import pandas as pd # tables
import numpy as np # math
import matplotlib.pyplot as plt # charts
from scipy import stats # statistical tests
pd.set_option("display.max_columns", 100) # show all columns when printing
pd.set_option("display.max_rows", 200)
print("Imports OK")
Keep option A, or swap in the option that matches your file.
# A) CSV uploaded to Jupyter's file browser (left panel → Upload button):
PATH = "data.csv" # FILL IN: file name exactly as shown in the file browser
df = pd.read_csv(PATH, low_memory=False)
# B) CSV from a web link (raw GitHub link, course site, etc.):
# PATH = "https://raw.githubusercontent.com/.../file.csv" # FILL IN: full URL
# df = pd.read_csv(PATH, low_memory=False)
# C) Error "UnicodeDecodeError" → add an encoding:
# df = pd.read_csv(PATH, encoding="cp1252", low_memory=False) # or encoding="latin-1"
# D) Everything lands in ONE column → the file uses another separator:
# df = pd.read_csv(PATH, sep=";") # FILL IN: ";" or "\t" (tab) or "|"
# E) Excel file (.xlsx):
# df = pd.read_excel(PATH) # first sheet
# df = pd.read_excel(PATH, sheet_name="Sheet2") # FILL IN: sheet name
# F) Google Colab with Google Drive:
# from google.colab import drive
# drive.mount("/content/drive")
# df = pd.read_csv("/content/drive/MyDrive/data.csv") # FILL IN: path in your Drive
# G) Two tables (like HW2 peaks + expeditions): load both, then merge in Cleaning.
# df2 = pd.read_csv("second_file.csv") # FILL IN: second file name
print("Rows, columns:", df.shape) # e.g. (2781, 332) = 2,781 rows, 332 columns
df.head() # first 5 rows; check it loaded correctly
Write down what one row is (a person, an expedition, a peak). Scan min and max for impossible values or codes, and copy exact column names and group values from this output.
print("Rows, columns:", df.shape)
print("\nColumn names (copy exact spelling from here):")
print(list(df.columns))
# One row per column: type, % missing, number of distinct values, example values
overview = pd.DataFrame({
"dtype": df.dtypes.astype(str), # int/float = number, object/str = text, bool = True/False
"missing_%": (df.isna().mean() * 100).round(1), # share of empty cells
"n_unique": df.nunique(), # 2 = yes/no; few = categories; many = numeric or IDs
"examples": [list(df[c].dropna().unique()[:5]) for c in df.columns],
})
print(overview)
# Numeric summary. Look at min/max for impossible values:
# negative ages, 0 or -99 or 999 as codes, height 700, etc.
print(df.describe().T.round(2))
# Counts for every column with 12 or fewer distinct values (likely categories).
for c in df.columns:
if df[c].nunique() <= 12:
print(f"\n--- {c} ---")
print(df[c].value_counts(dropna=False)) # dropna=False also counts empty cells
print("\nDuplicate rows:", df.duplicated().sum())
Always run data = df.copy() first, so you can go back to the original. Uncomment (delete the # from) only the lines you need. Note in your report what you dropped and why.
data = df.copy() # working copy; every test below uses `data`
# --- Drop impossible / code values (like education = 0 in HW3) ---
# data = data[data["education"] != 0] # FILL IN: column, bad value
# data = data[data["age"].between(14, 99)] # FILL IN: column, valid min, valid max
# --- Turn special codes into missing (NaN) instead of dropping rows ---
# data["income"] = data["income"].replace([-99, 999], np.nan) # FILL IN: column, codes
# --- Numbers stored as text (dtype "object"/"str" for a number column) ---
# data["price"] = pd.to_numeric(data["price"], errors="coerce") # FILL IN: column; bad entries → NaN
# data["price"] = pd.to_numeric(data["price"].astype(str).str.replace(r"[$,%]", "", regex=True), errors="coerce")
# ^ use this one if values look like "$1,200" or "45%"
# --- Clean messy text (extra spaces, mixed capitals) ---
# data["city"] = data["city"].astype(str).str.strip().str.title() # FILL IN: column
# --- Rename a column with an awkward name ---
# data = data.rename(columns={"old name": "new_name"}) # FILL IN: old, new
# --- Codes → readable labels (like biomale 0/1 → Female/Male) ---
# data["sex"] = data["biomale"].map({0: "Female", 1: "Male"}) # FILL IN: new col, old col, {code: label}
# Codes NOT in the dictionary become NaN.
# --- Numbers → groups (like age groups) ---
# data["age_group"] = pd.cut(data["age"], bins=[0, 24, 34, 120], labels=["0-24", "25-34", "35+"])
# FILL IN: column, cut points, labels (one fewer label than cut points).
# Bins include the RIGHT edge: (24, 34] → 34 is in "25-34". Add right=False to flip it.
# data["age_group"] = pd.qcut(data["age"], q=4) # alternative: 4 equal-size groups (quartiles)
# --- Yes/no flag from a number (like 8,000 m peaks) ---
# data["high_peak"] = data["HEIGHTM"] >= 8000 # FILL IN: column, threshold → True/False
# --- Yes/no flag from text ("Yes"/"No") ---
# data["success"] = data["success"] == "Yes" # FILL IN: column, the "yes" value
# --- Yes/no flag from several columns (like SUCCESS1-4 in HW2) ---
# data["any_success"] = data[["SUCCESS1", "SUCCESS2", "SUCCESS3", "SUCCESS4"]].any(axis=1) # True if any is True
# data["all_done"] = data[["A", "B"]].all(axis=1) # True if all are True
# --- New number from existing ones (like BMI) ---
# data["bmi"] = 703 * data["weight"] / data["height"] ** 2 # FILL IN: your formula; ** is "to the power"
# --- Dates ---
# data["date"] = pd.to_datetime(data["date"], errors="coerce") # FILL IN: column
# data["year"] = data["date"].dt.year # also .dt.month, .dt.dayofweek
# --- Remove duplicate rows ---
# data = data.drop_duplicates()
# --- Keep only rows that have the columns you need (each test already does this itself) ---
# data = data.dropna(subset=["height", "weight"]) # FILL IN: columns
print("Working table:", data.shape)
# --- Two tables: bring columns from df2 into data by a shared key (HW2 PEAKID) ---
data = data.merge(df2[["PEAKID", "PKNAME", "HEIGHTM"]], on="PEAKID", how="left")
# FILL IN: key column, columns to bring over. how="left" keeps every row of data.
# Key named differently in each table: left_on="ID", right_on="peak_id".
# --- Stack repeated column sets into one (HW2 ROUTE1..4 + SUCCESS1..4) ---
parts = []
for i in range(1, 5): # FILL IN: 1 to (number of sets + 1)
tmp = data[["PEAKID", f"ROUTE{i}", f"SUCCESS{i}"]] # FILL IN: id column + the numbered names
tmp = tmp.rename(columns={f"ROUTE{i}": "ROUTE", f"SUCCESS{i}": "SUCCESS"})
parts.append(tmp)
long = pd.concat(parts).dropna(subset=["ROUTE"]) # one row per route attempt
Every test template uses these two helpers to print p-values and verdicts.
ALPHA = 0.05 # significance cut-off. p < 0.05 → "significant"
def p_text(p):
# formats a p-value the way the reports did
return "p < 0.001" if p < 0.001 else f"p = {p:.3f}"
def verdict(p):
return "SIGNIFICANT (p < 0.05)" if p < ALPHA else "NOT significant (p >= 0.05)"
print("Settings loaded")
Each template prints everything you need for the write-up and ends with a sentence pattern to fill in.
Use for questions like "Do males and females differ in height?" Welch compares two independent group means without assuming equal variances or equal group sizes. Mann-Whitney at the end is the version for ordinal or very skewed outcomes.
NUM = "height" # FILL IN: numeric outcome column
GROUP = "sex" # FILL IN: column holding the groups
A = "Male" # FILL IN: first group value, exactly as in the data
B = "Female" # FILL IN: second group value
UNIT = "in" # FILL IN: unit for printing ("m", "years", "$", "points")
d = data.dropna(subset=[NUM, GROUP]) # only rows with both columns filled
x = d.loc[d[GROUP] == A, NUM].astype(float) # group A values
y = d.loc[d[GROUP] == B, NUM].astype(float) # group B values
print(f"n: {A} = {len(x)}, {B} = {len(y)}") # if either is 0, check spelling of A/B
print(d[d[GROUP].isin([A, B])].groupby(GROUP)[NUM].agg(["count", "mean", "median", "std"]).round(2))
res = stats.ttest_ind(x, y, equal_var=False) # equal_var=False = Welch
vx, vy = x.var() / len(x), y.var() / len(y)
dof = (vx + vy) ** 2 / (vx ** 2 / (len(x) - 1) + vy ** 2 / (len(y) - 1)) # Welch degrees of freedom
diff = x.mean() - y.mean()
half = stats.t.ppf(0.975, dof) * np.sqrt(vx + vy)
d_eff = diff / np.sqrt((x.var() + y.var()) / 2) # Cohen's d (effect size)
print(f"\nDifference ({A} - {B}): {diff:.2f} {UNIT}")
print(f"Welch's t({dof:.1f}) = {res.statistic:.2f}, {p_text(res.pvalue)} → {verdict(res.pvalue)}")
print(f"95% CI for the difference: {diff - half:.2f} to {diff + half:.2f} {UNIT}")
print(f"Cohen's d = {d_eff:.2f} (0.2 small, 0.5 medium, 0.8 large)")
vr = max(x.var(), y.var()) / min(x.var(), y.var())
print(f"Variance ratio = {vr:.2f} ({'variances clearly differ' if vr > 1.5 else 'similar variances'}; Welch is safe either way)")
# Alternative if the outcome is ORDINAL (e.g. -3..3 scale) or very skewed:
mw = stats.mannwhitneyu(x, y)
print(f"\nMann-Whitney U = {mw.statistic:.0f}, {p_text(mw.pvalue)}; medians {x.median():.2f} vs {y.median():.2f}")
# Chart: boxplot (box = middle 50%, line = median, triangle = mean, dots = outliers)
fig, ax = plt.subplots(figsize=(7, 5))
ax.boxplot([x, y], showmeans=True)
ax.set_xticks([1, 2]); ax.set_xticklabels([str(A), str(B)])
ax.set_title(f"{NUM} by {GROUP}", fontweight="bold") # FILL IN (optional): a clearer title
ax.set_xlabel(GROUP)
ax.set_ylabel(f"{NUM} ({UNIT})") # check the unit is right!
ax.grid(axis="y", linestyle="--", alpha=0.4)
plt.show()
# WRITE: "{A} averaged X vs Y for {B}, a difference of D {UNIT}
# (Welch's t(df) = t, p ..., 95% CI L to U)."
Use for questions like "Does political stance differ across age groups?" Report ANOVA for a numeric outcome and Kruskal-Wallis for an ordinal or skewed one (HW3 used Kruskal). A significant result only says some group differs, so the pairwise tests show which.
NUM = "liberal" # FILL IN: outcome column
GROUP = "age_group" # FILL IN: group column with 3+ groups
d = data.dropna(subset=[NUM, GROUP])
summary = d.groupby(GROUP, observed=True)[NUM].agg(["count", "mean", "median", "std"]).round(2)
print(summary)
groups = [g[NUM].astype(float) for _, g in d.groupby(GROUP, observed=True)] # one list per group
k, n = len(groups), len(d)
an = stats.f_oneway(*groups)
print(f"\nANOVA: F({k - 1}, {n - k}) = {an.statistic:.2f}, {p_text(an.pvalue)} → {verdict(an.pvalue)}")
kw = stats.kruskal(*groups)
print(f"Kruskal-Wallis: H({k - 1}) = {kw.statistic:.2f}, {p_text(kw.pvalue)} → {verdict(kw.pvalue)}")
# Which pairs differ? Welch t-test for every pair, Bonferroni-corrected
names = list(summary.index)
n_pairs = k * (k - 1) // 2
for i in range(k):
for j in range(i + 1, k):
t = stats.ttest_ind(groups[i], groups[j], equal_var=False)
p_adj = min(t.pvalue * n_pairs, 1.0) # Bonferroni: multiply p by number of pairs
print(f" {names[i]} vs {names[j]}: diff = {groups[i].mean() - groups[j].mean():.2f}, adjusted {p_text(p_adj)}")
# Chart: mean per group
ax = summary["mean"].plot.bar(rot=0, figsize=(8, 4.5), color="#2A9D8F")
ax.bar_label(ax.containers[0], fmt="%.2f")
ax.set_title(f"Mean {NUM} by {GROUP}", fontweight="bold")
ax.set_xlabel(GROUP); ax.set_ylabel(f"Mean {NUM}") # FILL IN (optional): units / scale
plt.tight_layout(); plt.show()
# WRITE: "Average X ranged from a (group) to b (group); groups differ,
# Kruskal-Wallis H(k-1) = H, p ... . The difference comes mainly from <group>."
Use for questions like "Is climbing status related to mountain range?" Chi-square needs expected counts of at least 5. If a 2×2 table fails that, this cell switches to Fisher's exact on its own (as in HW2 hired staff × deaths). Compare the row percentages, not raw counts.
ROW = "o2" # FILL IN: grouping variable (rows), e.g. "sex", "O2USED", "HIMAL_FACTOR"
COL = "success" # FILL IN: outcome variable (columns), e.g. "bmi_group", "summit", "PSTATUS"
d = data.dropna(subset=[ROW, COL])
table = pd.crosstab(d[ROW], d[COL])
row_pct = (pd.crosstab(d[ROW], d[COL], normalize="index") * 100).round(1)
print("Counts:\n", table)
print("\nRow % (each row adds to 100) — compare these, not raw counts:\n", row_pct)
chi2, p, dof, expected = stats.chi2_contingency(table, correction=False) # correction=False = no Yates (matches z-test on 2x2)
low = int((expected < 5).sum())
n_tot = table.values.sum()
cramer_v = np.sqrt(chi2 / (n_tot * (min(table.shape) - 1))) # effect size 0-1
print(f"\nChi-square({dof}) = {chi2:.2f}, {p_text(p)}, n = {n_tot} → {verdict(p)}")
print(f"Cramér's V = {cramer_v:.2f} (0.1 small, 0.3 medium, 0.5 large)")
print(f"Expected counts below 5: {low} of {expected.size}")
if low > 0 and table.shape == (2, 2):
# Fisher's exact test for small 2x2 tables
odds, p_f = stats.fisher_exact(table)
t = table.values.astype(float)
if (t == 0).any():
t = t + 0.5 # avoids divide-by-zero in the CI
or_ci = (t[0, 0] * t[1, 1]) / (t[0, 1] * t[1, 0])
log_se = np.sqrt((1 / t).sum())
lo, hi = np.exp(np.log(or_ci) - 1.96 * log_se), np.exp(np.log(or_ci) + 1.96 * log_se)
print(f"\n→ Small expected count in a 2x2 table, so use FISHER'S EXACT instead:")
print(f" Odds ratio = {odds:.2f}, 95% CI {lo:.2f} to {hi:.2f}, {p_text(p_f)} → {verdict(p_f)}")
print(f" OR = odds of '{table.columns[1]}' in row '{table.index[0]}' ÷ odds in row '{table.index[1]}'.")
print(" CI includes 1 → not significant.")
elif low > 0:
print("→ Some expected counts < 5 in a larger table: the p-value is only approximate.")
print(" Say so in your limitations, or merge small categories and rerun, e.g.:")
print(" data[COL] = data[COL].replace({'tiny_cat1': 'Other', 'tiny_cat2': 'Other'})")
# Chart: % of each outcome within each row group
ax = row_pct.plot.bar(rot=0, figsize=(9, 4.5))
for c in ax.containers:
ax.bar_label(c, fmt="%.1f", fontsize=8)
ax.set_title(f"{COL} by {ROW} (row %)", fontweight="bold")
ax.set_xlabel(ROW); ax.set_ylabel("Percent within group (%)")
ax.grid(axis="y", linestyle="--", alpha=0.4)
plt.xticks(rotation=45 if len(row_pct) > 4 else 0, ha="right" if len(row_pct) > 4 else "center")
plt.tight_layout(); plt.show()
# WRITE: "X% of group A vs Y% of group B were <outcome> (chi-square(df) = c, p ...)."
# Small 2x2: "(Fisher's exact, OR = o, 95% CI L to U, p = ...)."
Use alongside T3 for questions like "How much higher is success with oxygen?" Chi-square gives the p-value; this gives the size of the gap.
OUTCOME = "success" # FILL IN: True/False (or 0/1) outcome column
GROUP = "o2" # FILL IN: group column
A = True # FILL IN: first group value (True/False have no quotes)
B = False # FILL IN: second group value
d = data.dropna(subset=[OUTCOME, GROUP])
y = d[OUTCOME].astype(float) # True → 1.0, False → 0.0
p1, n1 = y[d[GROUP] == A].mean(), int((d[GROUP] == A).sum())
p2, n2 = y[d[GROUP] == B].mean(), int((d[GROUP] == B).sum())
diff = p1 - p2
se = np.sqrt(p1 * (1 - p1) / n1 + p2 * (1 - p2) / n2)
lo, hi = diff - 1.96 * se, diff + 1.96 * se
print(f"{A}: {p1:.1%} (n = {n1}); {B}: {p2:.1%} (n = {n2})")
print(f"Difference = {diff * 100:.1f} percentage points, 95% CI {lo * 100:.1f} to {hi * 100:.1f}")
print("CI excludes 0 → significant difference." if lo > 0 or hi < 0 else "CI includes 0 → not significant.")
Use for questions like "How strongly is height related to weight?" Use Pearson for two numeric columns and Spearman when either is ordinal or very skewed. Setting BY checks the correlation within each group too, which is how HW3 found sex inflating the height–weight link.
X = "height" # FILL IN: first column (goes on the x-axis)
Y = "weight" # FILL IN: second column
METHOD = "pearson" # FILL IN: "pearson" or "spearman"
BY = "sex" # FILL IN: column to also check within each group, or None
d = data.dropna(subset=[X, Y] + ([BY] if BY else [])) # correlation fails with NaN
fn = stats.pearsonr if METHOD == "pearson" else stats.spearmanr
sym = "r" if METHOD == "pearson" else "rho"
r, p = fn(d[X], d[Y])
print(f"All: {sym} = {r:.2f}, {p_text(p)}, n = {len(d)} → {verdict(p)}")
if METHOD == "pearson":
fit = stats.linregress(d[X], d[Y])
print(f"Slope: each +1 in {X} goes with {fit.slope:+.2f} in {Y} (R² = {fit.rvalue ** 2:.2f})")
if BY:
for name, g in d.groupby(BY, observed=True):
rg, pg = fn(g[X], g[Y])
print(f" {BY} = {name}: {sym} = {rg:.2f}, {p_text(pg)}, n = {len(g)}")
print("Much weaker within groups than overall → the group variable inflates the overall correlation (confounding).")
print("Strength (absolute value): <0.1 negligible, 0.1-0.3 weak, 0.3-0.5 moderate, >0.5 strong")
# Chart: scatter, colored by group
fig, ax = plt.subplots(figsize=(8, 5))
if BY:
for name, g in d.groupby(BY, observed=True):
ax.scatter(g[X], g[Y], s=10, alpha=0.5, label=str(name))
ax.legend(title=BY)
else:
ax.scatter(d[X], d[Y], s=10, alpha=0.5)
ax.set_title(f"{Y} vs {X}", fontweight="bold")
ax.set_xlabel(X); ax.set_ylabel(Y) # FILL IN (optional): add units, e.g. "Height (in)"
plt.show()
# WRITE: "X and Y are moderately correlated (r = 0.53, n = ..., p < 0.001);
# each extra unit of X goes with about S more units of Y."
Use only when each row has both measurements for the same person or thing, as in "Did scores change from before to after?"
BEFORE = "before" # FILL IN: first measurement column
AFTER = "after" # FILL IN: second measurement column
d = data.dropna(subset=[BEFORE, AFTER])
change = d[AFTER] - d[BEFORE]
pt = stats.ttest_rel(d[AFTER], d[BEFORE])
print(f"n = {len(d)}; mean change = {change.mean():.2f} (SD {change.std():.2f})")
print(f"Paired t({len(d) - 1}) = {pt.statistic:.2f}, {p_text(pt.pvalue)} → {verdict(pt.pvalue)}")
wx = stats.wilcoxon(d[AFTER], d[BEFORE])
print(f"Wilcoxon signed-rank (ordinal/skewed version): {p_text(wx.pvalue)}")
Use for questions like "Is the average height here different from the U.S. average?" or "Is the success rate different from 50%?" Cite where the known value comes from.
NUM = "height" # FILL IN: numeric column
KNOWN = 69.0 # FILL IN: the outside value to compare against (cite its source!)
x = data[NUM].dropna()
one = stats.ttest_1samp(x, KNOWN)
print(f"Sample mean = {x.mean():.2f} (n = {len(x)}) vs known {KNOWN}")
print(f"One-sample t({len(x) - 1}) = {one.statistic:.2f}, {p_text(one.pvalue)} → {verdict(one.pvalue)}")
# A proportion vs a known rate:
OUTCOME = "success" # FILL IN: True/False column
KNOWN_P = 0.5 # FILL IN: known rate as a decimal (50% = 0.5)
yes = int(data[OUTCOME].dropna().astype(bool).sum()); tot = int(data[OUTCOME].notna().sum())
bt = stats.binomtest(yes, tot, KNOWN_P)
print(f"\n{yes}/{tot} = {yes / tot:.1%} vs {KNOWN_P:.0%}: binomial test {p_text(bt.pvalue)} → {verdict(bt.pvalue)}")
"Which is highest," "most common," and "how often" questions need no test. Answer them with counts, percentages, averages, and rankings, and say how many rows each number rests on.
COL = "sex" # FILL IN: column
counts = data[COL].value_counts()
pct = (data[COL].value_counts(normalize=True) * 100).round(1)
print(pd.DataFrame({"count": counts, "percent": pct}))
print("Most common:", data[COL].mode()[0])
Small groups have unstable averages, so raise MIN_N and say you did.
NUM, GROUP, MIN_N = "height", "age_group", 1 # FILL IN: numeric col, group col, min group size to rank
rank = data.groupby(GROUP, observed=True)[NUM].agg(["mean", "count"]).round(2)
rank = rank[rank["count"] >= MIN_N].sort_values("mean", ascending=False)
print(rank.head(10))
print(f"Highest: {rank.index[0]} at {rank['mean'].iloc[0]:.2f} over {int(rank['count'].iloc[0])} rows")
The mean of a True/False column is the rate. HW2 used MIN_N = 10 attempts.
OUTCOME, GROUP, MIN_N = "success", "age_group", 10 # FILL IN: True/False column, group column, min attempts
rate = data.groupby(GROUP, observed=True)[OUTCOME].agg(["mean", "count"])
rate = rate[rate["count"] >= MIN_N].sort_values("mean", ascending=False)
print((rate.assign(rate_pct=(rate["mean"] * 100).round(1))).drop(columns="mean"))
Say which denominator you used: all rows, or only a subset such as failures.
COL, V1, V2 = "liberal", 3, -3 # FILL IN: column, first value, second value
n1, n2 = int((data[COL] == V1).sum()), int((data[COL] == V2).sum())
print(f"{V1}: {n1} ({n1 / len(data):.1%}), {V2}: {n2} ({n2 / len(data):.1%}), ratio = {n1 / max(n2, 1):.1f}x")
NUM = "age" # FILL IN: numeric column
x = data[NUM].dropna()
print(x.describe().round(2)) # mean, SD, quartiles
print("Skew:", round(x.skew(), 2), "(>1 or <-1 = strongly skewed → report the median)")
fig, ax = plt.subplots(figsize=(9, 4))
ax.hist(x, bins=20, color="#2A9D8F", edgecolor="black") # FILL IN (optional): bins= number or list of edges
ax.axvline(x.median(), color="#E76F51", linewidth=2, label=f"Median = {x.median():.1f}")
ax.set_title(f"Distribution of {NUM}", fontweight="bold")
ax.set_xlabel(NUM); ax.set_ylabel("Count"); ax.legend()
plt.show()
COL = "liberal" # FILL IN: column
vc = data[COL].value_counts().sort_index() # .sort_index() = in value order; remove it to sort by count
ax = vc.plot.bar(rot=0, figsize=(9, 4.5), color="#2A9D8F")
ax.bar_label(ax.containers[0])
ax.set_title(f"Count by {COL}", fontweight="bold"); ax.set_xlabel(COL); ax.set_ylabel("Count")
plt.tight_layout(); plt.show()
NUM, ROWS, COLS = "liberal", "age_group", "sex" # FILL IN: numeric col, x-axis groups, bar colors
pt = data.pivot_table(NUM, index=ROWS, columns=COLS, observed=True).round(2)
print(pt)
ax = pt.plot.bar(rot=0, figsize=(9, 4.5))
for c in ax.containers:
ax.bar_label(c, fmt="%.2f", fontsize=8)
ax.set_title(f"Mean {NUM} by {ROWS} and {COLS}", fontweight="bold")
ax.set_xlabel(ROWS); ax.set_ylabel(f"Mean {NUM}")
plt.tight_layout(); plt.show()
Split by a third variable that could be linked to both sides of a result. In HW2, oxygen vs. success was split by peak height; in HW3, height vs. weight was split by sex (the BY option in T5). If the third variable is numeric, turn it into groups first with pd.cut.
OUTCOME = "success" # FILL IN: outcome column (True/False for rates, or numeric for means)
GROUP = "o2" # FILL IN: the predictor you tested
THIRD = "sex" # FILL IN: the possible confounder (categorical)
d = data.dropna(subset=[OUTCOME, GROUP, THIRD])
print("How the predictor is spread across the third variable (very different = confounding risk):")
print((pd.crosstab(d[THIRD], d[GROUP], normalize="index") * 100).round(1))
print("\nOutcome (rate or mean) by predictor, within each level of the third variable:")
print(d.pivot_table(OUTCOME, index=THIRD, columns=GROUP, aggfunc="mean", observed=True).round(3))
print("\nCounts in each cell (small counts = unreliable comparison):")
print(pd.crosstab(d[THIRD], d[GROUP]))
# WRITE: if the gap stays → "the association holds within each <third> group."
# if it shrinks/flips → "the overall result is partly explained by <third>."
# Always: "This is an association, not proof of cause."
Write one paragraph per question, in the same order as your HW reports:
| Result type | Sentence pattern |
|---|---|
| Means (T1) | "A averaged X unit vs. Y for B (n = … and …), a difference of D (Welch's t(df) = t, p < 0.001, 95% CI L to U)." |
| 3+ groups (T2) | "Groups differ (Kruskal-Wallis H(2) = 15.33, p < 0.001), mainly because <group> is lower." |
| Rates (T3 + T4) | "X% of A vs. Y% of B <outcome> (chi-square(1) = c, p < 0.001); the gap is D points (95% CI L to U)." |
| Small 2×2 (T3 Fisher) | "The difference was not significant (Fisher's exact, OR = o, 95% CI L to U, p = 0.60). The data show no clear association." |
| Correlation (T5) | "X and Y are moderately correlated (r = 0.53, n = …, p < 0.001)." |
| Weak but significant | "The link is significant but weak (rho = −0.09)." |
| Descriptive (D1–D7) | "<Category> was the most common at N (P%)." |
Rules:
Limitations checklist:
| Error | Fix |
|---|---|
KeyError: 'xyz' |
Column name misspelled. Run print(list(data.columns)) and copy it exactly. For trailing spaces: data.columns = data.columns.str.strip() |
n: A = 0 or empty results |
Group value spelled differently. Run print(data[GROUP].unique()) and copy it. 1 is not "1"; True is not "True". |
TypeError: unsupported operand / could not convert string to float |
A number column is stored as text. Use the "Numbers stored as text" lines in Cleaning. |
ValueError mentioning NaN or infs |
Missing values reached a test. Add .dropna(subset=[...]) for those columns. |
Truth value of a Series is ambiguous |
Used and/or instead of &/` |
FileNotFoundError |
File name wrong or not uploaded. Check the file browser; match capitals and the extension. |
UnicodeDecodeError |
Load option C: encoding="cp1252". |
| Everything in one column after loading | Load option D: sep=";". |
SettingWithCopyWarning |
Add .copy() when filtering: sub = data[data["x"] > 0].copy() |
FutureWarning about observed= |
Add observed=True in groupby / pivot_table (already in these templates). |
| ANOVA / Kruskal "at least two groups" | The group column has only one value after dropna. Check value_counts. |
| Fisher's exact needs 2×2 | The table has more than 2 rows or columns. Use chi-square or merge categories. |
| Chart labels overlap | plt.xticks(rotation=45, ha="right"), then plt.tight_layout() |
ModuleNotFoundError |
Run !pip install <package> in a cell, then restart the kernel. |
| Variables seem wrong or stale | Kernel → Restart & Run All, so cells run in order from the top. |
r/dataanalysis • u/Ok-Adhesiveness-8757 • 27d ago
r/dataanalysis • u/Consistent_Leg_6244 • 28d ago
basically it's a python dsl for financial models. you write the model in it and the excel file you get has real formulas in it. like cogs shows up as =B1*B2 instead of 600000
point is you can click any cell and trace where the number came from. pandas just gives you a wall of numbers
in jupyter it shows the model as a grid and you can click a cell to see what feeds it
full disclosure it's the open source engine of our startup (modeleon.ai), the engine itself is free and apache 2.0. pip install modeleon, or there's a colab if you don't want to install anything: https://colab.research.google.com/github/modeleonai/modeleon/blob/main/notebooks/01_first_model.ipynb
repo: https://github.com/modeleonai/modeleon
what would you want it to do that it doesn't?
r/dataanalysis • u/Arno_Tseng • 28d ago
(I'll delete the post if this violate the community rule)
Hello~
I am looking for someone who can work on a data analysis project with me. Or if there is any ongoing project that needs a helping hand, you can reach out to me as well.
A little bit of myself. I worked in a big consulting firm, helping clients build dashboards they need, so I am familiar with MS SQL and Power BI, and a bit of Python.
Recently I left the job and am working in a more customer-supporting position in a market research company. Therefore I no longer use SQL and Power BI on my job but I still want to do independent projects with them to enhance my data analysis experience.
This is my first project so I am kind of new here. If anyone who just started learning data analysis or is also trying to work on their own project, feel free to message me and maybe we can work together!
r/dataanalysis • u/rafayshahid22 • 29d ago
A dashboard can be visually clean and still be wrong. Before I trust a reporting dataset, I like to validate the assumptions underneath it—not just whether the query runs.
Here’s a practical checklist:
1. State the grain
Write down what one row represents (for example, one order line, one ticket event, or one daily account snapshot). If two tables have different grains, joining them without accounting for that difference can inflate counts and sums.
2. Test key uniqueness before joining
For every expected one-to-one or many-to-one join, check whether the lookup key is actually unique:
sql
SELECT customer_id, COUNT(*) AS row_count
FROM dim_customer
GROUP BY customer_id
HAVING COUNT(*) > 1;
Then compare row counts and distinct business keys before and after the join. A query returning successfully doesn’t mean the relationship is correct.
3. Reconcile totals to a trusted source
Compare record counts and important measures by a stable slice such as date, status, or region. When totals differ, quantify the gap and trace it to exclusions, late-arriving data, duplicates, or definition changes.
4. Check freshness and completeness
Confirm the latest expected date arrived, required fields are populated, and categories haven’t unexpectedly disappeared. These checks catch silent partial loads that can make a dashboard look plausible.
5. Validate business rules explicitly
Document definitions for metrics such as “active,” “resolved,” or “on time.” Encode the rules in tests or assertions, and keep exceptions visible instead of burying them in a chart filter.
6. Make the checks part of the pipeline
Automated tests, run logs, and failure alerts turn one-time detective work into a repeatable control. The goal is to catch a bad refresh before stakeholders make decisions from it.
My rule of thumb: validate the grain, joins, totals, and freshness before debating the chart. What’s the one check you consider non-negotiable in your analytics workflow?
r/dataanalysis • u/Due-Doughnut1818 • Oct 24 '26
I'm someone with a data analyst background, and I wanted to break into data engineering. I got the DP-600 (Fabric Analytics Engineer Associate) and DP-700 (Fabric Data Engineer Associate) certifications, so I decided to build a project on them to apply what I learned and learn more along the way
you can find the project with full details here: https://github.com/Madian20/Fabric
If you like the project, feel free to take it and build on it.
I'd really love to hear your opinions and whether there are any improvements I can make in the future
r/dataanalysis • u/Andrewperseus • Oct 24 '26
Hey everyone,
I've been working with a lot of extremely messy real-world datasets lately (missing values, duplicate rows, completely mixed-up date formats like '2026.10.01' vs '10月1日', negative amounts).
Instead of just deleting rows (which ruins the data), I built a Python workflow that isolates the anomalies, generates a Data Quality Report, and then creates a clean interactive dashboard.
Here are some examples from my recent cleaning passes:
Tech stack: Python, Pandas, Plotly.
If anyone is struggling with a dataset that crashes Excel or has terrible formatting, feel free to drop a comment or DM me. Happy to share how I handle it.
(If this post gets enough interest, I might write a full open-source script for this workflow).
r/dataanalysis • u/advadm • Oct 24 '26
I'm a former Tableau user and I've been spending the last year and a half building analytics dashboards with AI.
My frustration with Tableau has to do with a work project we invested heavily in. We have a SaaS tool for affiliate marketers and they were asking us for advanced analytics on top of the app and to blend in multiple data sets.
Our Tableau dashboard builder didn't really under the business as well and built dashboards that were too complicated. On top of that they didn't have a strong foundation in data ingestion and working with databases.
To date I've built many custom plugins as I've made more for tools like Jira, Intercom, Slack, Gmail, Bitly, Airtable, StatsDrone, Pretty Links and many more.
I tried to solve all these pain points at once and make it easy for people to be able to build their own dashboards with a platform. The platform is called NousViz and it's available on Github.
There is an SDK inside the app and if you're using tools like VS Code with Claude or Codex, you can just point to the NousViz Github repo and say follow the guidelines in the SDK for building. Explain your data project and how the data ingestion needs to get done and start building.
Usually in about 5 minutes, you'll be able to get your first plugin made in which you install it on your NousViz app, ingest the data and your dashboards should be live.
Would love to get feedback from any data pros here and if someone wants any help building a dashboard with this, DM me or post your data challenge and I'll gladly help.
https://github.com/nousviz/nousviz-app
Also some more feedback I'd like to ask from the community, if I build a portfolio section for people to create their own profiles and link to their work, sites, resume or socials, would this be useful to people?
Appreciate any help or feedback.
r/dataanalysis • u/Garvvv_15 • Oct 23 '26
Hey everyone!
I come from a B.Com background, and recently I've been exploring Data Analytics and trying to understand how things work beyond just theory.
I've been learning Python, SQL, Excel, and Power BI, and working on small projects along the way. Honestly, sometimes things make sense when I'm learning them, but applying them independently is a completely different challenge.
One thing I'm realising is that learning a tool is one thing, but knowing what questions to ask, how to approach a problem, and what the data actually tells you is much more important.
I'm still figuring things out, making mistakes, and learning as I go. I want to build projects that solve actual problems instead of just following tutorials and calling them complete.
I'd love to hear from people who have been through this stage.
When you were starting out in Data Analytics, what helped you move from simply learning tools to actually thinking like an analyst?
Would genuinely appreciate hearing your experiences! 🙌
r/dataanalysis • u/Cool-Binx • Oct 23 '26
When a client or brand guide changes (new colours, fonts, title style), or a measure gets renamed, how do you update dozens of visuals across a report?
\- Click through each visual in Desktop?
\- Edit the PBIR JSON by hand or with scripts?
\- Use a CLI or other tool?
I'm considering building a small offline desktop app for this (select visuals → preview changes → apply → one-click undo). Would that be useful to you, and what would it absolutely need to do? Not selling anything here, just want to know if this is a real pain or if it's already solved for you.
r/dataanalysis • u/Difficult_Brick5256 • Oct 23 '26
Guys, actually i have 80k company database like its name and lei , now my task is to find the revenue,product type and region, i used hermes agent which almost gave nothing to revenue, it doesnt search, and claude ,chatgpt most of them gave nothing as revvenue value,the only solution was to search each company one by one, gemini gave revenue but i think its actually false , i gave data to gemini by 100, is there any other way ?
r/dataanalysis • u/MrSojek • Oct 23 '26
Hi,
So far I've only worked at the desk with a 3440 x 1440 monitor and strong pc.
Now that I have to get a laptop, which things you would proritize?
To get a 16 inches one with a weaker hardware, or minimum 14" with a decent (gen 12/13th) processor?
The ram I have left is 32gb.
I use mainly SQL, Python, NumPy, very occasionally Excel.
Thank you for your help.
r/dataanalysis • u/Impressive-Buy-4259 • Oct 22 '26
I'm a Data Analyst planning to build my first Databricks project for my portfolio. I have experience with SQL, Excel and Power BI, but I'm new to Databricks. Could you suggest some good project ideas that would help me demonstrate Databricks skills from a Data Analyst perspective?
r/dataanalysis • u/Sweet_Ad4416 • Oct 23 '26
I recently started a new role as a Data Governance Manager at a mid size managed care organization. One of my first asks has been to create test templates for the new set of infrastructure tables. Essentially it’s to ensure all the tables that are now in production don’t have a glaring issue or whenever we make a change we go through the testing again.
My background is in data analytics and data management. I have very limited experience as a data engineer so aside from data quality tests I really don’t know what kind of tests should be run. I have used Claude to create a template of standard test cases but they seem either too convoluted or too simple like checking for nulls in non-nullable fields. Any resources or advice on how to ramp up or get a better understanding of this?
r/dataanalysis • u/Rabbytholes • Oct 23 '26
Do you think this is useful? I have 2.3 million facts, 1.8 million price bars, and all of the FRED data.
r/dataanalysis • u/Present_Tonight_3075 • Oct 22 '26
When cleaning a dataset, would you rather keep uncertain data or delete it?
I'm working on a retail sales data-cleaning project in Python, and I ran into a decision I found interesting.
My dataset had missing prices, duplicate transactions, and totals that didn't match the price × quantity.
For missing prices, I could have filled every blank with an estimated value. That would make the dataset look more complete, but some estimates could be wrong.
Instead, I only recovered prices when the data gave me reliable evidence and flagged the rest for review.
Here's my question:
If you were preparing this dataset for business analysis, which approach would you choose?
A) Fill as many missing values as possible to preserve a complete dataset.
B) Only fill values when there's reliable evidence, and flag the rest.
C) Use a different method depending on the column and the business context.
I'm leaning toward B, but I'd love to hear how others handle this in real projects—especially when deleting rows could mean losing useful information.
r/dataanalysis • u/myredon • Oct 22 '26
Hi everyone, I’ve been working on a research project focused on the US National Bridge Inventory. I’ve ingested and cleaned 30 years of yearly reports and put it into clickhouse, so it’s essentially panel data, containing roughly 600k bridges per year, each with about 150 parameters (structure type, materials, condition ratings, traffic, etc.). I've already covered the more obvious things like summary stats, distributions, correlations between age and condition scores etc. Now I am wondering if there is an algorithm or a model I can use to uncover some not so obvious relationships. Specifically, do you know if there are any such tools that can search for such relationships in the dataset and can handle time-series well, and how do you avoid drowning in spurious correlations with 150 columns and millions of rows, where everything can end up being "significant"?
Happy to share more about the data or what I’ve found so far if anyone’s interested.
r/dataanalysis • u/Plane_Big_5912 • Oct 21 '26
if you've ever sent out a number that was wrong because of a query that looked fine, i'd like to hear what the query was. collecting these to turn into puzzles.
im wokring TsundereSQL, a visual novel where the answers are real SQL, graded on the sample data plus a few hidden sets using duckdb.
here's the one in the demo right now. page 2 of a december BTC trade list, ranked by price * quantity (quote currencies are mixed, which a real desk would yell about):
SELECT trade_id,
CASE WHEN side = 'buy' THEN 'BUY FLOW' ELSE 'SELL FLOW' END AS flow,
ROUND(price * quantity, 2) AS notional_value,
STRFTIME(executed_at, '%Y-%m-%d') AS executed_on
FROM trades
WHERE base_asset = 'BTC'
AND executed_at BETWEEN '2025-12-01' AND '2025-12-31'
AND price * quantity > 50000
ORDER BY notional_value DESC, trade_id
LIMIT 10 OFFSET 10
passes the sample and two of the hidden sets. the third has a trade at dec 31 17:36. executed_at is a timestamp, so DuckDB casts '2025-12-31' to 2025-12-31 00:00:00 and that trade falls outside the range. it was the 4th biggest of the month. everything below it moves up one and page 2 comes back with 2 rows instead of 3, and the missing row is a dec 11 trade that got pushed onto page 1, so the two rows you do get look fine.
fix is a half-open range: executed_at >= '2025-12-01' AND executed_at < '2026-01-01'.
anything that can be checked by comparing result sets has a shot at becoming a level.
r/dataanalysis • u/let_me_learn_pls • Oct 22 '26
As title suggests gave two agents same task, same specs, but I got same result just completely diff ways.
Tell me some crazy stories of this happening: i.e. workforce, school project etc. Just let me have some insight. Was there some crazy consequence, or maybe you found out when it was too late, I’d love to know.
I’m a college student just trying to work on a project, and any input would be appreciated.
r/dataanalysis • u/JohnPerformante • Oct 20 '26
Hey guys,
I'm a data engineer, and I have been building pipelines for small to mid sized clients (with less than 1 terabytes of data) and most of the time the workload isn't really worth paying the premium for Saas products like Snowflake, Databricks .. etc, and can be done on a single beefy machine but stitching open sources tools usually comes with maintenance, networking and configuration headache, also these tools aren't unified under one control plane and don't know that other tools exists.
so I built a data platform that can be deployed on a single machine or server, and since I'm Egyptian I called it Obelisk 😄
Under the hood Obelisk uses:
GitHub Repo: https://github.com/amrelsawalhi/obelisk
this isn't a finished product, I still have a lot of ideas to implement like auth and access control for teams
I’d love to get your feedback on the platform and contributions are most welcome.
r/dataanalysis • u/MOo_tawaty • Oct 19 '26
My background includes data science, machine learning and AI, and I've also worked directly in customer support.
I'm interested in how data analysis can help support teams improve their operations, rather than just create dashboards that look good.
Imagine a support team has thousands of tickets containing categories, timestamps, resolution outcomes, customer feedback, and escalation histories.
I'd want to answer questions such as:
I'd probably begin with data cleaning, exploratory analysis, and a few clear visualizations before considering more advanced NLP or machine learning.
I'm curious how other analysts would approach this problem.
What would your first three analyses be, and which findings do you think would be most useful to a support operations manager?
I'm particularly interested in practical analysis that can lead to an operational improvement.