Reference¶
ssb_kostra_python package¶
ssb_kostra_python.kommunekorr module¶
- kostra_kommunekorr(year)¶
Fetches and compiles data on correspondences between municipalities and related classifications for a given year.
- The function retrieves the following:
Municipality classification (KLASS 131) and manually adds Longyearbyen.
The correspondence between municipality (KLASS 131) and KOSTRA group (KLASS 112). This request is wrapped in a try-except block to catch HTTP 404 errors and raise a descriptive ValueError.
The correspondence between municipality (KLASS 131) and county (KLASS 104).
- The retrieved data is merged into a single DataFrame containing information on:
Municipality number (komm_nr) and name (komm_navn)
County number (fylke_nr) and name (fylke_navn)
KOSTRA group number (kostra_gr) and name (kostra_gr_navn)
Validity start and end dates for both KOSTRA group and county classifications.
- Additional columns:
‘fylke_nr_eka’: county number prefixed with “EKA”.
‘fylke_nr_eka_m_tekst’: concatenation of ‘fylke_nr_eka’ and the county name.
‘landet’: a static label “EAK Landet”.
‘landet_u_oslo’: a static label “EAKUO Landet uten Oslo” (set to NaN for Oslo, municipality code “0301”).
- Parameters:
year (str) – The year (format “YYYY”) for which data should be fetched.
- Returns:
- A DataFrame with the following columns:
komm_nr: Municipality number.
komm_navn: Municipality name.
fylke_nr: County number.
fylke_navn: County name.
fylke_nr_eka: County number prefixed with “EKA”.
fylke_nr_eka_m_tekst: Combination of fylke_nr_eka and fylke_navn.
fylke_validFrom: Start date for county classification validity.
fylke_validTo: End date for county classification validity.
kostra_gr: KOSTRA group number.
kostra_gr_navn: KOSTRA group name.
kostra_validFrom: Start date for KOSTRA group validity.
kostra_validTo: End date for KOSTRA group validity.
landet: Static label for the nation.
landet_u_oslo: Static label for the nation excluding Oslo.
- Return type:
pd.DataFrame
- Raises:
ValueError – If the correspondence between municipality and KOSTRA group is not found (e.g., HTTP 404), or if duplicates are detected for municipality numbers after merging the data.
Example
>>> df = kostra_kommunekorr("2025") >>> df['verdi'] = 1000 >>> groups = [ ... ['komm_nr', 'komm_navn'], ... ['fylke_nr', 'fylke_navn'], ... ['kostra_gr', 'kostra_gr_navn'], ... ['landet_u_oslo'], ... ['landet'] ... ] >>> agg_list = [] >>> for cols in groups: ... temp = df.groupby(cols)['verdi'].sum().rename('agg_verdi') ... agg_list.append(temp) >>> df_agg = pd.DataFrame(pd.concat(agg_list))