{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sellers_x-Sellers_y: 118/136 matches (86.76%)\n",
      "Buyers_x-Buyers_y: 104/136 matches (76.47%)\n",
      "Brokers_x-Brokers_y: 100/136 matches (73.53%)\n",
      "Surgery_x-Surgery_y: 115/136 matches (84.56%)\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Load the two CSV files for comparison\n",
    "file1_df = pd.read_csv('filtered_file1.csv')\n",
    "file2_df = pd.read_csv('filtered_file2.csv')\n",
    "\n",
    "# Define the column pairs to compare\n",
    "columns_to_compare = [\n",
    "    (\"Sellers\", \"Sellers\"),\n",
    "    (\"Buyers\", \"Buyers\"),\n",
    "    (\"Brokers\", \"Brokers\"),\n",
    "    (\"Surgery\", \"Surgery\")\n",
    "]\n",
    "\n",
    "columns_to_compare2 = [\n",
    "    (\"Sellers_x\", \"Sellers_y\"),\n",
    "    (\"Buyers_x\", \"Buyers_y\"),\n",
    "    (\"Brokers_x\", \"Brokers_y\"),\n",
    "    (\"Surgery_x\", \"Surgery_y\")\n",
    "]\n",
    "\n",
    "# Mapping of common abbreviations to full country names\n",
    "country_mapping = {\n",
    "    'UK': 'United Kingdom',\n",
    "    'US': 'United States',\n",
    "    'England': 'United Kingdom',\n",
    "    'USA': 'United States',\n",
    "}\n",
    "\n",
    "# Function to replace abbreviations with full country names\n",
    "def replace_abbreviations(cell):\n",
    "    if pd.isna(cell):\n",
    "        return cell\n",
    "    for abbr, full_name in country_mapping.items():\n",
    "        cell = str(cell).replace(abbr, full_name)\n",
    "    return cell\n",
    "\n",
    "# Apply the function to relevant columns in both dataframes\n",
    "for col1, _ in columns_to_compare:\n",
    "    file1_df[col1] = file1_df[col1].apply(replace_abbreviations)\n",
    "for _, col2 in columns_to_compare:\n",
    "    file2_df[col2] = file2_df[col2].apply(replace_abbreviations)\n",
    "\n",
    "# Function to compare two cells\n",
    "def cell_comparison(cell1, cell2):\n",
    "    set1 = set(str(cell1).split(', '))\n",
    "    set2 = set(str(cell2).split(', '))\n",
    "    return not set1.isdisjoint(set2)\n",
    "\n",
    "# Merge the two dataframes on ID\n",
    "merged_df = pd.merge(file1_df, file2_df, on=\"ID\")\n",
    "\n",
    "# Print match counts for each column pair\n",
    "for col1, col2 in columns_to_compare2:\n",
    "    comparison = merged_df.apply(lambda row: cell_comparison(row[col1], row[col2]), axis=1)\n",
    "    match_count = comparison.sum()\n",
    "    total_count = len(comparison)\n",
    "    print(f\"{col1}-{col2}: {match_count}/{total_count} matches ({(match_count / total_count) * 100:.2f}%)\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sellers:\n",
      "  Precision (%): 65.6\n",
      "  Recall (%): 67.83\n",
      "  F1 Score (%): 62.33\n",
      "  Accuracy (%): 86.76\n",
      "\n",
      "Buyers:\n",
      "  Precision (%): 60.72\n",
      "  Recall (%): 65.72\n",
      "  F1 Score (%): 59.73\n",
      "  Accuracy (%): 76.47\n",
      "\n",
      "Brokers:\n",
      "  Precision (%): 61.13\n",
      "  Recall (%): 62.21\n",
      "  F1 Score (%): 58.47\n",
      "  Accuracy (%): 73.53\n",
      "\n",
      "Surgery:\n",
      "  Precision (%): 73.77\n",
      "  Recall (%): 76.27\n",
      "  F1 Score (%): 72.6\n",
      "  Accuracy (%): 84.56\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Load the uploaded CSV files\n",
    "file1_path = 'filtered_file1.csv'\n",
    "file2_path = 'filtered_file2.csv'\n",
    "\n",
    "file1_df = pd.read_csv(file1_path)\n",
    "file2_df = pd.read_csv(file2_path)\n",
    "\n",
    "# Define the columns to compare\n",
    "columns_to_compare = [\n",
    "    (\"Sellers\", \"Sellers\"),\n",
    "    (\"Buyers\", \"Buyers\"),\n",
    "    (\"Brokers\", \"Brokers\"),\n",
    "    (\"Surgery\", \"Surgery\")\n",
    "]\n",
    "\n",
    "# Mapping of common abbreviations to full country names\n",
    "country_mapping = {\n",
    "    'UK': 'United Kingdom',\n",
    "    'US': 'United States',\n",
    "    'England': 'United Kingdom',\n",
    "    'USA': 'United States',\n",
    "}\n",
    "\n",
    "# Function to replace abbreviations with full country names\n",
    "def replace_abbreviations(cell):\n",
    "    if pd.isna(cell):\n",
    "        return cell\n",
    "    for abbr, full_name in country_mapping.items():\n",
    "        cell = str(cell).replace(abbr, full_name)\n",
    "    return cell\n",
    "\n",
    "# Apply the function to relevant columns in both dataframes\n",
    "for col1, _ in columns_to_compare:\n",
    "    file1_df[col1] = file1_df[col1].apply(replace_abbreviations)\n",
    "    file2_df[col1] = file2_df[col1].apply(replace_abbreviations)\n",
    "\n",
    "# Merge the two dataframes on ID\n",
    "merged_df = pd.merge(file1_df, file2_df, on=\"ID\", suffixes=('_x', '_y'))\n",
    "\n",
    "# Function to calculate precision and recall\n",
    "def precision_recall(true_str, pred_str):\n",
    "    if pd.isna(true_str) and pd.isna(pred_str):\n",
    "        return 1.0, 1.0  # Both empty\n",
    "    if pd.isna(true_str):\n",
    "        return 0.0, 1.0  # Nothing in ground truth, all prediction is FP\n",
    "    if pd.isna(pred_str):\n",
    "        return 1.0, 0.0  # All ground truth missed\n",
    "\n",
    "    true_set = set(map(str.strip, str(true_str).split(',') if true_str else []))\n",
    "    pred_set = set(map(str.strip, str(pred_str).split(',') if pred_str else []))\n",
    "    tp = len(true_set & pred_set)\n",
    "    fp = len(pred_set - true_set)\n",
    "    fn = len(true_set - pred_set)\n",
    "    \n",
    "    precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0\n",
    "    recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0\n",
    "    return precision, recall\n",
    "\n",
    "# Calculate average precision and recall per column\n",
    "results = {}\n",
    "for col in ['Sellers', 'Buyers', 'Brokers', 'Surgery']:\n",
    "    metrics = merged_df.apply(lambda row: precision_recall(row[f\"{col}_x\"], row[f\"{col}_y\"]), axis=1)\n",
    "    precisions, recalls = zip(*metrics)\n",
    "\n",
    "    avg_precision = sum(precisions) / len(precisions)\n",
    "    avg_recall = sum(recalls) / len(recalls)\n",
    "\n",
    "    # F1 Score: harmonic mean of precision and recall\n",
    "    f1_scores = [2 * p * r / (p + r) if (p + r) > 0 else 0.0 for p, r in zip(precisions, recalls)]\n",
    "    avg_f1 = sum(f1_scores) / len(f1_scores)\n",
    "\n",
    "    # Accuracy = proportion of non-zero matches (partial or full)\n",
    "    match_count = sum((1 if (p > 0 and r > 0) else 0) for p, r in zip(precisions, recalls))\n",
    "    accuracy = match_count / len(merged_df)\n",
    "\n",
    "    results[col] = {\n",
    "        'Precision (%)': round(avg_precision * 100, 2),\n",
    "        'Recall (%)': round(avg_recall * 100, 2),\n",
    "        'F1 Score (%)': round(avg_f1 * 100, 2),\n",
    "        'Accuracy (%)': round(accuracy * 100, 2)\n",
    "    }\n",
    "\n",
    "# Print results\n",
    "for col, metrics in results.items():\n",
    "    print(f\"{col}:\")\n",
    "    for metric, value in metrics.items():\n",
    "        print(f\"  {metric}: {value}\")\n",
    "    print()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
