def struct_meta_conf_matrix(data: pd.DataFrame):
"""
Plots confusion matrices (crosstabs) showing the relationships
between taxonomy structures and metadata.
code
1. practice and belief structures (10 columns) vs gender
2. practice and belief structures vs country of birth (Top 15)
3. practice and belief structures vs interview country (Top 15)
:param data: DataFrame with columns ['practice_struct', 'belief_struct',
'gender', 'country_of_birth', 'interview_country']
:return: None (displays plots)
"""
print("📊 Generating structure vs. metadata crosstab heatmaps...")
gender_df = data[['practice_struct', 'belief_struct', 'gender']]
country_birth_df = data[['practice_struct', 'belief_struct', 'country_of_birth']]
interview_country_df = data[['practice_struct', 'belief_struct', 'interview_country']]
# for each metadata feature, plot confusion matrix
for df, meta_col in [(gender_df, 'gender'),
(country_birth_df, 'country_of_birth'),
(interview_country_df, 'interview_country')]:
# IMPLEMENTATION
Assistant
User
There's a bug! In each plot, practice and belief are identical
Assistant
Nice — here's a robust, ready-to-drop-in implementation of struct_meta_conf_matrix() that handles several common shapes for practice_struct / belief_struct (one-hot columns, dicts, list-of-tags, or single categorical labels), reduces long country lists to top-15, and plots tidy heatmaps (practice + belief stacked) for each metadata column.
Copy this into your script (I kept the original docstring and prints); it only requires pandas, matplotlib and seaborn.
pythonCopy codeimport pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def struct_meta_conf_matrix(data: pd.DataFrame):
"""
Plots confusion matrices (crosstabs) showing the relationships
between taxonomy structures and metadata.
code
1. practice and belief structures (10 columns) vs gender
2. practice and belief structures vs country of birth (Top 15)
3. practice and belief structures vs interview country (Top 15)
:param data: DataFrame with columns ['practice_struct', 'belief_struct',
'gender', 'country_of_birth', 'interview_country']
:return: None (displays plots)
"""
print("📊 Generating structure vs. metadata crosstab heatmaps...")
def get_struct_matrix(df: pd.DataFrame, col: str) -> pd.DataFrame:
"""
Return a DataFrame (index aligned to df) where each column is a structure/category
and values are numeric (0/1 or counts). Handles:
- existing one-hot columns named like "practice_struct_<cat>"
- the column itself being dicts -> json_normalize
- the column being a list of tags -> explode + get_dummies
- the column being a scalar categorical -> get_dummies
If nothing found, returns empty DataFrame with same index.
"""
# 1. explicit expanded columns in df (prefix patterns)
candidates = [c for c in df.columns if c.startswith(col + '_') or c.startswith(col + '__') or c.startswith(col + ' ')]
if candidates:
return df[candidates].fillna(0).astype(float)
# 2. column exists and contains structured data
if col in df.columns:
series = df[col].fillna(pd.NA)
nonnull = series.dropna()
if nonnull.empty:
return pd.DataFrame(index=df.index)
sample = nonnull.iloc[0]
# dict-like (json)
if isinstance(sample, dict):
mat = pd.json_normalize(series.apply(lambda x: x if isinstance(x, dict) else {})).fillna(0)
mat.index = df.index
mat.columns = [f"{col}__{c}" for c in mat.columns]
return mat.apply(pd.to_numeric, errors='coerce').fillna(0)
# list-like (multi-label)
if isinstance(sample, (list, tuple, set)):
exploded = series.explode().dropna()
if exploded.empty:
return pd.DataFrame(index=df.index)
dummies = pd.get_dummies(exploded)
dummies = dummies.groupby(level=0).max().reindex(df.index, fill_value=0)
dummies.columns = [f"{col}__{c}" for c in dummies.columns]
return dummies.astype(float)
# scalar categorical -> one-hot
# numeric (0/1) treat as single column
if pd.api.types.is_numeric_dtype(series):
return series.to_frame().astype(float)
dummies = pd.get_dummies(series.fillna("Unknown"), prefix=col)
return dummies.astype(float)
# nothing found
return pd.DataFrame(index=df.index)
# Extract structure matrices for practice and belief
practice_mat = get_struct_matrix(data, 'practice_struct')
belief_mat = get_struct_matrix(data, 'belief_struct')
if practice_mat.empty and belief_mat.empty:
print("⚠️ No structure data found for 'practice_struct' or 'belief_struct'. Nothing to plot.")
return
# Prepare metadata frames
meta_cols = [
('gender', None),
('country_of_birth', 15),
('interview_country', 15),
]
for meta_col, top_n in meta_cols:
if meta_col not in data.columns:
print(f"⚠️ Metadata column '{meta_col}' not in dataframe — skipping.")
continue
# reduce categories if requested (Top N)
meta_series = data[meta_col].fillna('Unknown').astype(str)
if top_n is not None:
top = meta_series.value_counts().nlargest(top_n).index.tolist()
meta_filtered = meta_series.where(meta_series.isin(top), other='Other')
else:
meta_filtered = meta_series
# Build counts matrix function: rows = structure categories, cols = meta categories
def counts_matrix(struct_mat: pd.DataFrame) -> pd.DataFrame:
if struct_mat.empty:
return pd.DataFrame()
# group-by meta and sum each structure column; result: index = meta categories, columns = struct cols
grouped = struct_mat.groupby(meta_filtered).sum()
# transpose so rows = struct cols, columns = meta categories
mat = grouped.T
# ensure consistent ordering and fill zeros
mat = mat.fillna(0).astype(int)
return mat
practice_counts = counts_matrix(practice_mat)
belief_counts = counts_matrix(belief_mat)
# Plotting: stack practice and belief vertically (if present)
n_subplots = 0
if not practice_counts.empty:
n_subplots += 1
if not belief_counts.empty:
n_subplots += 1
if n_subplots == 0:
print(f"⚠️ No structure counts for metadata '{meta_col}' — skipping.")
continue
# Figure sizing: base width depends on number of meta categories
n_meta_cols = len(practice_counts.columns) if not practice_counts.empty else len(belief_counts.columns)
fig_h = 4 * n_subplots
fig_w = max(8, n_meta_cols * 0.5 + 2)
fig, axes = plt.subplots(n_subplots, 1, figsize=(fig_w, fig_h))
if n_subplots == 1:
axes = [axes]
ax_idx = 0
for name, counts in (("Practice structures", practice_counts), ("Belief structures", belief_counts)):
if counts.empty:
continue
# normalize rows to show distribution across metadata categories for each structure
row_sums = counts.sum(axis=1).replace(0, 1) # avoid div by zero
prop = counts.div(row_sums, axis=0)
ax = axes[ax_idx]
sns.heatmap(prop, ax=ax, annot=counts, fmt='d', cbar=True,
linewidths=.5, linecolor='gray', annot_kws={"fontsize":8})
ax.set_title(f"{name} — vs. {meta_col} (rows: structures, cols: meta categories)\n(heat = proportion across metadata, annotation = raw counts)")
ax.set_xlabel(meta_col)
ax.set_ylabel("Structure category")
# nicer ticks
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right', fontsize=9)
ax.set_yticklabels(ax.get_yticklabels(), rotation=0, fontsize=9)
ax_idx += 1
plt.tight_layout()
plt.show()
print("✅ Done.")
Notes & tips
The function tries multiple heuristics so it should work whether your practice_struct / belief_struct are stored as one-hot columns, dicts, lists, or single categorical labels.
Heatmap color shows the row-normalized proportion (so you can compare how each structure is distributed across metadata categories). The numeric annotations are the raw counts.
If you prefer absolute counts as the heatmap instead of proportions, replace prop = counts.div(row_sums, axis=0) with prop = counts (and adjust the fmt/annot if you want different formatting).
If your country names are noisy, consider pre-cleaning (e.g., merging synonyms) before calling this function.
If you want, I can:
Change the normalization (column-wise vs row-wise).
Save the figures automatically to files.
Return the raw crosstab DataFrames for downstream use. Which would you like next?
Nice catch — that definitely shouldn't happen. Most likely causes are (in order of probability):
get_struct_matrix() accidentally picked the same set of one-hot columns for both practice_struct and belief_struct (e.g., because column name matching was too loose and matched both), so the two matrices are identical before plotting.
The source dataframe actually contains the same values in practice_struct and belief_struct (less likely but quick to check).
Some later step re-used the same object for both variables (rare given the code you posted).
Below are two short diagnostic checks you can run (fast), and then a small, safe fix for get_struct_matrix() that solves the common matching bug by using exact prefix matching with a regex. Paste & run the diagnostics first so you can see which problem you have; if the diagnostics show the matrices are identical, use the fixed function.
Quick diagnostics (paste into your session)
pythonCopy code# 1) quick look at raw columns / values
print("Columns containing 'practice' or 'belief':")
print([c for c in data.columns if 'practice' in c or 'belief' in c])
print("\nSample of the two raw columns:")
print(data[['practice_struct','belief_struct']].head(10))
2) reproduce the two structure matrices with your current function and compare
def counts(mat, meta_col):
meta = data[meta_col].fillna('Unknown').astype(str)
return mat.groupby(meta).sum().T.fillna(0).astype(int)
print("Practice vs Belief counts equal (gender)?",
counts(practice_mat, 'gender').equals(counts(belief_mat, 'gender')))
If practice_mat.equals(belief_mat) prints True, then the bug is in how get_struct_matrix() finds/expands columns (very likely). If the raw columns preview above already look identical, the problem is earlier in your pipeline.
Safe fix — tighter prefix matching
Replace the candidate-detection line in get_struct_matrix() with this regex-based logic so it only collects columns that start exactly with the column name + underscore (e.g. practice_struct_...) and not columns that merely contain the word anywhere:
pythonCopy codeimport re
def get_struct_matrix(df: pd.DataFrame, col: str) -> pd.DataFrame:
# look for explicit one-hot columns that start exactly with 'col_'
pattern = re.compile(rf"^{re.escape(col)}_")
candidates = [c for c in df.columns if pattern.match(c)]
if candidates:
return df[candidates].fillna(0).astype(float)
code
# ...then the rest of your current logic follows unchanged...
Why this helps: earlier code used fragile startswith checks like col + '' or col + '__' or col + ' ' which can accidentally match other columns if naming is inconsistent. The regex ^practice_struct will only match columns that truly begin with that prefix.
Extra guard & helpful assertion (add to your function)
Add a runtime check right after you build practice_mat and belief_mat:
pythonCopy codeif not practice_mat.empty and not belief_mat.empty:
if practice_mat.equals(belief_mat):
print("⚠️ Warning: practice_mat and belief_mat are identical — inspect raw columns above.")
# optionally: show the first few differing rows (should be none)
Summary / next step
Run the diagnostics above.
If they show identical matrices, apply the regex fix for candidate detection and re-run.
If diagnostics show the raw practice_struct and belief_struct columns already identical, fix upstream (that’s where the duplication happened).
If you paste the diagnostic output here (the few prints from the diagnostics), I’ll point exactly what went wrong and give the precise patch for your data shape. Want me to produce a full patched copy of your original struct_meta_conf_matrix() with the regex fix and the assertion inserted?