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 DR Label by Demographics
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.