CoolFace
Apppublic

Ezhil24/World-population-FastAPI

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
population_pandas.py55 linesDownload Raw Back to service
1import pandas as pd2# from backend.population_pandas import get_continents, get_continent_data3from logger import logger4 5import os6 7# file_path = os.path.join(os.path.dirname(__file__), "../../data/world_population.csv")8file_path = os.path.join(os.path.dirname(__file__), "../data/world_population.csv")9# file_path = os.path.abspath(file_path)  # Convert to absolute path10 11file_path = os.path.abspath(file_path)  # Convert to absolute path12try:13    df = pd.read_csv(file_path)14    logger.info(f"CSV file loaded successfully from: {file_path}")15except Exception as e:16    logger.error(f"Error loading CSV file from {file_path}: {e}")17    df = None  # Prevent NameError if file loading fails18 19if df is not None:20    # Perform the aggregations only if df is successfully loaded21    continent_stats = df.groupby("Continent").agg(22        Total_Countries=('Country', 'count'),23        Total_Population=('Population', 'sum'),24        Average_Population=('Population', 'mean'),25        Total_Area=('Area', 'sum'),26        max_population=('Population', 'max'),27        min_population=('Population', 'min'),28        Country_Max_Population=('Population', lambda x: df.loc[x.idxmax(), 'Country']),29        Country_Min_Population=('Population', lambda x: df.loc[x.idxmin(), 'Country'])30    ).reset_index()31     # Compute Population Density32    continent_stats["Population_Density"] = (33        continent_stats["Total_Population"] / continent_stats["Total_Area"]34    )35    36    logger.info("Data processing completed.")37 38def get_continents():39    """Returns a list of all continents."""40    logger.info("Fetching all continents.")41    return continent_stats["Continent"].tolist()42 43def get_continent_data(continent):44    """Returns statistics for a specific continent."""45    logger.info(f"Fetching data for continent: {continent}")46    result = continent_stats[continent_stats["Continent"] == continent].squeeze()47 48    if result.empty:49        logger.warning(f"No data found for continent: {continent}")50        return {}51 52    return result.to_dict()53 54 55