← Home

Investigating Italian Population¶

AIM: make the best of data available from ISTAT.

In particular, I want to have:

  • the number of residents each year, by age (2D table: AGE x YEAR_OF_OBSERVATION)
  • compute the delta of residents each year, by age (2D table: AGE x YEAR_OF_OBSERVATION)
  • compute the Cohort Change Ratio (CCR) each year, by age (2D table: AGE x YEAR_OF_OBSERVATION)
InĀ [1]:
import sys
from pathlib import Path
sys.path.insert(0, str(Path("../scripts").resolve()))

import time
import numpy as np
import pandas as pd
import requests
import matplotlib
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
from istat_source import istat_data, population_history
import warnings 


pio.renderers.default = 'plotly_mimetype+notebook'
warnings.filterwarnings('ignore')
requests.urllib3.disable_warnings() # avoid "InsecureRequestWarning: Unverified HTTPS request is being made to host 'sdmx.istat.it'. Adding certificate verification is strongly advised"

def get_colors(n, cmap_name="rainbow"):
    """Get colors for px colors_discrete argument, given the number of colors needed, n."""
    cmap = matplotlib.colormaps[cmap_name]
    colors = [cmap(i) for i in np.linspace(0, 1, n)]  # Generate colors
    colors_str = [f"rgba({int(color[0]*250)}, {int(color[1]*250)}, {int(color[2]*250)}, 1.0)" for color in colors]
    return colors_str

Retain the reconstructed resident population for 1952–2018 from the checked-in baseline, and refresh the current POPRES release from 2019 onward. The retained historical sex split is recovered from the saved notebook figure and its totals are verified against pop_by_age_year.csv. It is not a new historical-data download.

InĀ [2]:
# Retain 1952–2018 from the checked-in baseline; refresh the current release since 2019.
# population_history() verifies retained totals against pop_by_age_year.csv.
dfs = [population_history(), istat_data(
    resource_id="22_289_DF_DCIS_POPRES1_1",
    key={"FREQ": "A", "REF_AREA": "IT", "DATA_TYPE": "JAN", "AGE": [], "SEX": [], "MARITAL_STATUS": "99"},
)]
for frame in dfs:
    print(f"Population input: {frame.TIME_PERIOD.min()}–{frame.TIME_PERIOD.max()}, {len(frame)} rows")
Population input: 1952–2018, 20301 rows
Population input: 2019–2026, 2448 rows

Each row is a single year of age; age 100 is the open-ended group aged 100 or older. Population is measured on 1 January. Later releases take precedence at overlapping reconstruction boundaries.

InĀ [3]:
dfp_long = (
    pd.concat(dfs, ignore_index=True)
    [["TIME_PERIOD", "AGE", "SEX","value"]]
    .query("AGE!='TOTAL'")
    .replace("Y_GE100", "Y100") # Remember that 100 is 100+, converting for simplicity
    .assign(AGE= lambda x: x["AGE"].str.split("Y").str[-1].astype(int))
    .assign(YEAR= lambda x: x["TIME_PERIOD"]) # Remember, this YEAR means "at the beginning (January 1st) of the year"
    [["YEAR", "AGE", "SEX","value"]]
    .astype(int)
    .assign(SEX= lambda x: x["SEX"].map({9: "T", 1: "M", 2: "F"}))
    .drop_duplicates(["YEAR", "AGE", "SEX"], keep="last") # latest release at overlap
    .sort_values(["AGE", "YEAR", "SEX"])
    .reset_index(drop=True)
)
display(dfp_long)
YEAR AGE SEX value
0 1952 0 F 398977
1 1952 0 M 418500
2 1952 0 T 817477
3 1953 0 F 399947
4 1953 0 M 418434
... ... ... ... ...
22720 2025 100 M 3976
22721 2025 100 T 22652
22722 2026 100 F 20378
22723 2026 100 M 4332
22724 2026 100 T 24710

22725 rows Ɨ 4 columns

InĀ [4]:
fig = px.line(
    dfp_long,#.reset_index().melt(id_vars=["age"], var_name="year", value_name="population"), # convert to long format
    x="AGE", 
    y="value", 
    color="SEX",
    color_discrete_map={"T": "black", "M": "blue", "F": "red"},
    title="Total population in Italy by age (TOTAL)",
    animation_frame="YEAR",
    markers=False,
)
fig.update_layout(
    xaxis_title="Age",
    yaxis_title="Population by age group",
    yaxis_range=[0, 1e6],
    title=None,
    legend_title="Sex",
    margin=dict(l=10, r=10, t=10, b=10),
    width=780,
    height=420,
)

# Initialize the animation at the last frame (current year)
last = fig.frames[-1]
for extra in last.data[len(fig.data):]:
    fig.add_trace(extra)
for i, tr in enumerate(last.data):
    payload = tr.to_plotly_json() if hasattr(tr, "to_plotly_json") else dict(tr)
    fig.data[i].update(**payload)
if "sliders" in fig.layout and fig.layout.sliders:
    fig.layout.sliders[0].active = len(fig.frames) - 1
    
fig["layout"].pop("updatemenus") # optional, drop animation buttons
fig.write_html("../images_output/pop_by_age.html", auto_play=False)
print("Total population in Italy by age")
fig.show()
Total population in Italy by age
InĀ [5]:
# Pivot the tabel by year (of observation) vs age, and visualize it as a heatmap
dfp = (
    dfp_long
    .query("SEX=='T'") # only total population
    .pivot(index='AGE', columns='YEAR', values='value') # make an age x year table
    .rename(columns={"index": "AGE"})
)
dfp.to_csv("../data/pop_by_age_year.csv", index=True)
fig = px.imshow(
    dfp, labels=dict(x="YEAR", y="AGE", color="Population"), aspect="auto",
).update_layout(width=1000).show()