Below is a drop‑in, self‑contained implementation of everything you asked for:
bar_plot_topic_per_gender(...)
compute_weighted_avg_topic_prob(...)
Percent conversion of segment counts
Option to plot topics in their natural numeric order (1–18)
pythonCopyEditimport re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
-----------------------------
Plotting helpers
-----------------------------
def _id_to_name_mapper(topic_names):
"""
topic_names: list-like, where index 0 corresponds to topic_id == 1, etc.
Returns a function that maps numeric topic_id -> readable topic name.
"""
def mapper(tid):
# topic ids are assumed to start at 1
if np.isnan(tid):
return np.nan
idx = int(tid) - 1
if 0 <= idx < len(topic_names):
return f"{tid}. {topic_names[idx]}"
return str(int(tid))
return mapper
def bar_plot_topic_per_gender(df,
topic_names,
x_col='top_topic_id',
col='count',
title='Segments per Topic',
y_title='Count',
natural_order=True,
kind='grouped', # 'grouped' or 'stacked'
figsize=(12, 6),
legend_title='Gender'):
"""
Draws a (grouped/stacked) bar plot by topic and gender.
Parameters
----------
df : DataFrame -> must contain columns [x_col, 'gender', col]
topic_names : list[str] -> human-readable topic names ordered by topic id (1-based)
x_col : str
col : str -> y-axis column (e.g., 'count', 'pct', 'total_weight', etc.)
natural_order : bool
kind : 'grouped' or 'stacked'
"""
if {'gender', x_col, col} - set(df.columns):
missing = {'gender', x_col, col} - set(df.columns)
raise ValueError(f"DataFrame is missing columns: {missing}")
mapper = _id_to_name_mapper(topic_names)
plot_df = df.copy()
plot_df['topic_name'] = plot_df[x_col].map(mapper)
# Pivot for plotting
pvt = plot_df.pivot_table(index=['topic_name', x_col],
columns='gender',
values=col,
aggfunc='sum',
fill_value=0)
# Order topics by their numeric id, unless told otherwise
if natural_order:
pvt = pvt.sort_index(level=1) # sort by x_col (numeric)
else:
pvt = pvt.sort_index(level=0) # sort by topic_name
# Now drop the numeric level for cleaner plotting
pvt.index = pvt.index.get_level_values(0)
ax = pvt.plot(kind='bar',
stacked=(kind == 'stacked'),
figsize=figsize)
ax.set_title(title)
ax.set_ylabel(y_title)
ax.set_xlabel('Topic')
ax.legend(title=legend_title)
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
-----------------------------
Weights computation
-----------------------------
def compute_weighted_avg_topic_prob(segments,
id_regex=r'^top\d+_topic_id′,weightregextemplate=r|^{prefix}_prob$',
topic_col_name='topic_id'):
"""
Compute (1) total_weight per topic and (2) normalized_weight = total_weight / sum(total_weight).
This function **auto-detects** columns like:
top1_topic_id, top2_topic_id, top3_topic_id
and their matching weights:
top1_weight (or top1_prob), top2_weight (or top2_prob), top3_weight (or top3_prob)
If your dataframe is already in long format with ['topic_id', 'weight'], see
`compute_weighted_avg_topic_prob_from_long` below.
Returns
-------
weight_df : pd.DataFrame with columns:
topic_id, total_weight, normalized_weight
"""
id_cols = [c for c in segments.columns if re.match(id_regex, c)]
if not id_cols:
raise ValueError("Could not find any topic id columns with the given regex.")
long_frames = []
for id_col in id_cols:
prefix = id_col.rsplit('_', 1)[0] # e.g. 'top1_topic'
# Build a regex that searches for either {prefix}_weight or {prefix}_prob
weight_regex = weight_regex_template.format(prefix=re.escape(prefix))
weight_col = next((c for c in segments.columns if re.match(weight_regex, c)), None)
if weight_col is None:
raise ValueError(f"Could not find matching weight column for {id_col} "
f"(expected something like '{prefix}_weight' or '{prefix}_prob').")
tmp = segments[[id_col, weight_col]].rename(columns={id_col: topic_col_name,
weight_col: 'weight'})
long_frames.append(tmp)
long_df = pd.concat(long_frames, axis=0, ignore_index=True)
long_df = long_df.dropna(subset=[topic_col_name, 'weight'])
# Optional: ensure integers
long_df[topic_col_name] = long_df[topic_col_name].astype(int)
weight_df = (long_df
.groupby(topic_col_name, as_index=False)['weight']
.sum()
.rename(columns={'weight': 'total_weight'}))
total = weight_df['total_weight'].sum()
weight_df['normalized_weight'] = weight_df['total_weight'] / total if total > 0 else 0.0
return weight_df
def compute_weighted_avg_topic_prob_from_long(long_df,
topic_col='topic_id',
weight_col='weight'):
"""
Same as the function above, but expects your data already in long form with
[topic_col, weight_col].
"""
if {topic_col, weight_col} - set(long_df.columns):
raise ValueError(f"Missing columns { {topic_col, weight_col} - set(long_df.columns) }")
out = (long_df
.groupby(topic_col, as_index=False)[weight_col]
.sum()
.rename(columns={weight_col: 'total_weight'}))
total = out['total_weight'].sum()
out['normalized_weight'] = out['total_weight'] / total if total > 0 else 0.0
return out
-----------------------------
Example usage with your snippet
-----------------------------
1) Count the number of segments per topic and gender
topic_gender_counts = segments.groupby(['top_topic_id', 'gender']).size().reset_index(name='count')
1a) Convert counts to percentages over ALL segments (not per gender)
total_segments = len(segments)
topic_gender_counts['pct'] = (topic_gender_counts['count'] / total_segments) * 100
Plot counts
bar_plot_topic_per_gender(topic_gender_counts,
list(topics['Topic']),
x_col='top_topic_id',
col='count',
title='Segments per Topic (Counts)',
y_title='Count of segments',
natural_order=True)
Plot percentages
bar_plot_topic_per_gender(topic_gender_counts,
list(topics['Topic']),
x_col='top_topic_id',
col='pct',
title='Segments per Topic (Percent of all segments)',
y_title='Percent of segments (%)',
natural_order=True)
2) Weighted sums
weight_df = compute_weighted_avg_topic_prob(segments)
bar_plot_topic_per_gender(weight_df.merge(segments[['gender', 'top_topic_id']],
left_on='topic_id', right_on='top_topic_id',
how='left')
.groupby(['topic_id', 'gender'], as_index=False)
.agg(total_weight=('total_weight', 'sum')),
list(topics['Topic']),
x_col='topic_id',
col='total_weight',
title='Weighted Sum per Topic',
y_title='Sum of top-3-topic id weights')
bar_plot_topic_per_gender(weight_df,
list(topics['Topic']),
x_col='topic_id',
col='normalized_weight',
title='Normalized Weighted Sum per Topic',
y_title='Normalized weight',
# No gender column in weight_df alone; this will raise unless you add one.
# If you want a single bar per topic (no gender split), you can make a thin wrapper
# or pass a fake gender = 'all'. Example below:
)
---- If you want the "normalized" plot WITHOUT gender split ----
def bar_plot_topic(df, topic_names, x_col='topic_id', y_col='value',
title='', y_title='Value', natural_order=True, figsize=(12,6)):
mapper = _id_to_name_mapper(topic_names)
plot_df = df.copy()
plot_df['topic_name'] = plot_df[x_col].map(mapper)
if natural_order:
plot_df = plot_df.sort_values(by=x_col)
else:
plot_df = plot_df.sort_values(by='topic_name')
plt.figure(figsize=figsize)
plt.bar(plot_df['topic_name'], plot_df[y_col])
plt.xticks(rotation=45, ha='right')
plt.title(title)
plt.ylabel(y_title)
plt.xlabel('Topic')
plt.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
Example usage:
bar_plot_topic(weight_df.rename(columns={'normalized_weight': 'value'}),
list(topics['Topic']),
x_col='topic_id',
y_col='value',
title='Normalized Weighted Sum per Topic',
y_title='Normalized weight',
natural_order=True)
Notes & options
Natural order (1–18): natural_order=True keeps topics sorted by their numeric ID. Set it to False if you’d rather sort alphabetically by name or by value before plotting.
Percentages: I converted counts to a global percentage (count / total_segments * 100).
If you prefer within-gender percentages (each gender sums to 100%), do:
pythonCopyEdittopic_gender_counts['pct_within_gender'] = (
topic_gender_counts['count'] /
topic_gender_counts.groupby('gender')['count'].transform('sum') * 100
)
Weights function: The implementation auto-detects columns of the form:
top1_topic_id, top2_topic_id, top3_topic_id
and either top1_weight/top1_prob, etc.
Adjust the regexes if your column names differ.
No gender in weight_df: If you really want gendered weighted plots, you’ll need to propagate gender to the long format before aggregation (e.g., explode per row with gender kept, then groupby [topic_id, gender]). I showed a quick merge-based example, but depending on your schema you might want to explicitly explode first for correctness.
If you paste this into your notebook/script, it should run as-is (assuming the column names line up). Want me to adapt it precisely to your dataframe schema (show me the columns), or to output Plotly figures instead of Matplotlib?