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])
code# 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 df - 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
Valid year of birth values are between 1930 and 2010
- Assistant
Great — that makes things clearer. We'll enforce that year_of_birth values must be between 1930 and 2010, inclusive. Here's the updated visualizations() function with that validation added:
✅ Final visualizations(data) Implementation: 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 (1930–2010). Saves one histogram per topic in 'topic_birth_year_distributions/'. """ os.makedirs("topic_birth_year_distributions", exist_ok=True)
code
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.