Implement the missing code below - """ import pandas as pd from argparse import…
- User
Implement the missing code below -
""" import pandas as pd from argparse import ArgumentParser from datetime import datetime
DATE = datetime.now().date()
PATH2PROJ = "/home/esther/PycharmProjects/edut710" METADATA_PATH = f"{PATH2PROJ}/data/20250110-testimonies-monday.csv" GENDER_AGE_PATH = f"{PATH2PROJ}/data/year_of_birth_gender.csv"
META_COLS = {'איפה היית ב7/10': 'location', 'עד/ה': 'name'}
def incorporate_metadata(df: pd.DataFrame, path2topics, seg_method) -> pd.DataFrame: """ Incorporate metadata into the dataframe, including: topic_id, gender, age, location and organizations. :param path2topics: :param df: DataFrame with testimonies :return: DataFrame with metadata incorporated """ topic_df = pd.read_csv(path2topics, index_col=0)[['Testimony Identifier', 'text', 'most_probable_topic']] topic_df.rename(columns={'Testimony Identifier': 'tid', 'most_probable_topic': 'topic_id'}, inplace=True) topic_df.tid = topic_df.tid.apply(lambda x: x.split(".")[-1])
# merge the topic mapping with the predictions df = pd.merge(df, topic_df, how='left', on=['tid', 'text']) # load the metadata meta_data = pd.read_csv(METADATA_PATH, index_col=0) # rename the columns to match the expected format meta_data.rename(columns=META_COLS, inplace=True) meta_data['tid'] = meta_data['Identifier'].apply(lambda x: x.split(".")[-1]) # merge the metadata with the predictions df = pd.merge(df, meta_data, how='left', on=['tid']) gender_age_df = pd.read_csv(GENDER_AGE_PATH, index_col=0) gender_age_df.rename(columns={"מגדר": "gender", "שנת לידה": "year_of_birth"}, inplace=True) gender_age_df['tid'] = gender_age_df['Testimony Identifier'].apply(lambda x: x.split(".")[-1]) df = pd.merge(df, gender_age_df, how='left', on=['tid']) # save df = df[['tid', 'tid_order', 'name', 'text', 'topic_id', 'gender', 'year_of_birth', 'location', ]] # drop any duplicate rows - according to tid and text df.drop_duplicates(subset=['tid', 'text'], inplace=True) df.to_csv(f"domestic_resilience_predictions_{seg_method}_with_metadata_{DATE}.csv") return dfdef load_predictions(path2preds): """ Load the predictions from a CSV file. :param path2preds: :return: """ df = pd.read_csv(path2preds) # filter positive predictions only df = df[df['gpt4.1_out']] # rename columns to match the expected format df.rename(columns={'gpt4.1_out': 'label'}, inplace=True) df["tid"] = df.tid_order.apply(lambda x: x.split("_")[0].split("#")[0])
# in the eq_len segmentation method, the tid_order got messed up, but the tid is still correct # so we need to fix the tid_order order_series = df.groupby('tid').cumcount() + 1 df['tid_order'] = df.tid + "_" + order_series.astype(str) # ensure the columns are in the right order return df[['tid', 'tid_order', 'text', 'label']]def organize_data(): parser = ArgumentParser(description="Analyze domestic resilience data") parser.add_argument('--predictions', type=str, required=True, help="Path to the predictions file with DR classifications") parser.add_argument('--seg_method', type=str, required=True, choices=['eq_len', 'unsupervised'], help="Segmentation method used for the data") parser.add_argument('--topic_map', type=str, required=True, help="Path to the topic mapping file") args = parser.parse_args() data = load_predictions(args.predictions) return incorporate_metadata(data, args.topic_map, args.seg_method)
- Assistant
To complete the missing implementation, we need to define the visualizations(data) function that creates:
A heatmap showing the distribution of topic_id by year_of_birth.
With the shading implying age (younger = darker).
We assume year_of_birth is numeric and topic_id is categorical.
Here’s the completed implementation with seaborn for the heatmap: pythonCopyEditimport matplotlib.pyplot as plt import seaborn as sns
def visualizations(data): """ - create visualizations for the domestic resilience data - plot a heatmap for each topic id as a function of the year_of_birth (darker means younger) :param data: :return: """ # Drop missing or invalid data plot_data = data[['topic_id', 'year_of_birth']].dropna() plot_data = plot_data[plot_data['year_of_birth'].apply(lambda x: str(x).isdigit())] plot_data['year_of_birth'] = plot_data['year_of_birth'].astype(int)
- User
I had something else in mind. For each topic, I want to visualize its distribution along the year of birth
- Assistant
Got it! You want a separate plot for each topic, showing the distribution of year of birth (i.e., how age varies within each topic). This is more like a set of histograms or KDE plots, one per topic, where x = year_of_birth, y = count/density. Here’s how you can implement that:
✅ Updated visualizations(data) function: pythonCopyEditimport matplotlib.pyplot as plt import seaborn as sns import os
def visualizations(data): """ For each topic, plot the distribution of year of birth of testimonies. This helps understand the age composition of each topic. """ # Ensure output directory exists os.makedirs("topic_birth_year_distributions", exist_ok=True)
- User
What other analysis can be done?
- Assistant
Great question. Once your data includes topic ID, year of birth, gender, location, and labels for "domestic resilience" (DR), you can run a variety of insightful analyses to explore themes, demographic patterns, and behavioral signals in the testimonies.
🧠 1. Age and Topic Correlation
Goal: See which topics are more common among younger vs. older individuals.
- User
Yes. Implement Geographic Distribution
- Assistant
Great! Here's how to implement Geographic Distribution by Topic:
✅ Goal: Create a heatmap showing how different topics are distributed across locations.
📦 Code to Add to visualizations(data): pythonCopyEditdef visualize_geographic_distribution(data): """ Creates a heatmap of topic occurrence by location. Helps reveal geographic trends in topic relevance. """
import matplotlib.pyplot as plt import seaborn as sns import os os.makedirs("geo_distributions", exist_ok=True) # Clean data geo_data = data[['topic_id', 'location']].dropna() geo_data = geo_data[geo_data['location'].str.strip() != ""] # Count occurrences location_topic_matrix = geo_data.pivot_table(index='location', columns='topic_id', aggfunc='size', fill_value=0) # Filter to show most frequent locations if too many top_locations = location_topic_matrix.sum(axis=1).sort_values(ascending=False).head(20).index filtered_matrix = location_topic_matrix.loc[top_locations] plt.figure(figsize=(12, 8)) sns.heatmap(filtered_matrix, cmap="Purples", annot=True, fmt="d", cbar_kws={'label': 'Number of Testimonies'}) plt.title("Topic Distribution by Location (Top 20 Locations)") plt.xlabel("Topic ID") plt.ylabel("Location") plt.xticks(rotation=45) plt.tight_layout() plt.savefig(f"geo_distributions/topic_by_location_heatmap_{DATE}.png") plt.show() - User
How can I reverse the legend values by x[afde:b0c5:6213:cab4:2a40:699a:dd91:d30c-1], for Hebrew encoding?
- Assistant
Great observation — when working with Hebrew text, you often want the right-to-left (RTL) display, especially in axes labels or legends. However, most plotting libraries (like matplotlib/seaborn) are left-to-right (LTR) by default. If you're asking about reversing Hebrew-encoded location names on the y-axis (locations listed top to bottom) to be more natural (e.g., in alphabetical Hebrew order from bottom to top), here’s how to do it:
✅ Reverse the y-axis (locations) in your heatmap Update this line: pythonCopyEditsns.heatmap(filtered_matrix, ...)
To this: pythonCopyEditsns.heatmap(filtered_matrix[afde:b0c5:6213:cab4:2a40:699a:dd91:d30c-1], ...) # Reverse the DataFrame rows (y-axis)
This flips the location order vertically (so Hebrew reads better, top-to-bottom in reverse of default English ordering).
🧠 Explanation:
filtered_matrix[afde:b0c5:6213:cab4:2a40:699a:dd91:d30c-1] reverses the row order.
This is especially useful when your Hebrew locations appear inverted or visually disorienting.
- User
I mean to solve this: revert the order of characters in words, like this [afde:b0c5:6213:cab4:2a40:699a:dd91:d30c-1] on the given string
- Assistant
Ah, perfect — you're referring to reversing the characters in each Hebrew string, not reversing the order of the rows or axes. This is commonly needed when rendering Hebrew text in environments that don't support right-to-left (RTL) properly, like matplotlib.
✅ How to Reverse Characters in Hebrew Strings You can reverse Hebrew words using Python slicing: [afde:b0c5:6213:cab4:2a40:699a:dd91:d30c-1] Here’s how to apply it to all location names in your DataFrame before plotting: ✨ Update this line in your function: pythonCopyEditgeo_data = data[['topic_id', 'location']].dropna()
➕ Add this right after: pythonCopyEdit# Reverse Hebrew strings to display correctly in LTR matplotlib geo_data['location'] = geo_data['location'].apply(lambda x: x[afde:b0c5:6213:cab4:2a40:699a:dd91:d30c-1])
✅ Full snippet in context: pythonCopyEditgeo_data = data[['topic_id', 'location']].dropna() geo_data = geo_data[geo_data['location'].str.strip() != ""]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.