Data Analyses of the 2026 Taiwan Local Elections
Data Analyses of the 2026 Taiwan Local Elections

Code and Data: Taiwan, 2026

Shen-yi Liao · 1 December 2026

Everything needed to reproduce every number and chart in the series from the government’s own files: which files to download, the scripts that clean them, and the analysis behind each article.

Data to download

All inputs are government files, used as published. Download each into the folder shown; nothing in them is edited by hand.

WhatPublisher and whereFolderUsed by
2026 results by polling station: 縣表3-1 (mayor or magistrate) and 3-2 (council), all 22 cities and countiesCentral Election Commission (中央選舉委員會), 2026 results siteSOURCE/votedata/2026/計票/both articles
2026 council result pages, one per district (elected marks, indigenous districts)CEC results site, fetched by cec2026_web.pySOURCE/cec_web_2026/Taiwan
Election database (選舉資料庫): elbase, elcand, elctks, elpaty and elprof files for each electionCEC, on the government open-data platform or db.cec.gov.twSOURCE/votedata/votedata/voteData/both articles
By-elections after the database’s last update, including Chiayi City’s re-held 2022 mayoral race (2022年_嘉義市長重行選舉)CEC, db.cec.gov.twSOURCE/votedata/votedata/Taiwan
Village population by single year of age, October 2018, 2022 and 2026 (opendata10710M030.csv, opendata11110M030.csv, opendata11510M030.csv): place names for matching, and age shares for the age articleMinistry of the Interior (戶政司) open data, 村里戶數、單一年齡人口SOURCE/demographicdata/cleaning
Income-tax statistics by village, tax years 2018, 2022 and 2023 (107_165-9.csv, 111_165-9.csv, 112_165-9.csv)Fiscal Information Agency (財政部財政資訊中心), 綜稅所得村里統計SOURCE/fia_income/age
Turnout by age and sex, 2022 mayoral and magistrate elections (figures 4-13 and 4-14 and table 4-9)Central Election Commission, 選舉人年齡及性別投票統計; the printed figures are transcribed into cec_turnout_age_2022.csv (listed below), so nothing needs downloading—age

Cleaning the data

Six scripts turn the government files into tidy tables in one schema, with integrity checks: valid votes equal the sum of candidates’ votes, votes cast equal valid plus invalid, and station rows add up to every town subtotal. Known problems in the source files are listed in cec_known_issues.csv and attached to the tables, not silently fixed. The Taiwan article uses these tables; the Taipei scripts predate them.

  1. demog_clean.py: the village population tables; run first, because areas.py matches place names against them.
  2. cec_clean.py: every election in the election database (a few minutes).
  3. allcounty_load.py: the 2026 polling-station tables, with general and indigenous council districts identified.
  4. cec2026_web.py: fetches the 221 council result pages once, 1 second apart, and records elected marks; re-runs read the saved copies.
  5. cec2026_clean.py: the 2026 tables in the common schema; stops with a message if step 4 has not run.
  6. cec_byelection_clean.py: by-elections, including Chiayi City’s 2022 mayoral race.

Run

pip install pandas numpy xlrd pyarrow
python3 demog_clean.py SOURCE/demographicdata CLEAN
python3 cec_clean.py SOURCE/votedata/votedata CLEAN
python3 allcounty_load.py SOURCE/votedata/2026/計票 CLEAN
python3 cec2026_web.py CLEAN SOURCE
python3 cec2026_clean.py SOURCE/votedata/2026/計票 CLEAN
python3 cec_byelection_clean.py SOURCE/votedata/votedata CLEAN

Output: CLEAN/<table>/source=<source>/part.parquet for elections, candidates, votes and turnout, read with pandas.read_parquet.

Files

demog_clean.py

"""Clean the Ministry of the Interior village population tables (opendata<ROC yyymm>M030.csv: households and
population by single year of age and sex, per village 里) into tidy tables.

usage: python3 demog_clean.py DEMOG_DIR CLEAN_DIR   (DEMOG_DIR = _data/source/demographicdata)
Outputs (CLEAN_DIR):
  demog_age.parquet   month, county, town, vil, county/town/village names, sex, age (0-99; 100 = 100 and over), population
  demog_village.csv   one row per month x village: households, population (total, male, female), voting-age (20+)
                      population, 18+ (referendum age), and shares aged 20-39, 40-64, 65+
Codes: 區域別代碼 = county (5) + town (3) + village (3). The CEC (from 2016) uses the same county and town codes, and
village code '0' + the same 3 digits, so `vil` here is written in the CEC's 4-digit form.
Checks: per village, male + female = total; the sum over ages equals each sex total.
"""
import sys, os, glob, re
import pandas as pd

SRC, OUT = sys.argv[1], sys.argv[2]
os.makedirs(OUT, exist_ok=True)
long, wide = [], []
for f in sorted(glob.glob(f'{SRC}/opendata*M030.csv')):
    x = pd.read_csv(f, dtype=str, encoding='utf-8-sig')
    x = x[x['統計年月'].str.fullmatch(r'\d+', na=False)].copy()        # drop any English header row
    ages = [c for c in x.columns if re.fullmatch(r'\d+歲(以上)?-[男女]', c)]
    num = ['戶數', '人口數', '人口數-男', '人口數-女'] + ages
    x[num] = x[num].apply(pd.to_numeric).astype('int64')
    x = x.copy()                                                     # defragment before adding columns
    code = x['區域別代碼'].str.strip()
    assert code.str.len().eq(11).all(), f
    x['county'] = code.str[:5]; x['town'] = code.str[5:8]; x['vil'] = '0' + code.str[8:11]
    x['month'] = x['統計年月'].astype(int)
    assert (x['人口數-男'] + x['人口數-女'] == x['人口數']).all(), (f, 'male + female != total')
    for s in '男女':
        cs = [c for c in ages if c.endswith(s)]
        assert (x[cs].sum(axis=1) == x[f'人口數-{s}']).all(), (f, s, 'ages do not sum to total')
    assert not x.duplicated(['county', 'town', 'vil']).any(), (f, 'duplicate villages')
    x['county_town'] = x['區域別']; x['village'] = x['村里']
    m = x.melt(id_vars=['month', 'county', 'town', 'vil', 'county_town', 'village'], value_vars=ages, var_name='k', value_name='population')
    m['sex'] = m.k.str[-1].map({'男': 'M', '女': 'F'}); m['age'] = m.k.str.extract(r'(\d+)')[0].astype(int)
    long.append(m.drop(columns='k'))
    a = lambda lo, hi=100: x[[c for c in ages if lo <= int(re.match(r'\d+', c).group()) <= hi]].sum(axis=1)
    w = x[['month', 'county', 'town', 'vil', 'county_town', 'village']].copy()
    w['households'] = x['戶數']; w['population'] = x['人口數']; w['male'] = x['人口數-男']; w['female'] = x['人口數-女']
    w['age20plus'] = a(20); w['age18plus'] = a(18)
    for lab, lo, hi in (('share_20_39', 20, 39), ('share_40_64', 40, 64), ('share_65plus', 65, 100)):
        w[lab] = a(lo, hi) / w.age20plus.where(w.age20plus > 0)
    wide.append(w)
    print(os.path.basename(f), 'month', x.month.iloc[0], 'villages', len(x), 'population', f"{x['人口數'].sum():,}")
pd.concat(long, ignore_index=True).to_parquet(f'{OUT}/demog_age.parquet', index=False)
pd.concat(wide, ignore_index=True).to_csv(f'{OUT}/demog_village.csv', index=False)
print('checks passed')

areas.py

used by the cleaners
"""Area-name matching shared by the cleaners: county/town/village names -> MOI codes (as used by the CEC since 2016),
from the MOI October 2026 village population table (CLEAN_DIR/demog_village.csv, month 11510)."""
import re
from collections import defaultdict
import pandas as pd


def load(OUT, month=11510):
    dem = pd.read_csv(f'{OUT}/demog_village.csv', dtype={'county': str, 'town': str, 'vil': str})
    dem = dem[dem.month == month]
    dem['town_name'] = [ct[3:] for ct in dem.county_town]                            # '新北市板橋區' -> '板橋區'
    # Rare characters: the CEC .xls and the MOI table encode them differently (private-use codes or substitutes).
    # Mapped to one form on both sides; found by comparing unmatched village names town by town (2026-11-30).
    RARE = {'\ue02d': '廍', '\ue008': '磘', '\U000fffa8': '磘', '\U000fffc0': '萡', '\U00023424': '瓊', '\U000fcc79': '嵵',
            '\ue001': '𥕢', '\U000fffb5': '獇', '\ue007': '売', '\U0002f85a': '売', '\ue006': '塭', '\U000fb56f': '塭',
            '\ue000': '𦰡', '\ue012': '檨', '\U0002f8eb': '檨', '\U00024933': '檨'}   # last: Big5-HKSCS decoding
    def norm(s):
        if not isinstance(s, str): return s
        s = s.replace('台', '臺')
        for a, b in RARE.items(): s = s.replace(a, b)
        return s
    TOWN = {(c, norm(t)): tc for c, t, tc in zip(dem.county, dem.town_name, dem.town)}
    VIL = {(c, tc, norm(v)): vc for c, tc, v, vc in zip(dem.county, dem.town, dem.village, dem.vil)}
    BYTOWN = defaultdict(list)
    for (c, tc, v), vc in VIL.items(): BYTOWN[(c, tc)].append((v, vc))
    RARECH = set(RARE.values())
    def vil_code(c, tc, name, seen=()):
        """(code, list of codes, how). Exact name; 'A、B' cross-village stations -> list; names missing one rare character
        (dropped in the .xls, e.g. 磚里 for 磚磘里) -> the unique village in the town that equals it with one character removed."""
        name = norm(name).strip()
        if (c, tc, name) in VIL: return VIL[(c, tc, name)], None, 'exact'
        if '、' in name or ',' in name:                                    # stations covering several villages
            parts = [x for x in re.split('[、,]', name) if x]
            codes = [vil_code(c, tc, x)[0] for x in parts]
            return None, ';'.join(x or '?' for x in codes), 'cross_village'
        if '?' in name:
            # rare characters written as '?' in some CSVs: each '?' one character, or a run of '?' one character (Big5 bytes).
            # Drop villages spelled out elsewhere in the same file (`seen`); prefer names with a rare character; accept if unique.
            pats = {re.escape(name).replace('\\?', '.'), re.sub(r'(\\\?)+', '.', re.escape(name))}
            m = {(v, vc) for v, vc in BYTOWN[(c, tc)] for pt in pats if re.fullmatch(pt.replace('\\.', '.'), v)} - {(v, vc) for v, vc in BYTOWN[(c, tc)] if v in seen}
            if len(m) > 1: m = {x for x in m if any(ch in RARECH for ch in x[0])}
            return (next(iter(m))[1], None, 'wildcard') if len(m) == 1 else (None, None, 'unmatched')
        m = [vc for v, vc in BYTOWN[(c, tc)] if len(v) == len(name) + 1 and any(v[:i] + v[i + 1:] == name for i in range(len(v)))]
        if len(m) == 1: return m[0], None, 'missing_character'
        return None, None, 'unmatched'
    return TOWN, VIL, BYTOWN, vil_code, norm

cec_clean.py

"""Clean every election in the CEC election database (選舉資料庫, el* files) into one schema, with integrity checks.

usage: python3 cec_clean.py VOTEDATA_ROOT CLEAN_DIR      (VOTEDATA_ROOT = _data/source/votedata/votedata)

Outputs (CLEAN_DIR/<table>/source=cecdb/part.parquet; read all sources with pd.read_parquet(CLEAN_DIR/<table>)):
  elections            eid, source folder, year, office, seat type, race level, counts, check results, file versions used
  areas                eid, area codes, full name, town, village (names split from the CEC's concatenated names)
  candidates      eid, race codes, ballot no., name, party (raw and standardised), gender, birth (ROC yyymmdd),
                       age, birthplace, education, incumbent, elected mark (* elected, ! elected on a women's reserved
                       seat, - displaced by a reserved seat), elected (bool), vice (running mate)
  votes                eid, area codes, station, ballot no., votes, race_id, unit (station where published, else village or town)
  turnout            eid, area codes, unit, station, valid, invalid, cast, electors, population
  votes_agg, turnout_agg   the CEC's own aggregate rows (station = 0), kept for reference

Area codes: prv (省市, 2), city (縣市, 3), dist (選區, 2), town (鄉鎮市區, 3), vil (村里, 4); county = prv + city.
Codes follow the Ministry of the Interior from 2016; earlier codes are the CEC's own and change when counties merge.

Known source problems diagnosed by hand are listed in code/cec_known_issues.csv and attached to elections.csv.
Checks (each election; failures are recorded in elections.csv and printed, never silently dropped):
  sums     every aggregate vote row equals the sum of the station rows under it
  valid    at every station, valid = sum of candidates' votes; cast = valid + invalid
  elected  candidates marked elected per race = 當選人數 in elprof at that race's level
  link     every vote row matches a candidate, and every candidate has votes
File versions: where a folder holds several versions (e.g. elctks.csv and elctks1050129.csv, dated ROC yyymmdd),
each combination is checked and the one with fewest failed checks is kept (latest on ties); the 2016 'old' folder is skipped.
"""
import sys, os, re, glob, json
import numpy as np
import pandas as pd

ROOT, OUT = sys.argv[1], sys.argv[2]
os.makedirs(OUT, exist_ok=True)
CODES = ['prv', 'city', 'dist', 'town', 'vil']
ZERO = {'prv': '00', 'city': '000', 'dist': '00', 'town': '000', 'vil': '0000'}
NOPARTY = {'無', '無黨籍及未經政黨推薦', '無黨籍'}

# ----------------------------------------------------------------------------------------------- folder metadata
LY_TERM_YEAR = {'3屆立委': 1995, '4屆立委': 1998, '5屆立委': 2001}
CODE22 = {'C1': ('executive', 'general'), 'D1': ('township_chief', 'general'), 'D2': ('township_chief', 'indigenous_district'),
          'R1': ('township_rep', 'general'), 'R2': ('township_rep', 'plain_indigenous'), 'R3': ('township_rep', 'indigenous_district'),
          'T1': ('council', 'general'), 'T2': ('council', 'plain_indigenous'), 'T3': ('council', 'mountain_indigenous'),
          'V1': ('village_chief', 'general')}


def classify(rel):
    """rel: folder path relative to ROOT. Returns (year, office, seat_type, by_election)."""
    top = rel.split('/')[1] if rel.startswith('voteData/') else rel.split('/')[0]
    parts = rel.split('/')
    by = '補選' in rel
    m = re.search(r'(19|20)\d\d', top)
    year = int(m.group(0)) if m else LY_TERM_YEAR.get(top, 1996 if top == '9任總統' else None)
    if by and not m:                                   # 立委補選/<county><n> without a year
        year = None
    seat = 'general'
    s = rel
    if re.search(r'山原|山地', s): seat = 'mountain_indigenous'
    elif re.search(r'平原|平地', s): seat = 'plain_indigenous'
    elif '原住民' in s: seat = 'indigenous'
    for p in parts:
        if p in CODE22:
            return year, CODE22[p][0], CODE22[p][1], by
    if '總統' in s and not re.search(r'立委|不分區|區域', parts[-1]): office = 'president'
    elif '不分區' in s: office = 'legislator_party_list'
    elif re.search(r'立委|立法委員', s): office = 'legislator'
    elif re.search(r'國大|國代', s): office = 'national_assembly'
    elif '省長' in s: office = 'governor'
    elif '省議員' in s: office = 'provincial_assembly'
    elif re.search(r'議員', s): office = 'council'
    elif re.search(r'鄉鎮市長|區長', s): office = 'township_chief'
    elif re.search(r'代表', s): office = 'township_rep'
    elif re.search(r'村里長|里長', s): office = 'village_chief'
    elif re.search(r'市長|縣市長', s): office = 'executive'
    else: office = 'unknown'
    return year, office, seat, by


def versions(d, kind):
    """All versions of el<kind> in folder d, latest first (suffix = ROC date or version number)."""
    fs = [f for f in glob.glob(f'{d}/el{kind}*.csv') if re.fullmatch(rf'el{kind}(_[A-Z]\d)?(\d*)\.csv', os.path.basename(f))]
    key = lambda f: int(re.fullmatch(rf'el{kind}(_[A-Z]\d)?(\d*)\.csv', os.path.basename(f)).group(2) or 0)
    return sorted(fs, key=key, reverse=True)


def read(path, n):
    x = pd.read_csv(path, header=None, dtype=str, names=range(n + 4), encoding='utf-8-sig', keep_default_na=False,
                    on_bad_lines='error', engine='python' if os.path.getsize(path) < 5e5 else 'c')
    x = x.iloc[:, :n].apply(lambda c: c.str.strip().str.strip("'").str.strip())
    return x[x[0] != '']


def codes(x):
    x = x.rename(columns=dict(enumerate(CODES)))
    for c in CODES:
        x[c] = x[c].str.zfill(len(ZERO[c])) if c != 'vil' else x[c].where(~x[c].str.fullmatch(r'\d+'), x[c].str.zfill(4))
    return x


# ----------------------------------------------------------------------------------------------- one election
def clean(d, eid, files):
    rel = os.path.relpath(d, ROOT)
    year, office, seat, by = classify(rel)
    base = codes(read(files['base'], 6)).rename(columns={5: 'name'})
    paty = read(files['paty'], 2).rename(columns={0: 'code', 1: 'party'})
    pm = dict(zip(paty.code.str.lstrip('0').replace('', '0'), paty.party))
    ncol = 16 if pd.read_csv(files['cand'], header=None, dtype=str, nrows=5, encoding='utf-8-sig').shape[1] >= 16 else 15
    cand = codes(read(files['cand'], ncol))
    cand = cand.rename(columns={5: 'no', 6: 'name', 7: 'party_code', 8: 'gender', 9: 'birth', 10: 'age', 11: 'birthplace',
                                12: 'education', 13: 'incumbent', 14: 'mark', 15: 'vice'})
    if 'vice' not in cand: cand['vice'] = ''
    cand['no'] = cand.no.astype(int)
    cand['party'] = cand.party_code.str.lstrip('0').map(pm).fillna(cand.party_code)
    cand['party_std'] = cand.party.where(~cand.party.isin(NOPARTY), '無')
    cand['elected'] = cand.mark.isin(['*', '!'])
    prof = codes(read(files['prof'], 20))
    prof = prof.rename(columns={5: 'station', 6: 'valid', 7: 'invalid', 8: 'cast', 9: 'electors', 10: 'population'})
    for c in ['station', 'valid', 'invalid', 'cast', 'electors', 'population']:
        prof[c] = pd.to_numeric(prof[c], errors='coerce').fillna(0).astype(np.int64)
    ctks = codes(read(files['ctks'], 10)).rename(columns={5: 'station', 6: 'no', 7: 'votes', 9: 'mark'})
    ctks['station'] = ctks.station.astype(int); ctks['no'] = ctks.no.astype(int); ctks['votes'] = ctks.votes.astype(np.int64)
    ctks = ctks[CODES + ['station', 'no', 'votes', 'mark']]

    issues, notes = [], []
    # unit of observation: polling stations where published, else the finest aggregate level present
    def finest(x):
        stx = x[x.station != 0]
        if len(stx): return stx, x[x.station == 0], 'station'
        a = x[x.station == 0]
        for unit, m in (('village', a.vil != '0000'), ('town', (a.town != '000') & (a.vil == '0000'))):
            if m.any(): return a[m], a[~m], unit
        return a.iloc[:0], a, 'none'
    st, ag, unit = finest(ctks)
    pst, pag, punit = finest(prof)
    if unit != 'station': notes.append(f'votes published at {unit} level only')
    if punit != unit: notes.append(f'turnout at {punit} level, votes at {unit} level')

    # race level: codes set in elcand; dist dropped where the vote rows do not carry it (inconsistent coding)
    race = [c for c in CODES if (cand[c] != ZERO[c]).any()]
    if 'dist' in race and len(st) and (st.dist == ZERO['dist']).all():
        race.remove('dist'); notes.append('dist code set in elcand but not in vote rows; races keyed without dist')
    rid = lambda x: x[race].astype(str).agg('-'.join, axis=1) if race else pd.Series('all', index=x.index)
    cand['race_id'] = rid(cand); st = st.assign(race_id=rid(st))

    # sums: aggregate vote rows vs the unit rows under them
    bad = nomatch = 0
    if len(st) and len(ag):
        pat = ag[CODES].ne(pd.Series(ZERO)).astype(int).astype(str).agg(''.join, axis=1)
        for pt, g in ag.groupby(pat):
            keep = [c for c, b in zip(CODES, pt) if b == '1']
            for k in (keep, [c for c in keep if c != 'dist']):
                s_ = st.groupby(k + ['no']).votes.sum() if k else st.groupby('no').votes.sum()
                g2 = g.groupby(k + ['no']).votes.first() if k else g.groupby('no').votes.first()
                j = pd.concat([g2.rename('agg'), s_.rename('sum')], axis=1, join='inner')
                if len(j) == len(g2): break
            bad += int((j['agg'] != j['sum']).sum()); nomatch += len(g2) - len(j); absd = locals().get('absd', 0) + int((j['agg'] - j['sum']).abs().sum())
    if bad: issues.append(f'sums: {bad} aggregate rows differ from unit sums (|diff| summed over all levels {absd:,})')
    if nomatch: issues.append(f'sums: {nomatch} aggregate rows with no unit rows under them')

    # valid / cast at each unit; joined without dist where that keeps keys unique
    if len(st) and len(pst) and unit == punit:
        # village codes differ between files for cross-village stations (e.g. A001), so join on town + station when unique
        for k in (['prv', 'city', 'town', 'station'], ['prv', 'city', 'town', 'vil', 'station'], CODES + ['station']):
            if not pst.duplicated(k).any(): break                          # vote rows are summed to each turnout key
        sv = st.groupby(k).votes.sum().rename('sum')
        j = pst.groupby(k)[['valid', 'invalid', 'cast']].sum().join(sv, how='outer')
        extra = int(j.valid.isna().sum()); j = j.dropna(subset=['valid']).fillna(0)   # units with no vote rows count as 0 votes
        nv = int((j.valid != j['sum']).sum()); nc = int((j.cast != j.valid + j.invalid).sum())
        if extra: issues.append(f'valid: {extra} units with votes but no turnout row')
        if nv: issues.append(f'valid: {nv} units where valid != sum of votes (|diff| {int((j.valid - j["sum"]).abs().sum()):,} of {int(j.valid.sum()):,})')
        if nc: issues.append(f'valid: {nc} units where cast != valid + invalid')

    # link candidates and votes by race and ballot number
    ck = cand.drop_duplicates(['race_id', 'no'])[['race_id', 'no']]
    if len(st):
        m = st[['race_id', 'no']].drop_duplicates().merge(ck, how='outer', indicator=True)
        nv, nc = int((m._merge == 'left_only').sum()), int((m._merge == 'right_only').sum())
        if nv: issues.append(f'link: {nv} vote keys without a candidate')
        if nc: issues.append(f'link: {nc} candidates without votes')
    else:
        issues.append('no vote rows below the top level')

    # elected marks vs elprof 當選人數, for races that have their own elprof row
    def nelect(r):
        a = [int(float(v or 0)) for v in r]
        spec = a[0] == a[2] + a[3] and a[1] == a[4] + a[5]; alt = a[2] == a[0] + a[1] and a[5] == a[3] + a[4]
        return a[5] if alt and not spec else a[1]
    got = cand.drop_duplicates(['race_id', 'no']).groupby('race_id').elected.sum()
    if race:
        lvl = prof[(prof.station == 0) & pd.concat([(prof[c] != ZERO[c]) if c in race else (prof[c] == ZERO[c])
                                                   for c in CODES if c != 'dist' or 'dist' in race], axis=1).all(axis=1)]
        want = pd.Series([nelect(r) for r in lvl[[11, 12, 13, 14, 15, 16]].values], index=rid(lvl)).groupby(level=0).first()
    else:
        top = prof[(prof.station == 0) & (prof[CODES] == pd.Series(ZERO)).all(axis=1)]
        want = pd.Series([nelect(r) for r in top[[11, 12, 13, 14, 15, 16]].values[:1]], index=['all'])
    j = pd.concat([want.rename('want'), got.rename('got')], axis=1, join='inner')
    q = cand[~cand.mark.isin(['', '*', '!', '-'])].race_id.unique()          # undocumented marks such as '?'
    if len(q): notes.append(f"{len(q)} races with undocumented elected marks {sorted(set(cand.mark) - {'', '*', '!', '-'})}; not checked")
    j = j[~j.index.isin(q)]
    ne = int((j.want != j.got).sum())
    if ne: issues.append(f'elected: {ne} races where elected marks != 當選人數')
    if len(got) > len(j): notes.append(f'{len(got) - len(j)} races have no elprof row to check elected marks against')
    zero = int((got == 0).sum())
    if zero: notes.append(f"{zero} races with no candidate marked elected (marks: {sorted(set(cand.mark) - {'', '*', '!', '-'})})")
    tag = lambda x: x.assign(eid=eid)
    meta = dict(eid=eid, folder=rel, year=year, office=office, seat_type=seat, by_election=by, race_level='+'.join(race) or 'national',
                n_races=cand.race_id.nunique(), n_candidates=len(ck),
                unit=unit, n_units=len(pst), valid=int(pag[(pag[CODES] == pd.Series(ZERO)).all(axis=1)].valid.sum()) if len(pag) else int(pst.valid.sum()),
                unit_valid=int(pst.valid.sum()), checks='ok' if not issues else '; '.join(issues), notes='; '.join(notes),
                files=json.dumps({k: os.path.basename(v) for k, v in files.items()}, ensure_ascii=False))
    return (meta, tag(base), tag(cand[CODES + ['race_id', 'no', 'name', 'party_code', 'party', 'party_std', 'gender', 'birth', 'age', 'birthplace',
                                         'education', 'incumbent', 'mark', 'elected', 'vice']]),
            tag(st.drop(columns='mark').assign(unit=unit)), tag(pst.assign(unit=punit)[CODES + ['unit', 'station', 'valid', 'invalid', 'cast', 'electors', 'population']]),
            tag(ag), tag(pag[CODES + ['station', 'valid', 'invalid', 'cast', 'electors', 'population']]))


def split_names(base):
    """Town and village names from the CEC's concatenated full names, per election."""
    base = base.copy()
    full = base.set_index(['eid'] + CODES).name
    cty = base[(base.town == '000') & (base.vil == '0000') & (base.city != '000') | (base.prv != '00') & (base.city == '000') & (base.town == '000')]
    cty_name = cty.drop_duplicates(['eid', 'prv', 'city']).set_index(['eid', 'prv', 'city']).name
    twn = base[(base.town != '000') & (base.vil == '0000')].drop_duplicates(['eid', 'prv', 'city', 'town']).set_index(['eid', 'prv', 'city', 'town']).name
    def strip(s, p): return s[len(p):] if isinstance(p, str) and s.startswith(p) else s
    base['town_name'] = [strip(t, cty_name.get((e, p, c))) if t is not None else None
                         for e, p, c, t in zip(base.eid, base.prv, base.city, [twn.get(k) for k in zip(base.eid, base.prv, base.city, base.town)])]
    base['village_name'] = [strip(n, twn.get((e, p, c, t))) if v != '0000' else None
                            for e, p, c, t, v, n in zip(base.eid, base.prv, base.city, base.town, base.vil, base.name)]
    return base


if __name__ == '__main__':
    dirs = sorted({os.path.dirname(p) for p in glob.glob(f'{ROOT}/**/elcand*.csv', recursive=True)})
    dirs = [d for d in dirs if '/old/' not in d + '/']
    import itertools
    parts = []
    for i, d in enumerate(dirs, 1):
        vs = {k: versions(d, k) for k in ('base', 'cand', 'paty', 'prof', 'ctks')}
        tried = []
        for combo in itertools.product(*vs.values()):                       # latest-first order: ties keep the latest
            files = dict(zip(vs, combo)); r = clean(d, i, files)
            tried.append((0 if r[0]['checks'] == 'ok' else r[0]['checks'].count(';') + 1, len(tried), r))
        best = min(tried, key=lambda t: t[:2])[2]
        if len(tried) > 1:
            best[0]['notes'] = '; '.join(filter(None, [best[0]['notes'], f'{len(tried)} file-version combinations tried; kept the one with fewest failed checks']))
        r = best; parts.append(r)
        print(f"{i:3d} {r[0]['folder']:<50s} {r[0]['office']:<21s} {r[0]['unit']:<8s} {r[0]['checks']}", flush=True)
    E = pd.DataFrame([p[0] for p in parts])
    K = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cec_known_issues.csv'))
    known = {}
    for r in K.itertuples():
        for f in r.folder.split('; '): known.setdefault(f, []).append(f'{r.scope}: {r.use}')
    E['known_issue'] = E.folder.map(lambda f: ' | '.join(known.get(f, [])))      # documented in code/cec_known_issues.csv
    E['source'] = 'cecdb'
    def write(nm, df):                                       # one partition per source: CLEAN/<table>/source=cecdb/part.parquet
        d = f'{OUT}/{nm}/source=cecdb'; os.makedirs(d, exist_ok=True); df.to_parquet(f'{d}/part.parquet', index=False)
    write('elections', E.drop(columns='source'))
    names = ['areas', 'candidates', 'votes', 'turnout', 'votes_agg', 'turnout_agg']
    for k, nm in enumerate(names, 1):
        df = pd.concat([p[k] for p in parts], ignore_index=True)
        if nm == 'areas': df = split_names(df)
        write(nm, df)
        print(nm, len(df))
    print(f"{len(E)} elections; checks ok: {(E.checks == 'ok').sum()}")

cec_known_issues.csv

read by cec_clean.py
folder,scope,finding,evidence,use
voteData/2006直轄市長,Kaohsiung (prv 02) station-level elprof rows,"Station rows of the turnout file (elprof: valid, invalid, cast, electors) are attached to the wrong stations; the vote file (elctks) is correctly labelled. Totals at town, city and national level are unaffected.","760 of 839 Kaohsiung stations: elprof valid != sum of elctks votes, yet every elprof value equals some station's elctks total and the city totals agree (767,868). Same-day council ballot (voteData/2006直轄市議員(區域)): mayoral elctks vs council station valid, corr 0.990, 97% within 5%; mayoral elprof vs council, corr 0.076. Taipei (prv 01) matches station for station. No CEC correction notice found (searched 2026-11-30). Checked 2026-11-30: db.cec.gov.tw (theme d2ce132760640611c410338a3136e810) shows the same misassigned station turnout (e.g. Zuoying 海勝里 stations 136-139: valid 1001, 738, 975, 912) with correct votes (1030, 1446, 1012, 788); NCCU Election Study Center tables (vote.nccu.edu.tw/cec) give valid 1030, 1446, 1012, 788 and electors 1392, 2022, 1353, 1052, consistent with the votes and with the council electors. No correction notice found on web.cec.gov.tw, db.cec.gov.tw or data.gov.tw.","For Kaohsiung 2006 station turnout use the council election's elprof (same stations, same day) or mayoral elctks sums; do not use mayoral elprof station rows. NCCU's station tables are an independent source of correct station turnout if needed."
voteData/1994台灣省議員/山原; voteData/1994台灣省議員/平原; voteData/1994台灣省議員/平原2; voteData/1994直轄市議員/原住民; voteData/1996國大代表/山原; voteData/1996國大代表/平原,whole election,Only top-level (district or county) totals published; no village or station rows.,Coverage of the source files.,Use for totals only.
voteData/1998縣市議員/區域; voteData/2002縣市議員/區域,some districts,"Vote rows below the district level exist for only part of the districts, and turnout only at town level (2002). Sums of lower rows fall short of district totals.",1998: 351 district rows differ from town sums; 2002: 349 district totals have no station rows under them.,Use district totals for district-level work; lower-level rows are incomplete.

allcounty_load.py

"""Load the 2026 CEC polling-station tables (縣表3-1 mayor/magistrate, 縣表3-2 council) for all 22 counties.

General (regional) council districts are identified as the shortest leading run of district sheets whose
polling stations partition the county's stations exactly; the remaining sheets are indigenous districts
(平地/山地原住民), which overlap the general ones. Checked against the 2022 CEC database: the counts match in
21 counties; Hsinchu County gains one (Zhubei split into districts 1 and 2).

usage: python3 allcounty_load.py SRC_2026 CLEAN_DIR    (SRC_2026 = _data/source/votedata/2026/計票, CLEAN_DIR = _data/clean)
Reads the CEC files as downloaded (e.g. 63000臺北市/縣表3-1-63000(臺北市)-....xls).
Outputs (in CLEAN_DIR):
  ac_stations_2026.csv     one row per county x polling station: general district, town, village,
                           mayoral valid votes and votes per mayoral candidate (m_<ballot no.>), council valid votes
  ac_mayor_cands_2026.csv  county, ballot no., name, party, votes, share
  ac_council_cands_2026.csv county, district, general/indigenous, ballot no., name, party, votes, district share
  ac_districts_2026.csv    county, district, kind, seats, stations, candidates, valid votes
  ac_council_station_votes_2026.csv  long: county, district, kind, station, ballot no., votes (general and indigenous)
Station rows also carry invalid, cast and electors for the mayoral and the general council ballot.
"""
import sys, os, glob
from collections import defaultdict
import pandas as pd

num = lambda v: 0 if pd.isna(v) or str(v).strip() == '' else int(float(str(v).replace(',', '')))

# Seats per general council district, from the CEC's 2026 election announcement
# (https://web.cec.gov.tw/api/file/45d8e965-f63a-46d5-b636-7d81e47cf4d1.pdf, 應選出名額). REGIONAL = the announcement's 區域 totals.
SEATS = {
    '63000': [12, 9, 9, 8, 8, 13], '65000': [4, 5, 7, 9, 9, 6, 3, 9, 5, 1, 4],
    '68000': [12, 5, 5, 4, 2, 2, 11, 6, 4, 3, 1, 2], '66000': [3, 5, 5, 5, 6, 5, 4, 7, 3, 3, 4, 4, 6, 2],
    '67000': [5, 5, 3, 1, 5, 6, 7, 6, 6, 5, 6], '64000': [3, 3, 5, 9, 5, 4, 8, 5, 8, 7, 4],
    '10004': [4, 9, 5, 3, 2, 2, 1, 1, 5, 1, 1], '10005': [9, 3, 5, 9, 8, 2], '10007': [12, 7, 6, 9, 5, 4, 5, 5],
    '10008': [10, 9, 3, 5, 7], '10009': [10, 6, 9, 6, 7, 5], '10010': [8, 8, 4, 6, 3, 7],
    '10013': [12, 8, 10, 8, 4, 3, 1], '10002': [7, 2, 3, 2, 2, 5, 3, 4, 1, 2], '10015': [9, 1, 10, 3],
    '10014': [10, 1, 2, 2, 1, 1], '10016': [11, 3, 2, 1, 1, 1], '09020': [10, 7, 2], '09007': [5, 2, 1, 1],
    '10017': [4, 5, 3, 4, 7, 3, 4], '10018': [12, 4, 2, 9, 6], '10020': [10, 13]}
REGIONAL = {'63000': 59, '65000': 62, '68000': 57, '66000': 62, '67000': 55, '64000': 61, '10004': 34, '10005': 36,
            '10007': 53, '10008': 34, '10009': 43, '10010': 36, '10013': 46, '10002': 31, '10015': 23, '10014': 17,
            '10016': 19, '09020': 19, '09007': 9, '10017': 30, '10018': 33, '10020': 23}
assert all(sum(SEATS[k]) == REGIONAL[k] for k in SEATS)


SUMMARY = {'A': 'valid', 'B': 'invalid', 'C': 'cast', 'G': 'electors'}   # columns A-H after the candidates


def read_table(path, sheet):
    """Return (candidates [(col, ballot no., name, party)], station rows [(town, village, station, {col: votes}, summary)]).

    Checks, raising AssertionError on failure: at every station and town-subtotal row, A (valid) equals the sum of
    candidates' votes and C (cast) = A + B; station rows sum to each town subtotal row, for every candidate and A-G."""
    x = pd.read_excel(path, sheet_name=sheet, header=None, dtype=str)
    hdr, top = x.iloc[2], x.iloc[1]
    cols = [c for c in range(3, x.shape[1]) if isinstance(hdr[c], str) and '\n' in hdr[c]]
    scol = {SUMMARY[str(top[c])[0]]: c for c in range(cols[-1] + 1, x.shape[1])
            if isinstance(top[c], str) and str(top[c])[0] in SUMMARY}
    assert set(scol) == set(SUMMARY.values()), (path, sheet, scol)
    cands = []
    for c in cols:
        no, name, party = hdr[c].split('\n')[:3]
        cands.append((c, int(no), name.split(' ')[0].strip(), party.strip()))
    keys = cols + list(scol.values())
    town, rows, subtotal, acc = None, [], {}, defaultdict(lambda: defaultdict(int))
    for i, r in x.iloc[5:].iterrows():
        v = {c: num(r[c]) for c in keys}
        if any(pd.notna(r[c]) for c in keys):
            assert v[scol['valid']] == sum(v[c] for c in cols), (path, sheet, i, 'A != sum of candidates')
            assert v[scol['cast']] == v[scol['valid']] + v[scol['invalid']], (path, sheet, i, 'C != A + B')
        if pd.notna(r[0]):                                   # town subtotal row
            town = r[0].strip(); subtotal[town] = v
            continue
        if pd.isna(r[1]) or pd.isna(r[2]):
            continue
        for c in keys:
            acc[town][c] += v[c]
        rows.append((town, r[1].strip(), int(float(r[2])), {c: v[c] for c in cols},
                     {k: v[c] for k, c in scol.items()}))
    assert set(subtotal) == set(acc), (path, sheet, 'towns without stations or subtotals')
    for t in subtotal:
        bad = [c for c in keys if subtotal[t][c] != acc[t][c]]
        assert not bad, (path, sheet, t, 'stations do not sum to town subtotal', bad)
    return cands, rows


def load_county(raw, county):
    """county like '63000臺北市'. Returns stations, mayoral candidates, council candidates, districts (DataFrames)."""
    d = f'{raw}/{county}'
    mpath, = glob.glob(f'{d}/縣表3-1-*'); cpath, = glob.glob(f'{d}/縣表3-2-*')
    st = defaultdict(dict)
    mc, mrows = read_table(mpath, 0)
    assert len({s for _, _, s, _, _ in mrows}) == len(mrows), (county, 'duplicate mayoral station numbers')
    for town, vil, s, v, sm in mrows:
        r = st[s]; r.update(town=town, village=vil, m_valid=sm['valid'], m_invalid=sm['invalid'],
                            m_cast=sm['cast'], electors=sm['electors'])
        for c, no, _, _ in mc:
            r[f'm_{no}'] = v[c]
    mtot = {no: sum(st[s][f'm_{no}'] for s in st) for _, no, _, _ in mc}
    MV = sum(mtot.values())
    mayor = pd.DataFrame([dict(county=county, no=no, name=n, party=p, votes=mtot[no], share=mtot[no] / MV)
                          for _, no, n, p in mc])

    sheets = pd.ExcelFile(cpath).sheet_names
    tables = [read_table(cpath, sh) for sh in sheets]
    stations = set(st)
    seen, n_general = set(), None
    for k, (_, rows) in enumerate(tables, 1):
        ss = {s for _, _, s, _, _ in rows}
        if ss & seen:
            break
        seen |= ss
        if seen == stations:
            n_general = k
            break
    if n_general is None:
        raise ValueError(f'{county}: no leading run of districts partitions the polling stations')
    seats = SEATS[county[:5]]
    assert n_general == len(seats), (county, n_general, len(seats))

    cands, dists, long = [], [], []
    for k, (sh, (cc, rows)) in enumerate(zip(sheets, tables), 1):
        kind = 'general' if k <= n_general else 'indigenous'
        tot = {c: sum(v[c] for _, _, _, v, _ in rows) for c, *_ in cc}
        valid = sum(tot.values())
        M = seats[k - 1] if kind == 'general' else None
        dists.append(dict(county=county, dist=k, kind=kind, seats=M, stations=len(rows), candidates=len(cc), valid=valid))
        order = sorted(cc, key=lambda t: -tot[t[0]])
        rank = {t[1]: i for i, t in enumerate(order, 1)}
        for c, no, n, p in cc:
            cands.append(dict(county=county, dist=k, kind=kind, seats=M, no=no, name=n, party=p, votes=tot[c],
                              share=tot[c] / valid if valid else 0, rank=rank[no],
                              # top M by votes; the women's reserved seats are not applied
                              top_m=bool(M) and rank[no] <= M))
        for town, vil, s, v, sm in rows:
            for c, no, _, _ in cc:
                long.append((county, k, kind, s, no, v[c]))
        if kind == 'general':
            for town, vil, s, v, sm in rows:
                assert (town, vil) == (st[s]['town'], st[s]['village']), (county, s, 'station in a different village')
                st[s].update(dist=k, c_valid=sm['valid'], c_invalid=sm['invalid'], c_cast=sm['cast'],
                             c_electors=sm['electors'])
    sdf = pd.DataFrame([dict(county=county, station=s, **r) for s, r in sorted(st.items())])
    sv = pd.DataFrame(long, columns=['county', 'dist', 'kind', 'station', 'no', 'votes'])
    return sdf, mayor, pd.DataFrame(cands), pd.DataFrame(dists), sv


def counties(raw):
    return sorted(os.path.basename(p) for p in glob.glob(f'{raw}/*') if glob.glob(f'{p}/縣表3-2-*'))


if __name__ == '__main__':
    RAW, OUT = sys.argv[1], sys.argv[2]
    os.makedirs(OUT, exist_ok=True)
    parts = [load_county(RAW, c) for c in counties(RAW)]
    for i, name in enumerate(['ac_stations_2026', 'ac_mayor_cands_2026', 'ac_council_cands_2026', 'ac_districts_2026',
                             'ac_council_station_votes_2026']):
        pd.concat([p[i] for p in parts], ignore_index=True).to_csv(f'{OUT}/{name}.csv', index=False)
    dd = pd.concat([p[3] for p in parts])
    print(dd.groupby(['county', 'kind']).dist.count().unstack(fill_value=0).to_string())

cec2026_web.py

"""Fetch the CEC's 2026 council result pages (one per district) and record each candidate's gender and elected mark,
which the polling-station .xls tables do not carry.

Source: https://vote.cec.gov.tw/2026-local/zh-TW/T1/<county 5><district 2>0000000000.html (static HTML; T1 = council).
T2 = plain indigenous, T3 = mountain indigenous districts. Pages are saved unchanged in _data/source/cec_web_2026/<T1|T2|T3>/ (fetched once, 1 s apart; re-runs read the saved copies).

usage: python3 cec2026_web.py CLEAN_DIR SOURCE_DIR     (needs CLEAN_DIR/ac_districts_2026.csv from allcounty_load.py)
Output: CLEAN_DIR/ac_council_marks_2026.csv  county, dist, seats, women's reserved seats, no, name, gender, votes, party, mark
Checks: candidate list, votes and party on each page match the polling-station tables; marked winners = seats.
"""
import sys, os, re, time, html, urllib.request, urllib.error
import pandas as pd

CLEAN, SRC = sys.argv[1], sys.argv[2]
dists = pd.read_csv(f'{CLEAN}/ac_districts_2026.csv')
cands = pd.read_csv(f'{CLEAN}/ac_council_cands_2026.csv')
num = lambda s: int(s.replace(',', ''))
rows, problems = [], []
for r in dists.itertuples():
    code = f'{r.county[:5]}{r.dist:02d}0000000000'
    path = None
    for pre in (['T1'] if r.kind == 'general' else ['T2', 'T3']):     # T1 regional, T2 plain indigenous, T3 mountain indigenous
        p_ = f'{SRC}/cec_web_2026/{pre}/{code}.html'
        if os.path.exists(p_): path = p_; break
    for pre in ([] if path else (['T1'] if r.kind == 'general' else ['T2', 'T3'])):
        os.makedirs(f'{SRC}/cec_web_2026/{pre}', exist_ok=True)
        url = f'https://vote.cec.gov.tw/2026-local/zh-TW/{pre}/{code}.html'
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (research script)'})
        try:
            with urllib.request.urlopen(req, timeout=30) as f: body = f.read()
        except urllib.error.HTTPError as e:
            time.sleep(1)
            if e.code == 404: continue
            raise
        path = f'{SRC}/cec_web_2026/{pre}/{code}.html'; open(path, 'wb').write(body); time.sleep(1); break
    if path is None:
        problems.append(f'no page for {r.county} district {r.dist}'); continue
    seat_type = {'T1': 'general', 'T2': 'plain_indigenous', 'T3': 'mountain_indigenous'}[path.split('/')[-2]]
    s = open(path, encoding='utf-8').read()
    sub = re.sub(r'<[^>]+>', ' ', re.search(r'vote-table-header-subtitle">(.*?)</div>\s*</div>', s, re.S).group(1))
    seats = int(re.search(r'應選人數:\s*(\d+)', sub).group(1))
    w = re.search(r'婦女應當選名額:\s*(\d+)', sub); women = int(w.group(1)) if w else 0
    for tr in re.findall(r'<tr[^>]*>(.*?)</tr>', s, re.S)[1:]:
        c = [html.unescape(re.sub(r'<[^>]+>|\s+', ' ', x)).strip() for x in re.findall(r'<td[^>]*>(.*?)</td>', tr, re.S)]
        if len(c) < 7: continue
        rows.append(dict(county=r.county, dist=r.dist, kind=r.kind, seat_type=seat_type, seats_page=seats, women_seats=women, no=int(c[1]),
                         name=c[2], gender=c[3], votes=num(c[4]), party_page=c[6], mark=c[0]))
M = pd.DataFrame(rows)
# checks against the polling-station tables
j = M.merge(cands[['county', 'dist', 'no', 'name', 'votes', 'party', 'seats']], on=['county', 'dist', 'no'], how='outer',
            suffixes=('', '_xls'), indicator=True)
for lab, bad in [('missing from page or tables', j._merge != 'both'), ('name differs', j.name.str.split(' ').str[0] != j.name_xls),
                 ('votes differ', j.votes != j.votes_xls)]:
    if bad.any(): problems.append(f'{lab}: {int(bad.sum())}')
g = j[j.kind == 'general']
if (g.seats_page != g.seats).any(): problems.append('seats differ from the announcement')
# ◎ elected, ● elected on a women's reserved seat, - displaced by one
won = M.assign(w=M['mark'].isin(['◎', '●'])).groupby(['county', 'dist']).agg(w=('w', 'sum'), seats=('seats_page', 'first'))
if (won.w != won.seats).any(): problems.append(f"marked winners != seats in {int((won.w != won.seats).sum())} districts")
M.drop(columns='seats_page').assign(seats=M.seats_page).to_csv(f'{CLEAN}/ac_council_marks_2026.csv', index=False)
print(f'{len(dists)} districts, {len(M)} candidates; marks: {M["mark"].value_counts().to_dict()}; genders: {M.gender.value_counts().to_dict()}')
print('checks:', 'ok' if not problems else '; '.join(problems))

cec2026_clean.py

"""Clean the CEC's 2026 polling-station tables (縣表3-1 to 3-5, all 22 counties) into the same schema as cec_clean.py.

usage: python3 cec2026_clean.py SRC_2026 CLEAN_DIR    (SRC_2026 = _data/source/votedata/2026/計票, CLEAN_DIR = _data/clean)
Tables: 3-1 mayor/magistrate (executive), 3-2 council, 3-3 township chief (incl. indigenous district chief),
        3-4 township representative, 3-5 village chief.
Writes partition source=cec2026 of the datasets in CLEAN_DIR (elections, candidates, votes, turnout); eids 2026001...
Area codes: prv + city from the folder (e.g. 63000 -> 63, 000); town and village codes (MOI, as used by the CEC since
2016) matched by name from the MOI October 2026 population table (CLEAN_DIR/demog_village.csv, month 11510).
Council seat types and women's reserved seats come from ac_council_marks_2026.csv (cec2026_web.py) when present.
Checks (each sheet): A = sum of candidates and C = A + B on every row; station rows sum to every subtotal row;
every station of a county appears once per ballot type except where a town has several races (3-4, 3-5).
Elected: single-seat races = most votes (ties flagged); council from the CEC web marks; 3-4 not available (blank).
"""
import sys, os, re, glob
from collections import defaultdict
import pandas as pd

SRC, OUT = sys.argv[1], sys.argv[2]
num = lambda v: 0 if pd.isna(v) or str(v).strip() == '' else int(float(str(v).replace(',', '')))
SUMMARY = {'A': 'valid', 'B': 'invalid', 'C': 'cast', 'G': 'electors'}
TABLES = {'3-1': 'executive', '3-2': 'council', '3-3': 'township_chief', '3-4': 'township_rep', '3-5': 'village_chief'}


def parse(path, sheet, layout):
    """layout 'std': col0 subtotal name, col1 village, col2 station, candidates from col3.
       layout 'vil': col0 village (subtotal), col1 station, candidates from col2 (3-5).
    Returns list of blocks: dict(sub=name, cands=[(no, name, party)], stations=[(village, station, votes[list], summary)])."""
    x = pd.read_excel(path, sheet_name=sheet, header=None, dtype=str)
    c0 = 3 if layout == 'std' else 2
    top = x.iloc[1]
    scol = {SUMMARY[str(top[c])[0]]: c for c in range(c0, x.shape[1]) if isinstance(top[c], str) and str(top[c])[0] in SUMMARY}
    assert set(scol) == set(SUMMARY.values()), (path, sheet)
    last = min(scol.values())
    blocks, cur, cands = [], None, None
    for i in range(2, len(x)):
        r = x.iloc[i]
        cells = [r[c] for c in range(c0, last)]
        if any(isinstance(v, str) and '\n' in v for v in cells):                 # candidate header row
            cands = [(c, *v.split('\n')[:3]) for c, v in zip(range(c0, last), cells) if isinstance(v, str) and '\n' in v]
            cands = [(c, int(no), nm.strip(), p.strip()) for c, no, nm, p in cands]      # full name, incl. indigenous romanisation
            continue
        if cands is None or all(pd.isna(r[c]) for c in [cc[0] for cc in cands] + list(scol.values())):
            continue
        votes = [num(r[c]) for c, *_ in cands]; sm = {k: num(r[c]) for k, c in scol.items()}
        assert sm['valid'] == sum(votes), (path, sheet, i, 'A != sum of candidates')
        assert sm['cast'] == sm['valid'] + sm['invalid'], (path, sheet, i, 'C != A + B')
        if pd.notna(r[0]):                                                        # subtotal row opens a block
            cur = dict(sub=str(r[0]).strip(), cands=[cc[1:] for cc in cands], total=votes, total_sm=sm, stations=[], village=None)
            blocks.append(cur)
            if layout == 'vil': cur['village'] = cur['sub']
            continue
        if layout == 'std':
            if pd.notna(r[1]): cur['village'] = str(r[1]).strip()
            st = r[2]
        else:
            st = r[1]
        if pd.isna(st): continue
        cur['stations'].append((cur['village'], int(float(st)), votes, sm))
    for b in blocks:                                                              # stations sum to each subtotal
        assert [sum(s[2][k] for s in b['stations']) for k in range(len(b['cands']))] == b['total'], (path, sheet, b['sub'])
        for k in SUMMARY.values():
            assert sum(s[3][k] for s in b['stations']) == b['total_sm'][k], (path, sheet, b['sub'], k)
    return blocks


sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import areas
TOWN, VIL, BYTOWN, vil_code, norm = areas.load(OUT)
marks_path = f'{OUT}/ac_council_marks_2026.csv'
if not os.path.exists(marks_path):     # seat types and elected marks come from the CEC web pages
    sys.exit(f'{marks_path} missing: run allcounty_load.py and cec2026_web.py first')
MARKS = pd.read_csv(marks_path)

E, C, V, T, unmatched = [], [], [], [], defaultdict(set)
eid = 2026000
for cdir in sorted(glob.glob(f'{SRC}/*')):
    county = os.path.basename(cdir); code = county[:5]; prv, city = code[:2], code[2:]
    for tab, office in TABLES.items():
        fs = glob.glob(f'{cdir}/縣表{tab}-*')
        if not fs: continue
        path = fs[0]; sheets = pd.ExcelFile(path).sheet_names
        eid += 1; n_st = 0
        for si, sh in enumerate(sheets, 1):
            blocks = parse(path, sh, 'vil' if tab == '3-5' else 'std')
            for b in blocks:
                # race identity and area of each block
                if tab == '3-1': dist, town_nm, race = '00', None, code
                elif tab == '3-2': dist, town_nm, race = f'{si:02d}', None, f'{code}-{si:02d}'
                elif tab == '3-3': dist, town_nm, race = '00', sh, f'{code}-{sh}'
                elif tab == '3-4':
                    m = re.match(r'第(\d+)選舉區', b['sub']); dist = f'{int(m.group(1)):02d}' if m else '00'
                    town_nm, race = sh, f'{code}-{sh}-{dist}'
                else: dist, town_nm, race = '00', sh, f'{code}-{sh}-{b["sub"]}'
                for no, nm, party in b['cands']:
                    C.append(dict(eid=eid, prv=prv, city=city, dist=dist, race_id=race, no=no, name=nm, name_zh=nm.split(' ')[0], party=party,
                                  party_std='無' if party in ('無', '無黨籍及未經政黨推薦') else party))
                for vil, st, votes, sm in b['stations']:
                    tn = town_nm if tab in ('3-3', '3-4', '3-5') else (b['sub'] if tab in ('3-1', '3-2') else None)
                    tc = TOWN.get((code, norm(tn)))
                    vc, vlist, how = vil_code(code, tc, vil) if tc else (None, None, 'unmatched')
                    if tc is None: unmatched['town'].add((county, tn))
                    unmatched[how].add((county, tn, vil))
                    key = dict(eid=eid, prv=prv, city=city, dist=dist, town=tc, vil=vc, vil_list=vlist, vil_match=how,
                               town_name=tn, village_name=vil, station=st)
                    T.append(dict(key, race_id=race, **sm)); n_st += 1
                    for (no, _, _), v in zip(b['cands'], votes):
                        V.append(dict(key, race_id=race, no=no, votes=v))
        E.append(dict(eid=eid, source=f'2026/計票/{county}/{os.path.basename(path)}', year=2026, office=office, county=county, n_rows=n_st))
        print(county, tab, office, 'sheets', len(sheets), 'station rows', n_st, flush=True)

E, C, V, T = (pd.DataFrame(x) for x in (E, C, V, T))
C = C.drop_duplicates(['eid', 'race_id', 'no'])          # each subtotal block repeats its race's candidates
# council seat types and elected marks from the CEC web pages; seat type general/plain/mountain indigenous
if MARKS is not None:
    MARKS['race_id'] = MARKS.county.str[:5] + '-' + MARKS.dist.map('{:02d}'.format)
    C = C.merge(MARKS[['race_id', 'no', 'gender', 'mark', 'seat_type', 'seats', 'women_seats']], on=['race_id', 'no'], how='left')
    C.loc[C.eid.isin(E[E.office == 'council'].eid), 'elected'] = C.mark.isin(['◎', '●'])   # ◎ elected, ● reserved seat, - displaced
# single-seat races: elected = most votes; ties flagged
tot = V.groupby(['eid', 'race_id', 'no']).votes.sum().rename('total').reset_index()
C = C.merge(tot, on=['eid', 'race_id', 'no'], how='left')
single = C.eid.isin(E[E.office.isin(['executive', 'township_chief', 'village_chief'])].eid)
mx = C[single].groupby(['eid', 'race_id']).total.transform('max')
C.loc[single, 'elected'] = C.loc[single, 'total'] == mx
ties = C[single & C.elected.astype(bool)].groupby(['eid', 'race_id']).size()
E['ties'] = E.eid.map(ties[ties > 1].groupby(level=0).size()).fillna(0).astype(int)
E['n_races'] = E.eid.map(C.groupby('eid').race_id.nunique()); E['n_candidates'] = E.eid.map(C.groupby('eid').size())
E['unit'] = 'station'
for nm, df in (('elections', E), ('candidates', C), ('votes', V), ('turnout', T)):
    d = f'{OUT}/{nm}/source=cec2026'; os.makedirs(d, exist_ok=True)
    df.to_parquet(f'{d}/part.parquet', index=False)
print(f"{len(E)} tables; candidates {len(C)}; vote rows {len(V)}; station rows {len(T)}; ties in single-seat races: {int(E.ties.sum())}")
print('unmatched towns', len(unmatched['town']), '| village names:', {k: len(v) for k, v in unmatched.items() if k != 'town'})
print('unmatched village names:', sorted(unmatched['unmatched'])[:20])

cec_byelection_clean.py

"""Clean the CEC's by-elections published after the election database's last update (立委補選(2019年後),
鄉鎮市長及議員補選(2023年後)) and the 2022 Chiayi City mayoral re-run (2022年_嘉義市長重行選舉) into the common schema.

usage: python3 cec_byelection_clean.py VOTEDATA_ROOT CLEAN_DIR     (VOTEDATA_ROOT = _data/source/votedata/votedata)
Format: cand.csv (號次, 名字, 政黨名稱) and prof.csv (one row per polling station: 行政區別, 村里別, 投開票所別, 號次1..N, A-H).
Writes partition source=cec_byelection of elections, candidates, votes, turnout; eids 9000001...
County, year and office come from the folder name. Town/village codes are matched by name (code/areas.py).
Checks: every station row has A = sum of candidates, C = A + B, E = C + D, G = E + F; no duplicate stations.
Elected: most votes (single-seat races; ties flagged).
"""
import sys, os, re, glob
import pandas as pd
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import areas

ROOT, OUT = sys.argv[1], sys.argv[2]
TOWN, VIL, BYTOWN, vil_code, norm = areas.load(OUT)
dem = pd.read_csv(f'{OUT}/demog_village.csv', dtype={'county': str})
COUNTY = {norm(ct[:3]): c for ct, c in zip(dem.county_town, dem.county)}         # '臺北市' -> '63000'
num = lambda v: 0 if pd.isna(v) or str(v).strip() == '' else int(float(str(v).replace(',', '').replace('%', '')))
folders = sorted(glob.glob(f'{ROOT}/立委補選(2019年後)/*') + glob.glob(f'{ROOT}/鄉鎮市長及議員補選(2023年後)/*') + [f'{ROOT}/2022年_嘉義市長重行選舉'])
E, C, V, T, problems = [], [], [], [], []
for i, d in enumerate(folders, 9000001):
    name = os.path.basename(d)
    year = int(re.match(r'(\d{4})', name).group(1))
    cname = next(k for k in COUNTY if k in norm(name)); code = COUNTY[cname]
    office = ('legislator' if '立法委員' in name else 'council' if '議員' in name else
              'executive' if name.endswith('嘉義市長重行選舉') else 'township_chief')
    m = re.search(r'第(\d+)選舉區', name); dist = f'{int(m.group(1)):02d}' if m else '00'
    def rd(f):                                                  # UTF-8 (with BOM) or Big5; rows may carry extra empty columns
        for enc in ('utf-8-sig', 'cp950', 'big5hkscs'):
            try: return pd.read_csv(f, dtype=str, encoding=enc, index_col=False).dropna(how='all')
            except UnicodeDecodeError: continue
        raise ValueError(f)
    cand = rd(f'{d}/cand.csv').fillna('')
    cand = cand.iloc[:, :3]; cand.columns = ['no', 'name', 'party']; cand = cand.apply(lambda c: c.str.strip())
    cand['no'] = cand.no.astype(int); cand['party'] = cand.party.replace('', '無')
    prof = rd(f'{d}/prof.csv')
    cols = list(prof.columns); ncand = sum(c.startswith('號次') for c in cols)
    assert ncand == len(cand), (name, 'candidate columns != cand.csv')
    sm = {k: cols[3 + ncand + j] for j, k in enumerate(['valid', 'invalid', 'cast', 'unused_issued', 'issued', 'remaining', 'electors'])}
    race = f'{code}-{dist}' if office in ('legislator', 'council') else code if office == 'executive' else f'{code}-{name}'
    bad = 0
    seen = set(norm(str(v)).strip() for v in prof['村里別'])            # village names spelled out in this file
    for r in prof.itertuples(index=False):
        r = dict(zip(cols, r))
        votes = [num(r[f'號次{k}']) for k in cand.no]; s = {k: num(r[c]) for k, c in sm.items()}
        bad += (s['valid'] != sum(votes)) + (s['cast'] != s['valid'] + s['invalid']) + \
               (s['issued'] != s['cast'] + s['unused_issued']) + (s['electors'] != s['issued'] + s['remaining'])
        tn, vn = norm(r['行政區別']).strip(), str(r['村里別']).strip()
        tc = TOWN.get((code, tn)); vc, vlist, how = vil_code(code, tc, vn, seen) if tc else (None, None, 'unmatched')
        key = dict(eid=i, prv=code[:2], city=code[2:], dist=dist, town=tc, vil=vc, vil_list=vlist, vil_match=how,
                   town_name=tn, village_name=vn, station=num(r['投開票所別']))
        T.append(dict(key, race_id=race, valid=s['valid'], invalid=s['invalid'], cast=s['cast'], electors=s['electors']))
        for no, v in zip(cand.no, votes): V.append(dict(key, race_id=race, no=no, votes=v))
    tot = {no: sum(v['votes'] for v in V if v['eid'] == i and v['no'] == no) for no in cand.no}
    top = max(tot.values())
    for r in cand.itertuples():
        C.append(dict(eid=i, prv=code[:2], city=code[2:], dist=dist, race_id=race, no=r.no, name=r.name, name_zh=r.name.split(' ')[0],
                      party=r.party, party_std=r.party if r.party not in ('無黨籍及未經政黨推薦',) else '無', total=tot[r.no],
                      elected=tot[r.no] == top))
    n_st = len(prof); dup = prof.duplicated(['行政區別', '投開票所別']).sum()
    issues = [f'{bad} failed row identities'] if bad else []
    if dup: issues.append(f'{dup} duplicate stations')
    if sum(t == top for t in tot.values()) > 1: issues.append('tie for first place')
    E.append(dict(eid=i, source=os.path.relpath(d, ROOT), year=year, office=office, county=cname, by_election=True, unit='station',
                  n_races=1, n_candidates=len(cand), n_units=n_st, valid=sum(tot.values()), checks='ok' if not issues else '; '.join(issues)))
    print(f'{i} {name:<40s} {office:<15s} stations {n_st:4d} {E[-1]["checks"]}')
E, C, V, T = (pd.DataFrame(x) for x in (E, C, V, T))
for nm, df in (('elections', E), ('candidates', C), ('votes', V), ('turnout', T)):
    dd = f'{OUT}/{nm}/source=cec_byelection'; os.makedirs(dd, exist_ok=True); df.to_parquet(f'{dd}/part.parquet', index=False)
print(f"{len(E)} by-elections; checks ok: {(E.checks == 'ok').sum()}; village matching: {T.vil_match.value_counts().to_dict()}")

Taipei: mayor vs. city council votes

For Mayor vs. City Council Votes: Taipei, 2026 and its Chinese version. These scripts were written before the cleaning pipeline and read the government files directly, so they need only the four inputs below and, in the same folder, parse_votedata.py and ecoreg.py. They were revised on 1 December 2026 with the article: every estimate is now bounded and carries a 95% interval, and the village panel counts pan-green by ballot label in both years (see Method).

Inputs

RAW/2026/63000臺北市/縣表3-1-63000臺北市-115年臺北市縣市長選舉候選人在各投開票所得票數一覽表.xls    (mayor, by polling station)
RAW/2026/63000臺北市/縣表3-2-63000臺北市-115年臺北市縣市議員選舉候選人在各投開票所得票數一覽表.xls    (council, by polling station)
RAW/2022/mayor/   elbase.csv elcand.csv elctks.csv elpaty.csv elprof.csv   (選舉資料庫, 2022 直轄市長)
RAW/2022/council/ elbase.csv elcand.csv elctks.csv elpaty.csv elprof.csv   (選舉資料庫, 2022 直轄市議員)

The CEC names the 2026 files with the county in parentheses, 63000(臺北市); rename them as above. In the database download, the 2022 mayoral files are in voteData/2022-111年地方公職人員選舉/C1/prv and the council files in …/T1/prv.

Run

pip install pandas numpy xlrd matplotlib
python3 taipei_ballots.py RAW OUT        # parse_votedata.py and ecoreg.py in the same folder

# optional check for note 3 (after taipei_ballots.py; uses OUT/stations_2026.csv)
pip install pyei==1.1.4          # Python 3.10 or later
python3 taipei_ei_check.py OUT

The main script runs in under a minute; the optional check runs MCMC for several minutes. For the Chinese candidate names in fig 4, a CJK font such as Noto Sans CJK TC must be installed.

Outputs

File Contents Article section
results.md every figure quoted, grouped A–H all
fig1_camps.png council vote by party and camp vs mayoral vote opening chart; How did Shen compare with his camp?
fig2_tpp.png TPP council voters' mayoral choice, 2022 and 2026 Who did TPP voters back for mayor?
fig3_district_gaps.png mayoral share minus camp share, by district How did Shen compare with his camp?
fig4_daan.png Da’an council candidates; camps vs mayor same (Da’an paragraphs)
fig5_villages.png village swings, 2022→2026 same (village paragraphs)
stations_2026.csv, stations_2022.csv polling-station panels
villages_22_26.csv 456-village panel with swings and turnout
council_camps_2026.csv every 2026 council candidate with party, votes and camp Appendix table

Supplementary check, not part of the main analysis:

File Contents Article section
ei_check_results.md King EI and Goodman two-by-two estimates, pooled citywide and within districts, for four council-group → candidate tables note 3 (1998 comparison)

Method

Caveats

These are ecological estimates. They describe polling stations, not individual voters. The bounds keep them within 0–100%, but an estimate at a bound means only that the data push it there: the Miao-to-Shen estimate in district 6 is 1.00, where the unconstrained estimate was 1.20. The bootstrap intervals cover sampling error, not aggregation bias. Cross-election estimates compare two different electorates and are rougher still.

Files

taipei_ballots.py

"""Reproduce every figure and chart in "Comparing Mayoral and City Councillor Votes: Taipei, 2026".

Inputs (Central Election Commission):
  2026: polling-station tables 縣表3-1 (mayor) and 縣表3-2 (council), .xls, in RAW/2026/63000臺北市/
  2022: CEC 選舉資料庫 CSVs (elbase, elcand, elctks, elpaty, elprof) in RAW/2022/mayor/ and RAW/2022/council/
Outputs (in OUT/):
  results.md          every number quoted in the article, with the step that produces it
  stations_2026.csv, stations_2022.csv, villages_22_26.csv, council_camps_2026.csv
  fig1_camps.png ... fig5_villages.png

usage: python3 taipei_ballots.py RAW_DIR OUT_DIR
Requires pandas, numpy, xlrd, matplotlib.
"""
import sys, os
from collections import defaultdict
import numpy as np
import pandas as pd
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from parse_votedata import rows, parties

RAW, OUT = (sys.argv[1], sys.argv[2]) if len(sys.argv) > 2 else ('data', 'repro_out')
os.makedirs(OUT, exist_ok=True)
X26 = f'{RAW}/2026/63000臺北市'
MAYOR26 = f'{X26}/縣表3-1-63000臺北市-115年臺北市縣市長選舉候選人在各投開票所得票數一覽表.xls'
COUNCIL26 = f'{X26}/縣表3-2-63000臺北市-115年臺北市縣市議員選舉候選人在各投開票所得票數一覽表.xls'
GENERAL = range(1, 7)          # six general council districts; 7-8 are single-seat indigenous districts
DNAME = {1: 'Beitou–Shilin', 2: 'Neihu–Nangang', 3: 'Songshan–Xinyi', 4: 'Zhongshan–Datong',
         5: 'Zhongzheng–Wanhua', 6: "Da’an–Wenshan"}
num = lambda v: 0 if pd.isna(v) or str(v).strip() == '' else int(float(str(v).replace(',', '')))
LOG = []
def say(s=''):
    print(s); LOG.append(s)

# ------------------------------------------------------------------ camp classification (appendix table)
# Independents were assigned from their reported political ties; see the article's appendix for sources.
GREEN_PARTIES = {'民主進步黨', '社會民主黨'}                                  # pan-green core
GREEN_SMALL = {'時代力量', '台灣基進', '台灣綠黨', '綠黨', '小民參政歐巴桑聯盟'}  # pan-green other
GREEN_IND = {'陳怡君', '朱政騏', '紀建漢'}       # DPP members suspended, expelled or quit to run
BLUE_PARTIES = {'中國國民黨', '台灣民眾黨'}                                  # pan-blue core
BLUE_IND = {'陳怡潔', '陳重文', '應佳妤', '徐立信'}  # ex-PFP legislator; ex-KMT councillor; KMT councillor's daughter; KMT until 2014
HSU = '徐立信'
MIAO = '苗博雅'

def camp(name, party):
    if party in GREEN_PARTIES: return 'G_core'
    if party in GREEN_SMALL or name in GREEN_IND: return 'G_other'
    if party in BLUE_PARTIES: return 'B_core'
    if party == '新黨' or name in BLUE_IND: return 'B_other'
    return 'U'

# ------------------------------------------------------------------ 1. load 2026 polling-station tables
def load2026():
    st = defaultdict(lambda: defaultdict(float)); cands = []
    for d in GENERAL:
        x = pd.read_excel(COUNCIL26, sheet_name=f'第{d}選舉區', header=None, dtype=str); hdr = x.iloc[2]
        cols = [c for c in range(3, x.shape[1]) if isinstance(hdr[c], str) and '\n' in hdr[c]]
        info = {c: hdr[c].split('\n') for c in cols}           # [ballot no., name, party]
        for c in cols:
            cands.append(dict(dist=d, name=info[c][1].split(' ')[0], party=info[c][2]))
        town = None
        for _, r in x.iloc[5:].iterrows():
            if pd.notna(r[0]): town = r[0].strip()
            if pd.isna(r[1]) or pd.isna(r[2]): continue
            s = st[int(float(r[2]))]; s['dist'] = d; s['town'] = town; s['village'] = r[1].strip()
            for c in cols:
                v = num(r[c]); nm, p = info[c][1].split(' ')[0], info[c][2]
                s['c_valid'] += v; s['c_' + camp(nm, p)] += v
                s['c_KMT'] += v * (p == '中國國民黨'); s['c_TPP'] += v * (p == '台灣民眾黨')
                s['c_DPP'] += v * (p == '民主進步黨'); s['c_SDP'] += v * (p == '社會民主黨')
                s['c_HSU'] += v * (nm == HSU); s['c_MIAO'] += v * (nm == MIAO)
                s['c_GLAB'] += v * (p in GREEN_PARTIES or p in GREEN_SMALL)     # pan-green by ballot label only (village panel)
                s['cand_' + nm] += v
    x = pd.read_excel(MAYOR26, sheet_name='臺北市', header=None, dtype=str); hdr = x.iloc[2]
    cols = [c for c in range(3, x.shape[1]) if isinstance(hdr[c], str) and '\n' in hdr[c]]
    for _, r in x.iloc[5:].iterrows():
        if pd.isna(r[1]) or pd.isna(r[2]): continue
        s = st[int(float(r[2]))]
        for c in cols:
            p = hdr[c].split('\n')[2]; v = num(r[c])
            s['m_valid'] += v; s['m_KMT'] += v * (p == '中國國民黨'); s['m_DPP'] += v * (p == '民主進步黨')
        s['m_cast'] = num(r[cols[-1] + 3]); s['electors'] = num(r[cols[-1] + 7])   # C 投票數, G 選舉人數
    df = pd.DataFrame([dict(station=k, **v) for k, v in st.items()]).fillna(0)
    df = df[df.dist.isin(GENERAL)].copy()
    cdf = pd.DataFrame(cands)
    tot = df.filter(like='cand_').sum()
    cdf['votes'] = [tot.get('cand_' + n, 0) for n in cdf.name]; cdf['camp'] = [camp(n, p) for n, p in zip(cdf.name, cdf.party)]
    return df, cdf

# ------------------------------------------------------------------ 2. load 2022 CEC database
G22 = {'民主進步黨', '社會民主黨', '時代力量', '台灣基進', '綠黨', '台灣綠黨', '小民參政歐巴桑聯盟'}
def load2022():
    names = {(r[3], r[4]): r[5] for r in rows(f'{RAW}/2022/council/elbase.csv') if r[0] == '63'}
    st = defaultdict(lambda: defaultdict(float))
    pm = parties(f'{RAW}/2022/council')
    cand = {(r[2], int(r[5])): pm.get(r[7], '') for r in rows(f'{RAW}/2022/council/elcand.csv') if r[0] == '63'}
    for r in rows(f'{RAW}/2022/council/elctks.csv'):
        if r[0] != '63' or int(r[5]) == 0: continue
        s = st[int(r[5])]; p = cand[(r[2], int(r[6]))]; v = int(r[7])
        s['dist'] = int(r[2]); s['town'] = names[(r[3], '0000')]; s['village'] = names[(r[3], r[4])]
        s['c_valid'] += v; s['c_GREEN'] += v * (p in G22); s['c_TPP'] += v * (p == '台灣民眾黨')
        s['c_BLUE'] += v * (p in ('中國國民黨', '新黨')); s['c_DPP'] += v * (p == '民主進步黨')
        s['c_KMT'] += v * (p == '中國國民黨'); s['c_SDP'] += v * (p == '社會民主黨')
    pm = parties(f'{RAW}/2022/mayor')
    mc = {int(r[5]): (r[6], pm.get(r[7], '')) for r in rows(f'{RAW}/2022/mayor/elcand.csv') if r[0] == '63'}
    for r in rows(f'{RAW}/2022/mayor/elctks.csv'):
        if r[0] != '63' or int(r[5]) == 0: continue
        nm, p = mc[int(r[6])]; v = int(r[7]); s = st[int(r[5])]
        k = 'KMT' if p == '中國國民黨' else 'DPP' if p == '民主進步黨' else 'HUANG' if nm == '黃珊珊' else 'OTH'
        s['m_' + k] += v; s['m_valid'] += v
    for r in rows(f'{RAW}/2022/mayor/elprof.csv'):          # station rows: valid, invalid, cast, electors, ...
        if r[0] == '63' and r[4] != '0000' and r[5] != '0000':
            s = st[int(r[5])]; s['m_cast'] = int(r[8]); s['electors'] = int(r[9])
    df = pd.DataFrame([dict(station=k, **v) for k, v in st.items()]).fillna(0)
    df['c_REST'] = df.c_valid - df.c_GREEN - df.c_TPP - df.c_BLUE
    return df[df.dist.isin(GENERAL)].copy()

# ------------------------------------------------------------------ ecological regression (code/ecoreg.py)
# Within each council district, stations' outcome shares are regressed on their group shares with no intercept (Goodman's
# method), with each group's estimated shares bounded to 0-1 and summing to 1. Districts are combined with weights for
# the number of stations (villages for the village panel); 95% intervals from resampling stations within each district.
import ecoreg
def est(df, rows, cols, rden, cden, dist='dist', **kw):
    return ecoreg.within(df, rows, cols, rden, cden, dist=dist, **kw)
def ci(r, row, col):
    e, lo, hi = ecoreg.cell(r, row, col); return f'{e:.2f} [{lo:.2f}, {hi:.2f}]'
def dist_range(r, row, col):
    i, j = r['rows'].index(row), r['cols'].index(col)
    v = [b[k.index(row), j] for _, _, k, b in r['districts'] if row in k]
    return min(v), max(v)

pct = lambda a, b: 100 * a / b

# ================================================================== RUN
s26, cands26 = load2026(); s22 = load2022()
assert len(s26) == 1790, len(s26)
s26['m_OTH'] = s26.m_valid - s26.m_DPP - s26.m_KMT
s26.drop(columns=[c for c in s26 if c.startswith('cand_')]).to_csv(f'{OUT}/stations_2026.csv', index=False)
s22.to_csv(f'{OUT}/stations_2022.csv', index=False); cands26.to_csv(f'{OUT}/council_camps_2026.csv', index=False)
CV, MV = s26.c_valid.sum(), s26.m_valid.sum()
say('# Results: Comparing Mayoral and City Councillor Votes, Taipei 2026\n')
say(f'2026 valid votes: council {CV:,.0f}, mayor {MV:,.0f} (difference {MV-CV:,.0f} = {pct(MV-CV, CV):.1f}% of council); stations {len(s26)}')
say('Estimates: bounded ecological regression within council districts (code/ecoreg.py), point [95% interval].')

# ---- A. camps citywide and by district (opening chart and section "How did Shen compare with his camp?"; fig 1 and fig 3)
say('\n## A. Council vote by camp vs mayoral vote')
camps = {k: pct(s26['c_' + k].sum(), CV) for k in ['G_core', 'G_other', 'B_core', 'B_other', 'U']}
for k, v in camps.items(): say(f'  {k:8s} {v:6.2f}%')
G, B = camps['G_core'] + camps['G_other'], camps['B_core'] + camps['B_other']
shen, chiang = pct(s26.m_DPP.sum(), MV), pct(s26.m_KMT.sum(), MV)
kmt, tpp, dpp = (pct(s26[c].sum(), CV) for c in ('c_KMT', 'c_TPP', 'c_DPP'))
say(f'  pan-green {G:.1f}  Shen {shen:.1f}  gap {shen-G:+.1f}  |  pan-blue {B:.1f}  Chiang {chiang:.1f}  gap {chiang-B:+.1f}')
party = {k: pct(s26['c_' + k].sum(), CV) for k in ['DPP', 'SDP', 'G_other', 'U', 'B_other', 'TPP', 'KMT']}
say('  by party (fig 1): ' + '  '.join(f'{k} {v:.1f}' for k, v in party.items()))
say(f'  party only: DPP {dpp:.1f} (Shen lead {shen-dpp:+.1f}); KMT {kmt:.1f} (Chiang lead {chiang-kmt:+.1f}); TPP {tpp:.1f}')
dist = []
for d, z in s26.groupby('dist'):
    g = pct(z.c_G_core.sum() + z.c_G_other.sum(), z.c_valid.sum()); b = pct(z.c_B_core.sum() + z.c_B_other.sum(), z.c_valid.sum())
    sh, ch = pct(z.m_DPP.sum(), z.m_valid.sum()), pct(z.m_KMT.sum(), z.m_valid.sum())
    dist.append(dict(dist=d, green=g, blue=b, shen=sh, chiang=ch, shen_gap=sh - g, chiang_gap=ch - b))
dist = pd.DataFrame(dist); say(dist.round(1).to_string(index=False))
# sensitivity: the seven independents placed by reported ties (appendix table)
hsu = pct(s26.c_HSU.sum(), CV)
say(f'  Hsu Li-hsin unassigned: Shen gap {shen-G:+.1f}, Chiang gap {chiang-(B-hsu):+.1f}')
gi = pct(sum(s26['cand_' + n].sum() for n in GREEN_IND), CV); bi = pct(sum(s26['cand_' + n].sum() for n in BLUE_IND), CV)
say(f'  all seven independents unassigned: pan-green {G-gi:.1f}, pan-blue {B-bi:.1f}; Shen gap {shen-(G-gi):+.1f}, Chiang gap {chiang-(B-bi):+.1f}')
z5 = s26[s26.dist == 5]; cv5 = z5.c_valid.sum()
b5i = pct(sum(z5['cand_' + n].sum() for n in BLUE_IND), cv5)
say(f'  D5 with its two blue-leaning independents (Hsu, Ying) left out of the camps: Shen gap '
    f'{pct(z5.m_DPP.sum(), z5.m_valid.sum()) - pct(z5.c_G_core.sum() + z5.c_G_other.sum(), cv5 * (1 - b5i / 100)):+.1f}, '
    f'Chiang gap {pct(z5.m_KMT.sum(), z5.m_valid.sum()) - pct(z5.c_B_core.sum() + z5.c_B_other.sum() - cv5 * b5i / 100, cv5 * (1 - b5i / 100)):+.1f}')

# ---- B. camp loyalty, 2026
say('\n## B. Camp loyalty, 2026')
s26['c_G'] = s26.c_G_core + s26.c_G_other; s26['c_B'] = s26.c_B_core + s26.c_B_other
MC = ['m_DPP', 'm_KMT', 'm_OTH']
rB = est(s26, ['c_G', 'c_B', 'c_U'], MC, 'c_valid', 'm_valid')
say(f'  pan-green -> Shen {ci(rB, "c_G", "m_DPP")}, -> Chiang {ci(rB, "c_G", "m_KMT")}')
say(f'  pan-blue -> Chiang {ci(rB, "c_B", "m_KMT")}, -> Shen {ci(rB, "c_B", "m_DPP")}')
s26b = s26.copy(); s26b['c_GI'] = sum(s26b['cand_' + n] for n in GREEN_IND); s26b['c_BI'] = sum(s26b['cand_' + n] for n in BLUE_IND)
s26b['c_G2'] = s26b.c_G - s26b.c_GI; s26b['c_B2'] = s26b.c_B - s26b.c_BI; s26b['c_U2'] = s26b.c_U + s26b.c_GI + s26b.c_BI
r_ = est(s26b, ['c_G2', 'c_B2', 'c_U2'], MC, 'c_valid', 'm_valid', n_boot=0)
say(f'  with the seven independents unassigned: pan-green -> Shen {r_["est"][0, 0]:.3f}, pan-blue -> Chiang {r_["est"][1, 1]:.3f}')

# ---- C. TPP voters, 2022 and 2026 (section "Who did TPP voters back"; fig 2)
say('\n## C. TPP council voters -> mayoral candidates')
# groups: DPP, KMT, TPP, everyone else, plus SDP where it ran (party labels, not camps)
for df in (s26, s22): df['c_REST2'] = df.c_valid - df.c_DPP - df.c_SDP - df.c_KMT - df.c_TPP
GR = ['c_DPP', 'c_KMT', 'c_TPP', 'c_REST2', 'c_SDP']
rC = est(s26, GR, MC, 'c_valid', 'm_valid')
lo_, hi_ = dist_range(rC, 'c_TPP', 'm_KMT')
say(f'  2026: TPP -> Chiang {ci(rC, "c_TPP", "m_KMT")} (districts {lo_:.2f}-{hi_:.2f}), -> Shen {ci(rC, "c_TPP", "m_DPP")} (max {dist_range(rC, "c_TPP", "m_DPP")[1]:.2f}); all pan-blue -> Chiang {rB["est"][1, 1]:.2f}')
say(f'  2026 same regression: KMT -> Chiang {ci(rC, "c_KMT", "m_KMT")} (districts {dist_range(rC, "c_KMT", "m_KMT")[0]:.2f}-{dist_range(rC, "c_KMT", "m_KMT")[1]:.2f}), KMT -> Shen {ci(rC, "c_KMT", "m_DPP")}; DPP -> Chiang {ci(rC, "c_DPP", "m_KMT")}')
tpp_fig = {'2026': dict(Chiang=ecoreg.cell(rC, 'c_TPP', 'm_KMT')[0], Shen=ecoreg.cell(rC, 'c_TPP', 'm_DPP')[0])}
MC22 = ['m_KMT', 'm_DPP', 'm_HUANG', 'm_OTH']
r22t = est(s22, GR, MC22, 'c_valid', 'm_valid')
say(f'  2022: TPP -> Huang {ci(r22t, "c_TPP", "m_HUANG")} (districts {dist_range(r22t, "c_TPP", "m_HUANG")[0]:.2f}-{dist_range(r22t, "c_TPP", "m_HUANG")[1]:.2f}), Chiang {ci(r22t, "c_TPP", "m_KMT")}, Chen {ci(r22t, "c_TPP", "m_DPP")}')
tpp_fig['2022'] = dict(Chiang=ecoreg.cell(r22t, 'c_TPP', 'm_KMT')[0], Chen=ecoreg.cell(r22t, 'c_TPP', 'm_DPP')[0], Huang=ecoreg.cell(r22t, 'c_TPP', 'm_HUANG')[0])
G22 = ['c_TPP', 'c_BLUE', 'c_GREEN', 'c_REST']
r22 = est(s22, G22, MC22, 'c_valid', 'm_valid')

# ---- D. Hsu Li-hsin, Zhongzheng-Wanhua
say('\n## D. Zhongzheng–Wanhua (D5): Hsu Li-hsin')
z = s26[s26.dist == 5].copy(); z['c_B_noHSU'] = z.c_B - z.c_HSU
rD = est(z, ['c_G', 'c_B_noHSU', 'c_HSU', 'c_U'], MC, 'c_valid', 'm_valid')
say(f'  Hsu council share {pct(z.c_HSU.sum(), z.c_valid.sum()):.1f}%; Hsu voters -> Chiang {ci(rD, "c_HSU", "m_KMT")}, Shen {ci(rD, "c_HSU", "m_DPP")}; other pan-blue -> Shen {ci(rD, "c_B_noHSU", "m_DPP")}')

# ---- E. Da’an (fig 4)
say("\n## E. Da’an District (part of council district 6)")
z = s26[(s26.dist == 6)]; dz = z[z.town == '大安區']; cv = dz.c_valid.sum()
dcand = {c[5:]: dz[c].sum() for c in s26.columns if c.startswith('cand_') and dz[c].sum() > 0}
kmt_d = sorted(pct(v, cv) for n, v in dcand.items() if cands26.set_index('name').party.get(n) == '中國國民黨')
say(f"  Da’an council valid {cv:,.0f}; Miao {pct(dz.c_MIAO.sum(), cv):.1f}%; next best {sorted((pct(v, cv) for n, v in dcand.items() if n != MIAO))[-1]:.1f}%")
say(f'  KMT: {len(kmt_d)} candidates, {kmt_d[0]:.1f}-{kmt_d[-1]:.1f}%')
dB, dG = pct(dz.c_B.sum(), cv), pct(dz.c_G.sum(), cv)
say(f'  camps: blue {dB:.1f}, green {dG:.1f} | mayor: Chiang {pct(dz.m_KMT.sum(), dz.m_valid.sum()):.1f}, Shen {pct(dz.m_DPP.sum(), dz.m_valid.sum()):.1f}')
z = z.copy(); z['c_G_noMIAO'] = z.c_G - z.c_MIAO
rE = est(z, ['c_MIAO', 'c_G_noMIAO', 'c_B', 'c_U'], MC, 'c_valid', 'm_valid')
say(f'  Miao voters -> Shen (within district 6) {ci(rE, "c_MIAO", "m_DPP")}')
daan = dict(dcand=dcand, cv=cv, dB=dB, dG=dG, chiang=pct(dz.m_KMT.sum(), dz.m_valid.sum()), shen=pct(dz.m_DPP.sum(), dz.m_valid.sum()))

# ---- F. village panel 2022 -> 2026 (fig 5); pan-green by ballot label in both years
say('\n## F. Village panel, 2022 -> 2026 (pan-green by ballot label in both years)')
agg = dict(c_valid='sum', m_valid='sum', m_DPP='sum', m_KMT='sum', m_cast='sum', electors='sum', dist='first')
v22 = s22.groupby(['town', 'village']).agg(**{k: (k, f) for k, f in agg.items()}, c_GREEN=('c_GREEN', 'sum'), m_HUANG=('m_HUANG', 'sum'), c_TPP=('c_TPP', 'sum'))
v26 = s26.groupby(['town', 'village']).agg(**{k: (k, f) for k, f in agg.items()}, c_G=('c_G', 'sum'), c_GLAB=('c_GLAB', 'sum'))
for t in (v22, v26): t.index = pd.MultiIndex.from_tuples([(a, b.replace('台', '臺')) for a, b in t.index])
p = v22.join(v26, lsuffix='22', rsuffix='26', how='inner')
assert len(p) == len(v22) == len(v26) == 456, (len(p), len(v22), len(v26))
p['g22'] = p.c_GREEN / p.c_valid22; p['g26'] = p.c_GLAB / p.c_valid26; p['dg'] = p.g26 - p.g22
p['dg_res'] = p.c_G / p.c_valid26 - p.g22        # 2026 researched camp (first published version), for comparison
p['S22'] = p.m_DPP22 / p.m_valid22; p['S26'] = p.m_DPP26 / p.m_valid26; p['dS'] = p.S26 - p.S22
p['C22'] = p.m_KMT22 / p.m_valid22; p['C26'] = p.m_KMT26 / p.m_valid26; p['H22'] = p.m_HUANG / p.m_valid22
p['t22'] = p.m_cast22 / p.electors22; p['t26'] = p.m_cast26 / p.electors26; p['dt'] = p.t26 - p.t22
dm = lambda c: p[c] - p.groupby('dist26')[c].transform('mean')
say(f'  villages matched {len(p)}; Shen gain mean {100*p.dS.mean():.1f} pts (sd {100*p.dS.std():.1f}); green council gain mean {100*p.dg.mean():.1f} (sd {100*p.dg.std():.1f}); sd ratio {p.dg.std()/p.dS.std():.1f}')
say(f'  within-district: corr {np.corrcoef(dm("dg"), dm("dS"))[0,1]:.2f}, slope of Shen gain on green gain {np.polyfit(dm("dg"), dm("dS"), 1)[0]:.2f}, '
    f'of green gain on Shen gain {np.polyfit(dm("dS"), dm("dg"), 1)[0]:.2f}')
say(f'  (2026 researched camp, first version: green gain mean {100*p.dg_res.mean():.1f}, sd {100*p.dg_res.std():.1f}, within-district corr {np.corrcoef(dm("dg_res"), dm("dS"))[0,1]:.2f})')
X = np.column_stack([pd.get_dummies(p.dist26).to_numpy(float), p.dg, p.dt]); b_ = np.linalg.lstsq(X, p.dS, rcond=None)[0]
X2 = np.column_stack([pd.get_dummies(p.dist26).to_numpy(float), p.dS, p.dt]); b2 = np.linalg.lstsq(X2, p.dg, rcond=None)[0]
say(f'  with district fixed effects and turnout change: Shen gain on green gain {b_[-2]:.2f}, green gain on Shen gain {b2[-2]:.2f}')
dgE = p.c_GLAB / p.electors26 - p.c_GREEN / p.electors22; dSE = p.m_DPP26 / p.electors26 - p.m_DPP22 / p.electors22
say(f'  citywide, votes as shares of registered electors: green gain on Shen gain {np.polyfit(dSE, dgE, 1)[0]:.2f}')
for d, z in p.groupby('dist26'):
    say(f'   D{int(d)} {DNAME[int(d)]:18s} green council gain {100*z.dg.mean():5.1f}  Shen gain {100*z.dS.mean():5.1f}')
p.reset_index(names=['town', 'village']).to_csv(f'{OUT}/villages_22_26.csv', index=False)

# ---- G. Huang's 2022 voters
say('\n## G. Vivian Huang 2022')
cw = {g: s22[g].sum() / s22.c_valid.sum() for g in G22}
say('  2022 council group -> (Chiang, Chen, Huang): ' + '; '.join(f'{g[2:]} ({r22["est"][i, 0]:.2f}, {r22["est"][i, 1]:.2f}, {r22["est"][i, 2]:.2f})' for i, g in enumerate(G22)))
comp = {g: cw[g] * r22['est'][i, 2] for i, g in enumerate(G22)}; T = sum(comp.values())
say('  composition of Huang vote: ' + ', '.join(f'{g[2:]} {100*v/T:.0f}%' for g, v in comp.items()))
p['m_OTH22'] = p.m_valid22 - p.m_KMT22 - p.m_DPP22 - p.m_HUANG; p['m_O26'] = p.m_valid26 - p.m_KMT26 - p.m_DPP26
rows22 = ['m_KMT22', 'm_DPP22', 'm_HUANG', 'm_OTH22']
rG = est(p, rows22, ['m_KMT26', 'm_DPP26', 'm_O26'], 'm_valid22', 'm_valid26', dist='dist26')
for col, lab in (('m_KMT26', 'Chiang'), ('m_DPP26', 'Shen')):
    say(f'  2026 {lab} from 2022 (Chiang, Chen, Huang) voters: ' + ', '.join(ci(rG, r, col) for r in rows22[:3]))

# ---- H. turnout
say('\n## H. Turnout')
say(f'  turnout 2022 {pct(p.m_cast22.sum(), p.electors22.sum()):.1f}% (electors {p.electors22.sum():,.0f}), 2026 {pct(p.m_cast26.sum(), p.electors26.sum()):.1f}% (electors {p.electors26.sum():,.0f})')
say(f'  within-district corr(turnout change, green council gain) {np.corrcoef(dm("dt"), dm("dg"))[0,1]:.2f}; (turnout change, Shen gain) {np.corrcoef(dm("dt"), dm("dS"))[0,1]:.2f}, slope {np.polyfit(dm("dt"), dm("dS"), 1)[0]:.2f}')
p['A22'] = p.electors22 - p.m_valid22; p['R26'] = p.electors26 - p.m_KMT26 - p.m_DPP26   # non-voters + invalid; everything but the two
rows_e = rows22 + ['A22']
rH = est(p, rows_e, ['m_KMT26', 'm_DPP26', 'R26'], 'electors22', 'electors26', dist='dist26')
for col, lab in (('m_KMT26', 'Chiang'), ('m_DPP26', 'Shen')):
    say(f'  electorate model, 2026 {lab} from 2022 (Chiang, Chen, Huang, non-voters): ' + ', '.join(ci(rH, r, col) for r in ('m_KMT22', 'm_DPP22', 'm_HUANG', 'A22')))

open(f'{OUT}/results.md', 'w').write('\n'.join(LOG) + '\n')

# ================================================================== FIGURES
import matplotlib; matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 10, 'axes.spines.top': False, 'axes.spines.right': False})
GREEN, SDPROSE, LGREEN, BLUE, LBLUE, GREY, TEAL = '#1b7a3a', '#d6336c', '#8cc79a', '#1f4e9c', '#93b3e0', '#b0b0b0', '#2a9a9a'
CAP = 'Source: Central Election Commission polling-station results'

# fig 1: council vote by party, camp totals, mayoral vote (opening chart)
def hbar(ax, y, segs, minlab=3.5):
    x0 = 0
    for v, c, nm in segs:
        ax.barh(y, v, left=x0, height=0.62, color=c, edgecolor='white', label=nm)
        if v >= minlab: ax.text(x0 + v / 2, y, f'{v:.1f}%' if v >= 7 else f'{v:.1f}', ha='center', va='center', color='white', fontsize=9)
        x0 += v
fig, ax = plt.subplots(figsize=(7.5, 3.4))
hbar(ax, 0, [(party['DPP'], GREEN, 'DPP · Shen'), (party['SDP'], SDPROSE, 'SDP (Miao Poya)'), (party['G_other'], LGREEN, 'other pan-green'),
             (party['U'], GREY, 'unaligned · other mayoral'), (party['B_other'], LBLUE, 'other pan-blue'), (party['TPP'], TEAL, 'TPP'), (party['KMT'], BLUE, 'KMT · Chiang')])
hbar(ax, 1, [(shen, GREEN, None), (100 - shen - chiang, GREY, None), (chiang, BLUE, None)])
ax.plot([0, G], [0.5, 0.5], color=GREEN, lw=1.5, clip_on=False); ax.plot([100 - B, 100], [0.5, 0.5], color=BLUE, lw=1.5, clip_on=False)
ax.text(0.3, 0.53, f'pan-green {G:.1f}%', va='top', fontsize=8, color='#555'); ax.text(99.7, 0.53, f'pan-blue {B:.1f}%', va='top', ha='right', fontsize=8, color='#555')
h, l = ax.get_legend_handles_labels(); keep = [(hh, ll) for hh, ll in zip(h, l) if ll and not ll.startswith('_')]
ax.legend(*zip(*keep), frameon=False, fontsize=7, ncol=4, loc='upper center', bbox_to_anchor=(0.5, -0.22))
ax.set_yticks([0, 1], ['Council vote', 'Mayoral vote']); ax.set_ylim(1.45, -0.45); ax.set_xlim(0, 100); ax.set_xticks([0, 50, 100], ['0', '50', '100%'])
ax.spines['left'].set_visible(False); ax.tick_params(axis='y', length=0)
ax.set_title("Each mayoral candidate won about his camp's council vote", loc='left', fontsize=11)
fig.text(0.01, 0.01, CAP + ' · six general council districts', fontsize=7, color='grey'); fig.tight_layout(rect=(0, 0.04, 1, 1))
fig.savefig(f'{OUT}/fig1_camps.png', dpi=200); plt.close(fig)

# fig 2: TPP council voters (each bar scaled to full width, as on the page)
fig, ax = plt.subplots(figsize=(7, 3))
yrs = [('2022 (TPP backed Huang)', [(tpp_fig['2022']['Chen'], GREEN, 'DPP candidate'), (tpp_fig['2022']['Huang'], TEAL, 'Huang'), (tpp_fig['2022']['Chiang'], BLUE, 'Chiang')]),
       ('2026 (no TPP candidate)', [(tpp_fig['2026']['Shen'], GREEN, 'DPP candidate'), (tpp_fig['2026']['Chiang'], BLUE, 'Chiang')])]
seen = set()
for i, (lab, segs) in enumerate(yrs):
    tot = sum(max(v, 0) for v, _, _ in segs); x0 = 0
    for v, c, nm in segs:
        raw = max(v, 0) * 100; w = raw / tot
        ax.barh(i, w, left=x0, color=c, edgecolor='white', label=None if nm in seen else nm); seen.add(nm)
        if raw >= 10: ax.text(x0 + w / 2, i, f'{raw:.0f}%', ha='center', va='center', color='white', fontsize=9)
        elif raw >= 5: ax.text(x0 + w / 2, i, f'{raw:.0f}', ha='center', va='center', color='white', fontsize=8)
        x0 += w
ax.set_yticks([0, 1], [y[0] for y in yrs]); ax.invert_yaxis(); ax.set_xlim(0, 100); ax.set_xticks([0, 50, 100], ['0', '50', '100%'])
ax.legend(frameon=False, fontsize=8, ncol=3, loc='upper center', bbox_to_anchor=(0.5, -0.2))
ax.set_title('TPP council voters followed their party', loc='left', fontsize=11)
fig.text(0.01, 0.01, CAP + ' · ecological regression by district; estimates scaled to full width', fontsize=7, color='grey'); fig.tight_layout(rect=(0, 0.04, 1, 1))
fig.savefig(f'{OUT}/fig2_tpp.png', dpi=200); plt.close(fig)

# fig 3: district gaps
fig, ax = plt.subplots(figsize=(6.5, 3.2)); yy = np.arange(len(dist))
ax.barh(yy - 0.2, dist.shen_gap, 0.4, color=GREEN, label='Shen − pan-green council')
ax.barh(yy + 0.2, dist.chiang_gap, 0.4, color=BLUE, label='Chiang − pan-blue council')
ax.axvline(0, color='black', lw=0.8); ax.set_xlim(-7, 7)
ax.set_yticks(yy, [f'D{d} {DNAME[d]}' for d in dist.dist]); ax.invert_yaxis(); ax.set_xlabel('percentage points')
ax.legend(frameon=False, fontsize=8, ncol=2, loc='lower center', bbox_to_anchor=(0.4, 1.0)); ax.set_title('Mayoral share minus camp council share, by district', loc='left', fontsize=11, pad=24)
fig.text(0.01, 0.01, CAP, fontsize=7, color='grey'); fig.tight_layout(rect=(0, 0.05, 1, 1))
fig.savefig(f'{OUT}/fig3_district_gaps.png', dpi=200); plt.close(fig)

# fig 4: Da’an
top = sorted(daan['dcand'].items(), key=lambda t: -t[1])[:10]
ctab = cands26.drop_duplicates('name').set_index('name')
SHORT = {'中國國民黨': 'KMT', '民主進步黨': 'DPP', '社會民主黨': 'SDP', '台灣民眾黨': 'TPP'}
fig, (a1, a2) = plt.subplots(1, 2, figsize=(8.5, 3.6), gridspec_kw={'width_ratios': [1.4, 1]})
for i, (nm, v) in enumerate(top):
    c = ctab.camp.get(nm, 'U'); a1.barh(i, pct(v, daan['cv']), color=GREEN if c.startswith('G') else BLUE if c.startswith('B') else GREY)
    a1.text(pct(v, daan['cv']) + 0.3, i, f"{pct(v, daan['cv']):.1f}%", va='center', fontsize=8)
a1.set_yticks(range(len(top)), [f"{n} {SHORT.get(ctab.party.get(n, ''), 'ind.')}" for n, _ in top], fontfamily='Noto Sans CJK TC'); a1.invert_yaxis()
a1.set_xlim(0, 23); a1.set_xticks([])
a1.spines['bottom'].set_visible(False); a1.set_title("Da’an council vote: top ten candidates", loc='left', fontsize=10)
hbar(a2, 0, [(daan['dG'], GREEN, 'pan-green / Shen'), (100 - daan['dG'] - daan['dB'], GREY, None), (daan['dB'], BLUE, 'pan-blue / Chiang')], minlab=10)
hbar(a2, 1, [(daan['shen'], GREEN, None), (100 - daan['shen'] - daan['chiang'], GREY, None), (daan['chiang'], BLUE, None)], minlab=10)
a2.set_yticks([0, 1], ['Council, by camp', 'Mayor']); a2.set_ylim(1.5, -0.5); a2.set_xlim(0, 100); a2.set_xticks([])
a2.spines['bottom'].set_visible(False); a2.spines['left'].set_visible(False); a2.tick_params(axis='y', length=0)
h, l = a2.get_legend_handles_labels(); keep = [(hh, ll) for hh, ll in zip(h, l) if ll and not ll.startswith('_')]
a2.legend(*zip(*keep), frameon=False, fontsize=8, ncol=2, loc='upper center', bbox_to_anchor=(0.5, -0.02))
a2.set_title("Camps and mayor in Da’an", loc='left', fontsize=10)
fig.text(0.01, 0.01, CAP + f" · council district 6, Da’an District subtotal ({daan['cv']:,.0f} valid votes)", fontsize=7, color='grey'); fig.tight_layout(rect=(0, 0.05, 1, 1))
fig.savefig(f'{OUT}/fig4_daan.png', dpi=200); plt.close(fig)

# fig 5: village swings (same district colours as the page)
fig, ax = plt.subplots(figsize=(5.5, 4.2))
PAL = ['#2f6db3', '#e08a1e', '#3a9a5b', '#c8102e', '#7d5bb5', '#8a6a4f']
for d, z in p.groupby('dist26'):
    ax.scatter(100 * z.dg, 100 * z.dS, s=10, color=PAL[int(d) - 1], alpha=0.75, label=f'D{int(d)} {DNAME[int(d)]}')
ax.axvline(0, color='grey', lw=0.8)
ax.set_xlabel('green council gain (points)'); ax.set_ylabel('Shen gain over 2022 (points)')
ax.legend(frameon=False, fontsize=7); ax.set_title('Village swings: uniform for mayor, varied for council', loc='left', fontsize=11)
fig.text(0.01, 0.01, CAP + ' · 456 villages (里)', fontsize=7, color='grey'); fig.tight_layout(rect=(0, 0.04, 1, 1))
fig.savefig(f'{OUT}/fig5_villages.png', dpi=200); plt.close(fig)
say(f'\nwrote {OUT}/results.md and 5 figures')

ecoreg.py

bounded regression; read by taipei_ballots.py and the Taiwan scripts
"""Bounded ecological regression (Goodman's method with the accounting constraints), with bootstrap intervals.

Used by the mayor/council analyses (taipei_ballots.py, allcounty_mayor_council.py, allcounty_extras.py). Needs numpy only.

Model. Within one council district, station i has council (or earlier-ballot) group shares x_i (R groups, summing to 1)
and outcome shares y_i (C outcomes, summing to 1). Goodman's regression assumes y_i = x_i B, with B[r, c] the share of
group r's voters choosing outcome c, and estimates B by least squares without an intercept. Unconstrained, a group's
estimates can fall below 0 or above 1. Here B minimizes the same sum of squared errors subject to each row of B lying on
the simplex (every rate between 0 and 1, each group's rates summing to 1). Where the unconstrained estimates are already
inside the bounds the two coincide.

Districts are combined with weights (the published pages use the number of stations; villages for the 2022-2026 panel),
averaging each group over the districts where it is estimated. Intervals: stations resampled with replacement within
each district (n_boot resamples, fixed seed), the combined figure recomputed each time, 2.5th and 97.5th percentiles.
Estimates describe polling stations in aggregate, not individual voters.
"""
import numpy as np

N_BOOT, SEED = 200, 1


def _proj_simplex(V):
    """Euclidean projection of every vector along the last axis onto the probability simplex."""
    U = -np.sort(-V, axis=-1)
    css = np.cumsum(U, axis=-1) - 1
    k = np.arange(1, V.shape[-1] + 1)
    rho = (U - css / k > 0).sum(-1) - 1
    theta = np.take_along_axis(css, rho[..., None], -1) / (rho[..., None] + 1)
    return np.maximum(V - theta, 0)


def _fit_batch(XtX, XtY, tol=1e-10, max_iter=100000):
    """FISTA with adaptive restart for min tr(B'XtX B) - 2 tr(B'XtY), rows of B on the simplex; batched over axis 0."""
    L = 2 * np.linalg.eigvalsh(XtX)[:, -1][:, None, None] + 1e-12
    B = np.full(XtY.shape, 1 / XtY.shape[-1]); Z = B.copy(); t = np.ones((len(XtX), 1, 1))
    for _ in range(max_iter):
        G = 2 * (XtX @ Z - XtY)
        Bn = _proj_simplex(Z - G / L)
        restart = ((Z - Bn) * (Bn - B)).sum((1, 2), keepdims=True) > 0     # O'Donoghue-Candes gradient restart
        t = np.where(restart, 1.0, t)
        tn = (1 + np.sqrt(1 + 4 * t * t)) / 2
        Z = Bn + (t - 1) / tn * (Bn - B)
        done = np.abs(Bn - B).max() < tol
        B, t = Bn, tn
        if done: break
    return B


def bounded(X, Y):
    """X: n x R group shares, Y: n x C outcome shares. Returns the R x C bounded estimate."""
    return _fit_batch((X.T @ X)[None], (X.T @ Y)[None])[0]


def bounded_boot(X, Y, n_boot=N_BOOT, rng=None):
    """Point estimate and n_boot bootstrap estimates (stations resampled with replacement)."""
    rng = rng if rng is not None else np.random.default_rng(SEED)
    idx = rng.integers(0, len(X), (n_boot, len(X)))
    Xb, Yb = X[idx], Y[idx]
    return bounded(X, Y), _fit_batch(np.einsum('bnr,bns->brs', Xb, Xb), np.einsum('bnr,bnc->brc', Xb, Yb))


def goodman(X, Y):
    """Unconstrained Goodman estimates (least squares, no intercept), R x C, for comparison."""
    return np.linalg.lstsq(X, Y, rcond=None)[0]


def within(df, rows, cols, rden, cden, dist='dist', min_share=0.001, min_n=0, weight=None, n_boot=N_BOOT, seed=SEED):
    """Bounded estimates within each district, combined across districts.

    rows, cols: count columns of df; rows are divided by rden, cols by cden (each set should sum to its denominator).
    A group is dropped in a district where it is absent (mean share below min_share); the remaining shares are rescaled
    to sum to 1. Unlike unconstrained Goodman, groups with little variation need not be dropped: the bounds keep their
    estimates finite, and the bootstrap interval shows how little the data say about them. Districts with fewer than
    min_n units or fewer than two groups present are skipped. weight: column summed per district
    (default: number of units). n_boot=0 skips the intervals. Returns dict(est, lo, hi, goodman: R x C arrays (NaN for groups never estimated),
    boot: n_boot x R x C, districts: list of (district, n, groups kept, R x C estimate)).
    """
    rng = np.random.default_rng(seed)
    R, C = len(rows), len(cols)
    acc, accb, accg, w = np.zeros((R, C)), np.zeros((n_boot, R, C)), np.zeros((R, C)), np.zeros(R)
    parts = []
    for d, g in df.groupby(dist):
        if len(g) < min_n: continue
        X = np.column_stack([g[r].to_numpy(float) / g[rden].to_numpy(float) for r in rows])
        Y = np.column_stack([g[c].to_numpy(float) / g[cden].to_numpy(float) for c in cols])
        keep = [i for i in range(R) if X[:, i].mean() >= min_share]
        if len(keep) < 2: continue
        Xk = X[:, keep] / X[:, keep].sum(1, keepdims=True)          # renormalize after dropping (near-)absent groups
        b, bb = bounded_boot(Xk, Y, n_boot, rng) if n_boot else (bounded(Xk, Y), np.zeros((0, len(keep), C)))
        gm = goodman(X[:, keep], Y)
        n = float(len(g) if weight is None else g[weight].sum())
        for j, i in enumerate(keep):
            acc[i] += n * b[j]; accb[:, i] += n * bb[:, j]; accg[i] += n * gm[j]; w[i] += n
        parts.append((d, len(g), [rows[i] for i in keep], b))
    with np.errstate(invalid='ignore', divide='ignore'):
        est, boot, gm = acc / w[:, None], accb / w[None, :, None], accg / w[:, None]
    lo, hi = np.percentile(boot, [2.5, 97.5], axis=0) if n_boot else (np.full((R, C), np.nan),) * 2
    return dict(est=est, lo=lo, hi=hi, goodman=gm, boot=boot, districts=parts, rows=list(rows), cols=list(cols))


def cell(res, row, col):
    """(estimate, lo, hi) for one group and outcome."""
    i, j = res['rows'].index(row), res['cols'].index(col)
    return float(res['est'][i, j]), float(res['lo'][i, j]), float(res['hi'][i, j])

parse_votedata.py

read by taipei_ballots.py
"""Parse CEC 選舉資料庫 (elbase/elcand/elctks/elpaty/elprof) for one city into the same
JSON layout as parse_taipei.py. Seats per district come from the data (elprof 當選人數合計),
cross-checked against elected flags in elcand and elctks.
usage: parse_votedata.py COUNCIL_DIR MAYOR_DIR PRV_CODE OUT.json
"""
import csv, json, sys
from collections import defaultdict


def rows(path):
    with open(path, encoding='utf-8-sig', newline='') as f:
        for r in csv.reader(f):
            if r:
                yield [c.strip().lstrip("'").strip() for c in r]


def cand_counts(xs):
    """Two layouts seen: spec (2018) = total_c, total_e, c_m, c_f, e_m, e_f;
    2022 = c_m, c_f, total_c, e_m, e_f, total_e. Pick whichever is internally consistent."""
    a = [int(x) for x in xs]
    spec = a[0] == a[2] + a[3] and a[1] == a[4] + a[5]
    alt = a[2] == a[0] + a[1] and a[5] == a[3] + a[4]
    if spec and not alt:
        return dict(ncand=a[0], nelect=a[1])
    if alt and not spec:
        return dict(ncand=a[2], nelect=a[5])
    raise ValueError(('ambiguous elprof layout', xs))


def total3(xs):
    """of three counts (total, male, female in unknown order) return the total."""
    a = [int(x) for x in xs]
    for i in range(3):
        if a[i] == sum(a) - a[i]:
            return a[i]
    raise ValueError(xs)


def parties(d):
    return {r[0]: r[1] for r in rows(f'{d}/elpaty.csv')}


def load(d, prv):
    pmap = parties(d)
    cand = {}
    for r in rows(f'{d}/elcand.csv'):
        if r[0] != prv:
            continue
        key = (r[2], int(r[5]))  # (district, ballot no.)
        cand[key] = dict(no=int(r[5]), name=r[6], party=pmap.get(r[7], r[7]),
                         incumbent=r[13] == 'Y', elected_flag=r[14] in ('*', '!'))
    prof, tks, st_sum = {}, defaultdict(int), defaultdict(int)
    for r in rows(f'{d}/elprof.csv'):
        if r[0] == prv and r[2] != '00' and r[3] == '000' and r[4] == '0000' and int(r[5]) == 0:
            prof[r[2]] = dict(valid=int(r[6]), **cand_counts(r[11:17]))
    flag_tks = {}
    for r in rows(f'{d}/elctks.csv'):
        if r[0] != prv:
            continue
        k = (r[2], int(r[6]))
        if r[3] == '000' and r[4] == '0000' and int(r[5]) == 0:
            tks[k] = int(r[7])
            flag_tks[k] = r[9] in ('*', '!') if len(r) > 9 else False
        elif int(r[5]) != 0:
            st_sum[k] += int(r[7])  # polling-station level
    return cand, prof, tks, st_sum, flag_tks


def build(d, prv, district_level=True):
    cand, prof, tks, st_sum, flag_tks = load(d, prv)
    out = {}
    for dist, p in sorted(prof.items()):
        cs = [dict(c, votes=tks[k]) for k, c in cand.items() if k[0] == dist]
        assert len(cs) == p['ncand'], (dist, len(cs), p['ncand'])
        assert sum(c['votes'] for c in cs) == p['valid'], (dist, 'votes != valid')
        for k in [k for k in cand if k[0] == dist]:
            assert st_sum[k] == tks[k], (k, 'station sum mismatch', st_sum[k], tks[k])
            assert flag_tks[k] == cand[k]['elected_flag'], (k, 'elected flag mismatch')
        assert sum(c['elected_flag'] for c in cs) == p['nelect'], (dist, 'seat count mismatch')
        cs.sort(key=lambda c: -c['votes'])
        top = {c['no'] for c in cs[:p['nelect']]}
        for c in cs:
            c['share'] = c['votes'] / p['valid']
            c['elected'] = c['elected_flag']
            if c['elected'] != (c['no'] in top):
                print(f"NOTE {dist} #{c['no']} {c['name']}: elected flag differs from top-M rank", file=sys.stderr)
        out[dist] = dict(M=p['nelect'], valid=p['valid'], cands=cs)
    return out


if __name__ == '__main__':
    council_dir, mayor_dir, prv, outp = sys.argv[1:5]
    council = build(council_dir, prv)
    # mayor: city-level row has district '00'; load() keys by district code so use '00'
    cand, prof, tks, st_sum, flag = load(mayor_dir, prv)
    mprof = None
    for r in rows(f'{mayor_dir}/elprof.csv'):
        if r[0] == prv and r[2] == '00' and r[3] == '000' and r[4] == '0000' and int(r[5]) == 0:
            mprof = dict(valid=int(r[6]))
    mc = []
    for k, c in cand.items():
        v = sum(int(r[7]) for r in rows(f'{mayor_dir}/elctks.csv')
                if r[0] == prv and r[2] == '00' and r[3] == '000' and r[4] == '0000' and int(r[5]) == 0 and int(r[6]) == k[1])
        mc.append(dict(c, votes=v, share=v / mprof['valid']))
    assert sum(c['votes'] for c in mc) == mprof['valid'], 'mayor votes != valid'
    json.dump({'council': {f'第{int(k)}選舉區': dict(v, name=f'D{int(k)}') for k, v in council.items()},
               'mayor': dict(valid=mprof['valid'], cands=mc)},
              open(outp, 'w'), ensure_ascii=False, indent=1)
    for k, v in council.items():
        print(k, 'M=', v['M'], 'cands', len(v['cands']), 'valid', v['valid'])
    for c in sorted(mc, key=lambda c: -c['votes']):
        print('MAYOR', c['name'], c['party'], c['votes'], f"{100*c['share']:.2f}%")

expected output: OUT/results.md

# Results: Comparing Mayoral and City Councillor Votes, Taipei 2026

2026 valid votes: council 1,428,565, mayor 1,454,408 (difference 25,843 = 1.8% of council); stations 1790
Estimates: bounded ecological regression within council districts (code/ecoreg.py), point [95% interval].

## A. Council vote by camp vs mayoral vote
  G_core    42.31%
  G_other    2.75%
  B_core    49.55%
  B_other    4.74%
  U          0.65%
  pan-green 45.1  Shen 45.7  gap +0.6  |  pan-blue 54.3  Chiang 53.7  gap -0.6
  by party (fig 1): DPP 38.7  SDP 3.6  G_other 2.7  U 0.7  B_other 4.7  TPP 9.2  KMT 40.3
  party only: DPP 38.7 (Shen lead +7.0); KMT 40.3 (Chiang lead +13.4); TPP 9.2
 dist  green  blue  shen  chiang  shen_gap  chiang_gap
    1   47.1  51.2  49.6    49.8       2.6        -1.4
    2   44.7  55.2  44.3    55.1      -0.4        -0.1
    3   44.4  55.0  43.9    55.6      -0.5         0.6
    4   50.7  49.0  50.3    49.0      -0.4        -0.0
    5   40.1  59.3  45.7    53.7       5.6        -5.6
    6   43.2  56.4  41.4    58.0      -1.8         1.7
  Hsu Li-hsin unassigned: Shen gap +0.6, Chiang gap +0.8
  all seven independents unassigned: pan-green 44.2, pan-blue 51.2; Shen gap +1.5, Chiang gap +2.5
  D5 with its two blue-leaning independents (Hsu, Ying) left out of the camps: Shen gap -0.5, Chiang gap +0.5

## B. Camp loyalty, 2026
  pan-green -> Shen 0.93 [0.91, 0.94], -> Chiang 0.07 [0.06, 0.08]
  pan-blue -> Chiang 0.92 [0.91, 0.93], -> Shen 0.07 [0.06, 0.08]
  with the seven independents unassigned: pan-green -> Shen 0.937, pan-blue -> Chiang 0.935

## C. TPP council voters -> mayoral candidates
  2026: TPP -> Chiang 0.90 [0.86, 0.93] (districts 0.81-0.98), -> Shen 0.09 [0.06, 0.13] (max 0.17); all pan-blue -> Chiang 0.92
  2026 same regression: KMT -> Chiang 0.95 [0.94, 0.96] (districts 0.92-0.98), KMT -> Shen 0.04 [0.03, 0.05]; DPP -> Chiang 0.06 [0.05, 0.07]
  2022: TPP -> Huang 0.77 [0.72, 0.80] (districts 0.26-1.00), Chiang 0.17 [0.14, 0.20], Chen 0.06 [0.03, 0.10]

## D. Zhongzheng–Wanhua (D5): Hsu Li-hsin
  Hsu council share 11.0%; Hsu voters -> Chiang 0.77 [0.73, 0.81], Shen 0.20 [0.17, 0.25]; other pan-blue -> Shen 0.07 [0.06, 0.08]

## E. Da’an District (part of council district 6)
  Da’an council valid 156,634; Miao 19.7%; next best 8.6%
  KMT: 8 candidates, 4.7-8.6%
  camps: blue 55.4, green 44.3 | mayor: Chiang 55.7, Shen 43.8
  Miao voters -> Shen (within district 6) 1.00 [1.00, 1.00]

## F. Village panel, 2022 -> 2026 (pan-green by ballot label in both years)
  villages matched 456; Shen gain mean 13.7 pts (sd 1.6); green council gain mean 7.8 (sd 4.9); sd ratio 3.0
  within-district: corr 0.39, slope of Shen gain on green gain 0.21, of green gain on Shen gain 0.71
  (2026 researched camp, first version: green gain mean 8.7, sd 4.2, within-district corr 0.46)
  with district fixed effects and turnout change: Shen gain on green gain 0.22, green gain on Shen gain 0.72
  citywide, votes as shares of registered electors: green gain on Shen gain 0.75
   D1 Beitou–Shilin      green council gain  12.0  Shen gain  13.2
   D2 Neihu–Nangang      green council gain  11.4  Shen gain  15.2
   D3 Songshan–Xinyi     green council gain   8.8  Shen gain  13.5
   D4 Zhongshan–Datong   green council gain  -0.1  Shen gain  13.9
   D5 Zhongzheng–Wanhua  green council gain   4.0  Shen gain  13.4
   D6 Da’an–Wenshan      green council gain   8.9  Shen gain  13.5

## G. Vivian Huang 2022
  2022 council group -> (Chiang, Chen, Huang): TPP (0.18, 0.05, 0.76); BLUE (0.82, 0.03, 0.15); GREEN (0.02, 0.75, 0.22); REST (0.34, 0.27, 0.38)
  composition of Huang vote: TPP 28%, BLUE 25%, GREEN 31%, REST 17%
  2026 Chiang from 2022 (Chiang, Chen, Huang) voters: 0.93 [0.91, 0.95], 0.00 [0.00, 0.02], 0.54 [0.51, 0.57]
  2026 Shen from 2022 (Chiang, Chen, Huang) voters: 0.06 [0.04, 0.09], 1.00 [0.97, 1.00], 0.44 [0.41, 0.48]

## H. Turnout
  turnout 2022 67.7% (electors 2,026,769), 2026 72.1% (electors 2,031,431)
  within-district corr(turnout change, green council gain) -0.06; (turnout change, Shen gain) 0.10, slope 0.07
  electorate model, 2026 Chiang from 2022 (Chiang, Chen, Huang, non-voters): 0.92 [0.88, 0.94], 0.00 [0.00, 0.02], 0.48 [0.41, 0.55], 0.11 [0.08, 0.16]
  electorate model, 2026 Shen from 2022 (Chiang, Chen, Huang, non-voters): 0.01 [0.00, 0.03], 0.95 [0.91, 0.97], 0.48 [0.42, 0.53], 0.13 [0.10, 0.16]

taipei_ei_check.py

supplementary check for note 3
"""Supplementary check for note 3 of "Comparing Mayoral and City Councillor Votes: Taipei, 2026".

NOT PART OF THE MAIN ANALYSIS. Every estimate in the article's text and charts comes from
taipei_ballots.py (Goodman regressions estimated within council districts). This script only
backs one sentence in note 3: that a citywide King ecological-inference model, the set-up
Wu Yi-ming (2001) used for 1998, gives very different 2026 estimates from the within-district
method, because pooling across council districts with different candidate fields biases it.

It compares, for four two-by-two tables (council group -> mayoral candidate):
  A. King's EI (PyEI 'king99_pareto_modification'), all polling stations pooled citywide
  B. Goodman two-by-two regression, pooled citywide
  C. Goodman two-by-two regression, estimated within each council district (station-weighted)
The main analysis's multi-group, bounded, within-district estimates (since the 1 December 2026 revision) are listed for reference.

Input: OUT/stations_2026.csv written by taipei_ballots.py.  Output: OUT/ei_check_results.md
Usage:  pip install pyei==1.1.4      (pulls in PyMC/NumPyro; MCMC takes several minutes)
        python3 taipei_ei_check.py OUT
"""
import sys, time, warnings
import numpy as np, pandas as pd

warnings.filterwarnings('ignore')
OUT = sys.argv[1] if len(sys.argv) > 1 else 'repro_out'
DRAWS, CHAINS, SEED = 2000, 4, 1

s = pd.read_csv(f'{OUT}/stations_2026.csv')
s = s[(s.c_valid > 0) & (s.m_valid > 0)].copy()
s['c_GREEN'] = s.c_DPP + s.c_SDP + s.c_G_other
N = s.m_valid.values.astype(int)

RUNS = [  # label, council column, mayoral column, main-analysis estimate (taipei_ballots.py, results.md C/B)
    ('TPP council -> Chiang', 'c_TPP', 'm_KMT', '0.90'),
    ('KMT council -> Shen', 'c_KMT', 'm_DPP', '0.04'),
    ('KMT council -> Chiang', 'c_KMT', 'm_KMT', '0.95'),
    ('pan-green council -> Shen', 'c_GREEN', 'm_DPP', '0.93'),
]


def goodman2x2(x, y):
    return np.linalg.lstsq(np.column_stack([x, 1 - x]), y, rcond=None)[0][0]


def goodman_within(gc, mc):
    est, n = [], []
    for _, z in s.groupby('dist'):
        est.append(goodman2x2((z[gc] / z.c_valid).values, (z[mc] / z.m_valid).values)); n.append(len(z))
    return np.average(est, weights=n)


def king(gc, mc, label):
    from pyei.two_by_two import TwoByTwoEI
    import arviz as az
    X = np.clip((s[gc] / s.c_valid).values, 1e-4, 1 - 1e-4)
    T = np.clip((s[mc] / s.m_valid).values, 1e-4, 1 - 1e-4)
    ei = TwoByTwoEI(model_name='king99_pareto_modification', pareto_scale=15, pareto_shape=2)
    ei.fit(X, T, N, demographic_group_name=label, candidate_name='cand', draws=DRAWS, tune=DRAWS,
           chains=CHAINS, cores=CHAINS, random_seed=SEED, progressbar=False)
    b = np.asarray(ei.sampled_voting_prefs[0])
    rhat = float(az.rhat(b.reshape(CHAINS, -1)))
    return b.mean(), np.percentile(b, 2.5), np.percentile(b, 97.5), rhat


lines = ['# Supplementary check for note 3 (not part of the main analysis)', '',
         f'2026 polling stations: {len(s)}. King EI: PyEI king99_pareto_modification, {CHAINS} chains x {DRAWS} draws, seed {SEED}.', '',
         '| Two-by-two table | King EI, citywide (95% interval) [R-hat] | Goodman 2x2, citywide | Goodman 2x2, within districts | Main analysis (multi-group, bounded, within districts) |',
         '|---|---|---|---|---|']
for label, gc, mc, main in RUNS:
    t = time.time()
    k = king(gc, mc, label.split()[0])
    gcw = goodman2x2((s[gc] / s.c_valid).values, (s[mc] / s.m_valid).values)
    gw = goodman_within(gc, mc)
    lines.append(f'| {label} | {k[0]:.2f} ({k[1]:.2f}-{k[2]:.2f}) [{k[3]:.2f}] | {gcw:.2f} | {gw:.2f} | {main} |')
    print(lines[-1], f'({time.time() - t:.0f}s)', flush=True)

x = s.c_TPP / s.c_valid
lines += ['', f'TPP council share across stations: {x.min():.3f}-{x.max():.3f} (sd {x.std():.3f}); '
          f'correlation with KMT council share {np.corrcoef(x, s.c_KMT / s.c_valid)[0, 1]:.2f}.',
          '', 'Reading: King EI and Goodman agree when both pool citywide, and both move to the main analysis\'s values '
          'when estimated within council districts. The gap comes from pooling across districts whose candidate fields '
          'differ, not from the choice between King and Goodman. R-hat (in brackets) compares the four chains for the '
          'citywide rate; values well above 1.01 mean the chains disagree and that King estimate is unreliable on its own, '
          'though here it still matches the citywide Goodman figure. Note 3 cites only the KMT council -> Shen row.']
open(f'{OUT}/ei_check_results.md', 'w').write('\n'.join(lines) + '\n')
print(f'wrote {OUT}/ei_check_results.md')

expected output: OUT/ei_check_results.md

# Supplementary check for note 3 (not part of the main analysis)

2026 polling stations: 1790. King EI: PyEI king99_pareto_modification, 4 chains x 2000 draws, seed 1.

| Two-by-two table | King EI, citywide (95% interval) [R-hat] | Goodman 2x2, citywide | Goodman 2x2, within districts | Main analysis (multi-group, bounded, within districts) |
|---|---|---|---|---|
| TPP council -> Chiang | 0.23 (0.14-0.33) [1.21] | 0.25 | 0.94 | 0.90 |
| KMT council -> Shen | 0.15 (0.13-0.16) [1.04] | 0.17 | -0.03 | 0.04 |
| KMT council -> Chiang | 0.84 (0.82-0.85) [1.01] | 0.83 | 1.02 | 0.95 |
| pan-green council -> Shen | 0.93 (0.91-0.94) [1.15] | 0.91 | 0.93 | 0.93 |

TPP council share across stations: 0.024-0.214 (sd 0.026); correlation with KMT council share -0.37.

Reading: King EI and Goodman agree when both pool citywide, and both move to the main analysis's values when estimated within council districts. The gap comes from pooling across districts whose candidate fields differ, not from the choice between King and Goodman. R-hat (in brackets) compares the four chains for the citywide rate; values well above 1.01 mean the chains disagree and that King estimate is unreliable on its own, though here it still matches the citywide Goodman figure. Note 3 cites only the KMT council -> Shen row.

Taiwan: mayor vs. city council votes

For Mayor vs. City Council Votes: Taiwan, 2026. Runs on the cleaned tables above. Two analysis scripts produce every number on the page, in results.md and extras.md, and a third the robustness checks in the appendix (checks.md, checks.json); the two CSV files and ecoreg.py (listed in the Taipei section) must sit next to the scripts. Run from scratch in an empty folder, the cleaning and these steps reproduce the expected outputs below byte for byte.

Run

python3 allcounty_mayor_council.py CLEAN OUT/allcounty                        # party labels only
python3 allcounty_mayor_council.py CLEAN OUT/allcounty_researched --researched
python3 allcounty_extras.py CLEAN OUT/allcounty_researched
python3 checks_mayor_council.py CLEAN OUT/taipei OUT/allcounty_researched OUT/checks   # after taipei_ballots.py

Outputs

FileContentsArticle section
allcounty_researched/results.mdcounty table, camp loyalty and voter flows by county, with researched campsopening chart; cities; appendix table
allcounty_researched/extras.mdTPP voters by county, third candidates, sensitivity checks, special municipalities, change since 2022, council swing, races that changed hands, city and county averagesall four questions
allcounty/results.mdthe county table by party label aloneappendix
counties.csv, districts.csv, loyalty.csv, extras.jsonthe same figures as tables
checks/checks.md, checks/checks.jsonrobustness checks: district weights, classification of independents, party labels, effective number of candidates; for Taipei, the village panel under both definitions and with a turnout controlappendices of both articles

Method

Files

allcounty_mayor_council.py

"""Mayoral vs council votes in all 22 counties, 2026: "Taiwan 2026: Mayor vs Council".

usage: python3 allcounty_mayor_council.py CLEAN_DIR OUT_DIR [--researched]
  --researched: council candidates without a camp label take the camp in code/camps_council_2026.csv (researched,
                this cycle's evidence only; see council_research_merge.py). Default: party labels only.
Inputs: CLEAN_DIR/{elections,candidates,votes}/source=cec2026 (cec2026_clean.py); code/camps_executive.csv.
Outputs: OUT_DIR/results.md (every figure quoted on the page), counties.csv, districts.csv, loyalty.csv, page_data.json.

Definitions
  Council vote: every council ballot in the county (general and indigenous districts), so that it covers the same
    voters as the mayoral ballot.
  Camps (CLAUDE.md heuristic): official party labels. Pan-green = DPP, SDP, NPP, TSP, Green Party, Obasan, TSU.
    Pan-blue = KMT, New Party, PFP and, for 2026, TPP (kept visible as its own segment). Independents and all other
    parties = unaligned.
  Mayoral camps: party label; candidates without one placed by the standard-bearer rule (code/camps_executive.csv,
    column camp_race): a candidate takes a camp only as its sole standard-bearer in the race.
  Gap: a standard-bearer's mayoral share minus the camp's council share (percentage points of valid votes on each ballot).
  Two-camp gap: the green standard-bearer's share of the two standard-bearers' votes, minus pan-green's share of
    pan-green + pan-blue council votes (only where both camps have a standard-bearer).
  Loyalty (bounded ecological regression, code/ecoreg.py): within each general council district (8 stations or more),
    the stations' mayoral shares (green standard-bearer, blue standard-bearer, everyone else) are regressed on their
    council shares of pan-green, pan-blue and unaligned, with no intercept and each group's rates bounded to 0-1 and
    summing to 1; county figures weight districts by stations; 95% intervals from resampling stations (200 resamples).
    Columns *_goodman keep the unconstrained estimates for comparison. Stations are matched across the two ballots by
    county and station number.
"""
import sys, os, json
import numpy as np
import pandas as pd

CLEAN, OUT = sys.argv[1], sys.argv[2]
RESEARCHED = '--researched' in sys.argv[3:]
os.makedirs(OUT, exist_ok=True)
HERE = os.path.dirname(os.path.abspath(__file__))
GREEN = {'民主進步黨', '社會民主黨', '時代力量', '台灣基進', '綠黨', '台灣綠黨', '小民參政歐巴桑聯盟', '台聯黨', '台灣團結聯盟'}
BLUE = {'中國國民黨', '新黨', '親民黨', '台灣民眾黨'}
ENAME = {'09007': 'Lienchiang', '09020': 'Kinmen', '10002': 'Yilan', '10004': 'Hsinchu County', '10005': 'Miaoli',
         '10007': 'Changhua', '10008': 'Nantou', '10009': 'Yunlin', '10010': 'Chiayi County', '10013': 'Pingtung',
         '10014': 'Taitung', '10015': 'Hualien', '10016': 'Penghu', '10017': 'Keelung', '10018': 'Hsinchu City',
         '10020': 'Chiayi City', '63000': 'Taipei', '64000': 'Kaohsiung', '65000': 'New Taipei', '66000': 'Taichung',
         '67000': 'Tainan', '68000': 'Taoyuan'}
camp = lambda p: 'G' if p in GREEN else 'B' if p in BLUE else 'U'
LOG = []
def say(s=''):
    print(s); LOG.append(s)

rd = lambda t: pd.read_parquet(f'{CLEAN}/{t}/source=cec2026')
E, C, V = rd('elections'), rd('candidates'), rd('votes')
E['code'] = E.county.str[:5]
ex = E[E.office == 'executive'][['eid', 'code']]; co = E[E.office == 'council'][['eid', 'code']]
override = pd.read_csv(f'{HERE}/camps_executive.csv', dtype=str)
override = override[override.year == '2026'].assign(code=lambda d: d.county.str[:5]).set_index(['code', 'name']).camp_race
OV = {'pan_green': 'G', 'pan_blue': 'B', 'unaligned': 'U', 'third_force': 'T'}

# ---- mayoral candidates and camps
mc = C.merge(ex, on='eid')
mc['camp'] = [OV[override[(c, n)]] if (c, n) in override.index else camp(p) for c, n, p in zip(mc.code, mc.name_zh, mc.party)]
dup = mc[mc.camp.isin(['G', 'B'])].duplicated(['code', 'camp'], keep=False)
assert not dup.any(), mc[mc.camp.isin(['G', 'B'])][dup]
# ---- council candidates and camps
cc = C.merge(co, on='eid'); cc['camp'] = cc.party.map(camp); cc['tpp'] = cc.party == '台灣民眾黨'
if RESEARCHED:
    R = pd.read_csv(f'{HERE}/camps_council_2026.csv', dtype=str)
    R = R[R.camp.isin(['pan_green', 'pan_blue'])]
    key = dict(zip(R.county.str[:5] + '-' + R.dist.str.zfill(2) + '|' + R.name, R.camp.map({'pan_green': 'G', 'pan_blue': 'B'})))
    k = cc.race_id + '|' + cc.name
    hit = k.map(key)
    assert (cc.loc[hit.notna(), 'camp'] == 'U').all(), 'researched override on a labelled candidate'
    cc.loc[hit.notna(), 'camp'] = hit[hit.notna()]
    print(f'researched camps applied to {int(hit.notna().sum())} council candidates (of {len(R)} in the file)')
    # Taipei: the classification published on the Taipei page (taipei_ballots.py camp()), for all seven independents
    TPE = {'陳怡君': 'G', '朱政騏': 'G', '紀建漢': 'G', '陳怡潔': 'B', '陳重文': 'B', '應佳妤': 'B', '徐立信': 'B'}
    t = (cc.code == '63000') & cc.name_zh.isin(TPE) & (cc.party.map(camp) == 'U')
    assert t.sum() == len(TPE), t.sum()
    cc.loc[t, 'camp'] = cc.loc[t, 'name_zh'].map(TPE)
cc['kind'] = np.where(cc.seat_type.fillna('general') == 'general', 'general', 'indigenous')

# ---- station panel: mayoral votes by camp, council votes by camp (all council ballots), general district
mv = V.merge(ex, on='eid').merge(mc[['eid', 'no', 'camp', 'name_zh']], on=['eid', 'no'])
cv = V.merge(co, on='eid').merge(cc[['eid', 'race_id', 'no', 'camp', 'tpp', 'kind']], on=['eid', 'race_id', 'no'])
key = ['code', 'station']
M = mv.pivot_table(index=key, columns='camp', values='votes', aggfunc='sum', fill_value=0).add_prefix('m_')
M['m_valid'] = M.sum(axis=1)
K = cv.pivot_table(index=key, columns='camp', values='votes', aggfunc='sum', fill_value=0).add_prefix('c_')
K['c_valid'] = K.sum(axis=1)
K['c_TPP'] = cv[cv.tpp].groupby(key).votes.sum().reindex(K.index, fill_value=0)
gd = cv[cv.kind == 'general'].groupby(key).race_id.first().rename('dist')
S = M.join(K, how='outer').join(gd)
assert S.dist.notna().all() and S.m_valid.notna().all() and S.c_valid.notna().all(), 'stations do not match across ballots'
S = S.fillna(0).reset_index()
for c in ('m_G', 'm_B', 'm_U', 'c_G', 'c_B', 'c_U'):
    if c not in S: S[c] = 0

# ---- county table
rows = []
for code, z in S.groupby('code'):
    m = mc[mc.code == code]
    r = dict(code=code, county=ENAME[code], council_valid=int(z.c_valid.sum()), mayor_valid=int(z.m_valid.sum()))
    for k in 'GBU':
        r[f'c_{k}'] = 100 * z[f'c_{k}'].sum() / z.c_valid.sum()
        r[f'm_{k}'] = 100 * z[f'm_{k}'].sum() / z.m_valid.sum()
    r['c_TPP'] = 100 * z.c_TPP.sum() / z.c_valid.sum()
    r['has_G'] = (m.camp == 'G').any(); r['has_B'] = (m.camp == 'B').any()
    r['G_name'] = ', '.join(m[m.camp == 'G'].name_zh); r['B_name'] = ', '.join(m[m.camp == 'B'].name_zh)
    r['G_party'] = ', '.join(m[m.camp == 'G'].party); r['B_party'] = ', '.join(m[m.camp == 'B'].party)
    win = m.sort_values('total').iloc[-1]; r['winner'] = win.name_zh; r['winner_camp'] = win.camp
    r['gap_G'] = r['m_G'] - r['c_G'] if r['has_G'] else np.nan
    r['gap_B'] = r['m_B'] - r['c_B'] if r['has_B'] else np.nan
    if r['has_G'] and r['has_B']:
        r['two_G_mayor'] = 100 * r['m_G'] / (r['m_G'] + r['m_B']); r['two_G_council'] = 100 * r['c_G'] / (r['c_G'] + r['c_B'])
        r['two_gap'] = r['two_G_mayor'] - r['two_G_council']
    r['valid_diff_pct'] = 100 * (r['mayor_valid'] - r['council_valid']) / r['council_valid']
    r['stations'] = len(z)
    rows.append(r)
T = pd.DataFrame(rows)
# KMT-only council share (for reference)
kmt = cv[cv.eid.isin(co.eid)].merge(C[['eid', 'race_id', 'no', 'party']], on=['eid', 'race_id', 'no'])
kmt = kmt.assign(k=kmt.party == '中國國民黨', d=kmt.party == '民主進步黨')
T = T.merge(kmt.groupby('code').apply(lambda z: pd.Series({'c_KMT': 100 * z.votes[z.k].sum() / z.votes.sum(),
                                                           'c_DPP': 100 * z.votes[z.d].sum() / z.votes.sum()})).reset_index(),
            on='code')

# ---- bounded ecological regression within general districts (code/ecoreg.py)
sys.path.insert(0, HERE); import ecoreg
S['m_O'] = S.m_valid - S.m_G - S.m_B
L = []
for code, z in S.groupby('code'):
    t = T.set_index('code').loc[code]
    if not (t.has_G or t.has_B): continue
    r = ecoreg.within(z, ['c_G', 'c_B', 'c_U'], ['m_G', 'm_B', 'm_O'], 'c_valid', 'm_valid', min_n=8)
    if not r['districts']: continue
    for tgt in ('G', 'B'):
        if not t[f'has_{tgt}']: continue
        rr = dict(code=code, county=ENAME[code], target=tgt, districts=len(r['districts']), stations=int(sum(d[1] for d in r['districts'])))
        for g in ('c_G', 'c_B', 'c_U'):
            e, lo, hi = ecoreg.cell(r, g, f'm_{tgt}')
            rr[g], rr[g + '_lo'], rr[g + '_hi'] = e, lo, hi
            rr[g + '_goodman'] = float(r['goodman'][r['rows'].index(g), r['cols'].index(f'm_{tgt}')])
        L.append(rr)
L = pd.DataFrame(L)

# ---- district gaps (general districts; council = that district's ballots)
D = []
for (code, d), z in S.groupby(['code', 'dist']):
    t = T.set_index('code').loc[code]
    r = dict(code=code, county=ENAME[code], dist=d, stations=len(z), council_valid=int(z.c_valid.sum()))
    for k in 'GBU':
        r[f'c_{k}'] = 100 * z[f'c_{k}'].sum() / z.c_valid.sum(); r[f'm_{k}'] = 100 * z[f'm_{k}'].sum() / z.m_valid.sum()
    r['gap_G'] = r['m_G'] - r['c_G'] if t.has_G else np.nan; r['gap_B'] = r['m_B'] - r['c_B'] if t.has_B else np.nan
    D.append(r)
D = pd.DataFrame(D)

# ================================================================== report
say('# Results: Taiwan 2026, mayoral vs council votes (all 22 counties)\n')
say(f'Stations matched across ballots: {len(S):,} in 22 counties; general council districts: {D.shape[0]}')
say(f'Valid votes: mayor {T.mayor_valid.sum():,}, council (all districts) {T.council_valid.sum():,}; '
    f'difference by county {T.valid_diff_pct.min():+.1f}% to {T.valid_diff_pct.max():+.1f}% of council')
nat = {k: 100 * S[f'c_{k}'].sum() / S.c_valid.sum() for k in 'GBU'}; natm = {k: 100 * S[f'm_{k}'].sum() / S.m_valid.sum() for k in 'GBU'}
say(f"Nationwide council: pan-green {nat['G']:.1f}, pan-blue {nat['B']:.1f} (TPP {100*S.c_TPP.sum()/S.c_valid.sum():.1f}), unaligned {nat['U']:.1f}")
say(f"Nationwide mayoral: green standard-bearers {natm['G']:.1f}, blue standard-bearers {natm['B']:.1f}, others {natm['U']:.1f}")
say('\n## A. County table (percent of valid votes on each ballot; gaps in points)')
cols = ['county', 'c_G', 'c_B', 'c_TPP', 'c_U', 'm_G', 'm_B', 'm_U', 'gap_G', 'gap_B', 'two_gap', 'winner_camp', 'valid_diff_pct']
say(T.sort_values('c_U')[cols].round(1).to_string(index=False))
b = T[T.has_G & T.has_B]
say(f'\nTwo-standard-bearer races: {len(b)}; green gap mean {b.gap_G.mean():+.1f} (range {b.gap_G.min():+.1f} to {b.gap_G.max():+.1f}); '
    f'blue gap mean {b.gap_B.mean():+.1f} (range {b.gap_B.min():+.1f} to {b.gap_B.max():+.1f})')
say(f'Two-camp gap: mean {b.two_gap.mean():+.1f}, median {b.two_gap.median():+.1f}, range {b.two_gap.min():+.1f} to {b.two_gap.max():+.1f}; '
    f'positive (green ran ahead) in {(b.two_gap > 0).sum()} of {len(b)}; |gap| < 2 in {(b.two_gap.abs() < 2).sum()}')
r = np.corrcoef(b.c_U, b.gap_G + b.gap_B)[0, 1]
say(f'Correlation of unaligned council share with (green gap + blue gap): {r:.2f}; identity: gap_G + gap_B = c_U - m_U')
r2 = np.corrcoef(b.c_U, b.two_gap)[0, 1]; say(f'Correlation of unaligned council share with two-camp gap: {r2:.2f}')
say('\n## B. Loyalty (bounded ecological regression within general council districts, station-weighted)')
for tgt, lab in (('G', 'green standard-bearer'), ('B', 'blue standard-bearer')):
    z = L[L.target == tgt].set_index('county')
    say(f'  -> {lab}: ' + '; '.join(f"{c} G {r_.c_G:.2f} B {r_.c_B:.2f} U {r_.c_U:.2f}" for c, r_ in z.iterrows()))
say('\n## C. District gaps (general districts)')
for k in ('G', 'B'):
    z = D.dropna(subset=[f'gap_{k}'])
    say(f'  {k}: {len(z)} districts, mean {z[f"gap_{k}"].mean():+.1f}, sd {z[f"gap_{k}"].std():.1f}, within 3 points: {(z[f"gap_{k}"].abs() < 3).mean():.0%}')
t = T.set_index('county').loc['Taipei']
say(f"\n## D. Taipei by party label: pan-green {t.c_G:.1f}, pan-blue {t.c_B:.1f}, unaligned {t.c_U:.1f}; Shen {t.m_G:.1f} (gap {t.gap_G:+.1f}), Chiang {t.m_B:.1f} (gap {t.gap_B:+.1f})")
say('   (published Taipei page, independents researched: pan-green 45.1, pan-blue 54.3; gaps +0.6, -0.6)')
open(f'{OUT}/results.md', 'w').write('\n'.join(LOG) + '\n')
mcand = mv.pivot_table(index=key, columns='name_zh', values='votes', aggfunc='sum', fill_value=0).reset_index()
S.to_parquet(f'{OUT}/stations.parquet', index=False); mcand.to_parquet(f'{OUT}/stations_mayor_by_candidate.parquet', index=False)
T.to_csv(f'{OUT}/counties.csv', index=False); D.to_csv(f'{OUT}/districts.csv', index=False); L.to_csv(f'{OUT}/loyalty.csv', index=False)
json.dump(dict(counties=json.loads(T.round(2).to_json(orient='records', force_ascii=False)),
               loyalty=json.loads(L.round(3).to_json(orient='records', force_ascii=False)),
               districts=json.loads(D.round(2).to_json(orient='records', force_ascii=False))),
          open(f'{OUT}/page_data.json', 'w'), ensure_ascii=False)

allcounty_extras.py

"""Further analyses for "Taiwan 2026: Mayor vs Council", from allcounty_mayor_council.py output (researched camps).

usage: python3 allcounty_extras.py CLEAN_DIR ANALYSIS_DIR      (ANALYSIS_DIR = _data/output/allcounty_researched)
Output: ANALYSIS_DIR/extras.json and extras.md (every figure quoted from these sections)
  change22   two-camp shift in 2022 (same definition; TPP included with pan-blue and, separately, excluded) and the change
  tpp        TPP council voters' mayoral choice by county (bounded regression within general districts, TPP as its own group)
  splinter   where third candidates' votes came from (Hualien, Changhua, Penghu)
  sens       sensitivity checks: Hualien with Wei Chia-hsien counted pan-blue; Hsinchu County and Miaoli with the TPP left
             out of both camps; Penghu by party label vs researched camps
  muni       the six special municipalities: shifts and loyalty estimates
  ratings    Kharis Templeman's final pre-election ratings (blog, 15 Nov 2026) against the winners and margins
  council_swing  pan-green two-camp council share, 2022 and 2026, by party label
  flips      2022 and 2026 winners and margins (Chiayi City 2022 from the re-held election)
  groups     special municipalities vs other head-to-head races, averaged
"""
import sys, json, os
import numpy as np
import pandas as pd

CLEAN, A = sys.argv[1], sys.argv[2]
HERE = os.path.dirname(os.path.abspath(__file__))
S = pd.read_parquet(f'{A}/stations.parquet'); MC = pd.read_parquet(f'{A}/stations_mayor_by_candidate.parquet')
T = pd.read_csv(f'{A}/counties.csv', dtype={'code': str}).set_index('code')
L = pd.read_csv(f'{A}/loyalty.csv', dtype={'code': str})
LAB = pd.read_csv(f'{A}/../allcounty/counties.csv', dtype={'code': str}).set_index('code')
OUT, LOG = {}, []
def say(s=''):
    print(s); LOG.append(s)
sys.path.insert(0, HERE); import ecoreg
def within(z, rows, cols, min_n=8):
    """Bounded ecological regression within general districts (ecoreg.within); {(row, col): (estimate, lo, hi)}, #districts."""
    r = ecoreg.within(z, rows, cols, 'c_valid', 'm_valid', min_n=min_n)
    if not r['districts']: return {}, 0
    return {(g, c): ecoreg.cell(r, g, c) for g in rows for c in cols if not np.isnan(ecoreg.cell(r, g, c)[0])}, len(r['districts'])
S['c_Bk'] = S.c_B - S.c_TPP                      # pan-blue without the TPP
two = lambda g, b: 100 * g / (g + b)

# ---- change22: 2022 two-camp shift by county (CEC database; party labels; TPP not a 2026-style ally in 2022)
E = pd.read_parquet(f'{CLEAN}/elections/source=cecdb'); C = pd.read_parquet(f'{CLEAN}/candidates/source=cecdb')
e22 = E[(E.year == 2022) & E.office.isin(['executive', 'council'])][['eid', 'office']]
V = pd.read_parquet(f'{CLEAN}/votes/source=cecdb', filters=[('eid', 'in', e22.eid.tolist())]).merge(e22, on='eid')
V['code'] = V.prv + V.city
V = V.merge(C[C.eid.isin(e22.eid)][['eid', 'race_id', 'no', 'party']], on=['eid', 'race_id', 'no'])
GREEN = {'民主進步黨', '社會民主黨', '時代力量', '台灣基進', '綠黨', '台灣綠黨', '小民參政歐巴桑聯盟', '台聯黨', '台灣團結聯盟'}
grp = lambda p: 'G' if p in GREEN else 'K' if p in ('中國國民黨', '新黨', '親民黨') else 'T' if p == '台灣民眾黨' else 'U'
V['g'] = V.party.map(grp)
co = V[V.office == 'council'].pivot_table(index='code', columns='g', values='votes', aggfunc='sum', fill_value=0)
mx = V[V.office == 'executive']
# Chiayi City's 2022 mayoral race was re-held on 18 December 2022 (嘉義市長重行選舉) and sits in the by-election files
Eb = pd.read_parquet(f'{CLEAN}/elections/source=cec_byelection')
eb = Eb[(Eb.year == 2022) & (Eb.office == 'executive') & Eb.source.str.contains('嘉義市長重行選舉')].eid.tolist(); assert len(eb) == 1
Vb = pd.read_parquet(f'{CLEAN}/votes/source=cec_byelection', filters=[('eid', 'in', eb)])
Vb = Vb.merge(pd.read_parquet(f'{CLEAN}/candidates/source=cec_byelection')[['eid', 'race_id', 'no', 'party']], on=['eid', 'race_id', 'no'])
Vb['code'] = Vb.prv + Vb.city; assert (Vb.code == '10020').all() and '10020' not in set(mx.code)
mx = pd.concat([mx, Vb[['code', 'party', 'votes']]], ignore_index=True)
dpp = mx[mx.party == '民主進步黨'].groupby('code').votes.sum(); kmt = mx[mx.party == '中國國民黨'].groupby('code').votes.sum()
others22 = mx.groupby('code').apply(lambda z: 100 * z[~z.party.isin(['民主進步黨', '中國國民黨'])].votes.sum() / z.votes.sum())
rows = []
for code, t in T.iterrows():
    if code not in co.index or code not in dpp.index or code not in kmt.index or np.isnan(t.two_gap): continue
    c = co.loc[code]; m22 = two(dpp[code], kmt[code])
    s_in = m22 - two(c.G, c.K + c.get('T', 0)); s_ex = m22 - two(c.G, c.K)
    rows.append(dict(code=code, county=t.county, shift26=t.two_gap, shift22_tpp_in=s_in, shift22_tpp_out=s_ex,
                     change=t.two_gap - s_in, others22=others22[code]))
ch = pd.DataFrame(rows); ch['comparable'] = ch.others22 < 10            # 2022 a two-camp race (third candidates < 10%)
OUT['change22'] = ch.round(2).to_dict('records')
say('# Extras: Taiwan 2026 mayor vs council (researched camps)\n')
say('## Change in two-camp shift since 2022 (2022 TPP counted with pan-blue; comparable = third candidates under 10% in 2022)')
say(ch.sort_values('change').round(1).to_string(index=False))

# ---- tpp: where TPP council voters went
rows = []
for code, z in S.groupby('code'):
    tpp = z.c_TPP.sum() / z.c_valid.sum()
    if tpp < 0.01 or not T.loc[code, 'has_B']: continue
    r = dict(code=code, county=T.loc[code, 'county'], tpp_council=100 * tpp)
    est, n = within(z, ['c_G', 'c_Bk', 'c_TPP', 'c_U'], ['m_G', 'm_B', 'm_O'])
    for tgt in ('B', 'G'):
        if not T.loc[code, f'has_{tgt}'] or ('c_TPP', f'm_{tgt}') not in est: continue
        r[f'to_{tgt}'], r[f'lo_{tgt}'], r[f'hi_{tgt}'] = est[('c_TPP', f'm_{tgt}')]; r['districts'] = n
    rows.append(r)
tp = pd.DataFrame(rows).sort_values('tpp_council', ascending=False); tp['reliable'] = tp.tpp_council >= 3
OUT['tpp'] = tp.round(5).to_dict('records')
say('\n## TPP council voters -> mayoral candidates (bounded regression within general districts)'); say(tp.round(2).to_string(index=False))

# ---- splinter candidates
CAND = {'10015': ['魏嘉賢', '張峻', '游淑貞'], '10007': ['邱建富', '陳素月', '魏平政'], '10016': ['葉竹林', '吳淑瑾', '陳振中']}
rows = []
for code, names in CAND.items():
    z = S[S.code == code].merge(MC[MC.code == code], on=['code', 'station'])
    size = {g: z[g].sum() / z.c_valid.sum() for g in ('c_G', 'c_B', 'c_U')}
    z['m_rest'] = z.m_valid - z[names].sum(1)
    est, n = within(z, ['c_G', 'c_B', 'c_U'], names + ['m_rest'])
    for nm in names:
        tot = z[nm].sum() / z.m_valid.sum()
        rows.append(dict(code=code, county=T.loc[code, 'county'], name=nm, mayoral_share=100 * tot, districts=n,
                         **{f'rate_{g[2:]}': est.get((g, nm), (np.nan,))[0] for g in size},
                         halfwidth_max=max((v[2] - v[1]) / 2 for (g, c), v in est.items() if c == nm) if est else np.nan,
                         **{f'from_{g[2:]}': 100 * est.get((g, nm), (0,))[0] * size[g] / tot for g in size}))
sp = pd.DataFrame(rows); OUT['splinter'] = sp.round(5).to_dict('records')
say('\n## Third candidates: share of each council group backing them, and the implied make-up of their vote'); say(sp.round(2).to_string(index=False))

# ---- sensitivities
sens = {}
hl = T.loc['10015']; wei = 100 * MC[MC.code == '10015']['魏嘉賢'].sum() / S[S.code == '10015'].m_valid.sum()
sens['hualien_wei_blue'] = two(hl.m_G, hl.m_B + wei) - two(hl.c_G, hl.c_B)
for code in ('10004', '10005'):
    t = T.loc[code]; z = S[S.code == code]
    cG, cBk = z.c_G.sum(), z.c_Bk.sum()
    sens[f'{t.county}_tpp_out'] = two(t.m_G, t.m_B) - two(cG, cBk)
sens['penghu_label'] = LAB.loc['10016', 'two_gap']; sens['penghu_researched'] = T.loc['10016', 'two_gap']
OUT['sens'] = {k: round(float(v), 2) for k, v in sens.items()}
say('\n## Sensitivity checks'); [say(f'  {k}: {v:+.1f}') for k, v in sens.items()]

# ---- municipalities
MU = ['63000', '65000', '66000', '67000', '64000', '68000']
lo = L[L.code.isin(MU)].pivot_table(index='code', columns='target', values=['c_G', 'c_B', 'c_U'])
mu = pd.DataFrame({'county': T.loc[MU, 'county'], 'shift26': T.loc[MU, 'two_gap'], 'm_G': T.loc[MU, 'm_G'], 'c_G': T.loc[MU, 'c_G'],
                   'G_to_G': lo[('c_G', 'G')], 'B_to_G': lo[('c_B', 'G')], 'U_to_G': lo[('c_U', 'G')], 'B_to_B': lo[('c_B', 'B')]})
mu = mu.join(ch.set_index('code')[['shift22_tpp_in', 'change', 'comparable']])
OUT['muni'] = mu.reset_index().round(5).to_dict('records')
say('\n## Special municipalities'); say(mu.round(2).to_string())

# ---- Templeman ratings (final list, 15 Nov 2026) vs results
RT = {'Taipei': 'Leans KMT', 'New Taipei': 'Toss-up', 'Taichung': 'Leans KMT', 'Tainan': 'Safe DPP', 'Kaohsiung': 'Likely DPP',
      'Taoyuan': 'Likely KMT', 'Keelung': 'Toss-up', 'Hsinchu City': 'Leans IND', 'Hsinchu County': 'Toss-up', 'Miaoli': 'Safe KMT',
      'Changhua': 'Likely DPP', 'Nantou': 'Safe KMT', 'Yilan': 'Leans DPP', 'Hualien': 'Leans KMT', 'Taitung': 'Leans KMT',
      'Chiayi City': 'Likely DPP', 'Chiayi County': 'Safe DPP', 'Yunlin': 'Leans KMT', 'Pingtung': 'Leans DPP', 'Penghu': 'Toss-up',
      'Kinmen': 'Safe KMT', 'Lienchiang': 'Safe KMT'}
Cn = pd.read_parquet(f'{CLEAN}/candidates/source=cec2026'); En = pd.read_parquet(f'{CLEAN}/elections/source=cec2026')
m = Cn.merge(En[En.office == 'executive'][['eid', 'county']], on='eid'); m['share'] = 100 * m.total / m.groupby('county').total.transform('sum')
rows = []
for cty, g in m.sort_values('share', ascending=False).groupby('county'):
    a, b = g.iloc[0], g.iloc[1]; nm = T.loc[cty[:5], 'county']
    rows.append(dict(county=nm, rating=RT[nm], winner=a.name_zh, winner_party=a.party, margin=a.share - b.share, votes_margin=int(a.total - b.total)))
rt = pd.DataFrame(rows).sort_values('margin'); OUT['ratings'] = rt.round(2).to_dict('records')
say('\n## Templeman final ratings vs results'); say(rt.round(1).to_string(index=False))
# ---- council camp swing 2022 -> 2026 (party labels both years; TPP with pan-blue both years; two-camp share of the council vote)
cw = pd.DataFrame({'cg22': 100 * co.G / (co.G + co.K + co.get('T', 0))}).join(LAB[['county', 'c_G', 'c_B']], how='inner')
cw['cg26'] = 100 * cw.c_G / (cw.c_G + cw.c_B); cw['swing'] = cw.cg26 - cw.cg22
OUT['council_swing'] = cw.reset_index()[['code', 'county', 'cg22', 'cg26', 'swing']].round(2).to_dict('records')
say('\n## Council camp swing toward pan-green, 2022 -> 2026 (party labels; two-camp share)')
say(cw.sort_values('swing', ascending=False)[['county', 'cg22', 'cg26', 'swing']].round(1).to_string())
say(f'  median {cw.swing.median():.1f}; positive in {(cw.swing > 0).sum()} of {len(cw)}')
# ---- races that changed hands: 2022 winner's party and margins (points of valid votes)
w22 = mx.groupby(['code', 'party']).votes.sum().reset_index(); tot22 = w22.groupby('code').votes.sum()
w22 = w22.sort_values('votes', ascending=False).groupby('code')
fl = []
for code, g in w22:
    top = g.iloc[0]; dv = g[g.party == '民主進步黨'].votes.sum(); kv = g[g.party == '中國國民黨'].votes.sum()
    nm = T.loc[code, 'county']; r26 = rt.set_index('county').loc[nm]
    fl.append(dict(code=code, county=nm, winner22=top.party, margin22=100 * (top.votes - g.iloc[1].votes) / tot22[code],
                   dpp_minus_kmt22=100 * (dv - kv) / tot22[code], winner26=r26.winner_party, margin26=r26.margin,
                   camp26=T.loc[code, 'winner_camp']))
fl = pd.DataFrame(fl); fl['dpp22'] = fl.winner22 == '民主進步黨'; fl['dpp26'] = fl.camp26 == 'G'
OUT['flips'] = fl.round(2).to_dict('records')
say('\n## Races by 2022 and 2026 winner'); say(fl.round(1).to_string(index=False))
# ---- bars: council vote by group and mayoral vote (Taipei-page style), municipalities and contrast counties
Cc = Cn.merge(En[En.office == 'council'][['eid', 'county']], on='eid'); Cc['code'] = Cc.county.str[:5]
RC = pd.read_csv(f'{HERE}/camps_council_2026.csv', dtype=str)
rc = dict(zip(RC.county.str[:5] + '|' + RC.dist.str.zfill(2) + '|' + RC.name, RC.camp))
TPE7 = {'陳怡君': 'pan_green', '朱政騏': 'pan_green', '紀建漢': 'pan_green', '陳怡潔': 'pan_blue', '陳重文': 'pan_blue', '應佳妤': 'pan_blue', '徐立信': 'pan_blue'}
def seg(r):
    if r.party == '民主進步黨': return 'DPP'
    if r.party in GREEN: return 'G_other'
    if r.party == '中國國民黨': return 'KMT'
    if r.party == '台灣民眾黨': return 'TPP'
    if r.party in ('新黨', '親民黨'): return 'B_other'
    c = TPE7.get(r.name_zh) if r.code == '63000' else rc.get(f'{r.code}|{r.race_id[-2:]}|{r.name}')
    return {'pan_green': 'G_other', 'pan_blue': 'B_other'}.get(c, 'U')
Cc['seg'] = [seg(r) for r in Cc.itertuples()]
BARS = ['63000', '65000', '66000', '67000', '64000', '68000', '10009', '10015']
bars = []
for code in BARS:
    z = Cc[Cc.code == code]; tot = z.total.sum(); t = T.loc[code]
    bars.append(dict(code=code, county=t.county, **{k: 100 * z[z.seg == k].total.sum() / tot for k in ('DPP', 'G_other', 'U', 'B_other', 'TPP', 'KMT')},
                     m_G=t.m_G, m_U=t.m_U, m_B=t.m_B, c_G=t.c_G, c_B=t.c_B))
OUT['bars'] = pd.DataFrame(bars).round(2).to_dict('records')
check = pd.DataFrame(bars).set_index('county'); assert ((check.DPP + check.G_other - check.c_G).abs() < 0.05).all(), 'bar segments do not match camp shares'
say('\n## Council vote by group (municipalities and contrast counties)'); say(pd.DataFrame(bars).round(1).to_string(index=False))
# ---- loyalty across all two-camp races
Lg, Lb = L[L.target == 'G'].set_index('code'), L[L.target == 'B'].set_index('code')
loy = pd.DataFrame([dict(code=c, county=T.loc[c, 'county'], muni=c in ('63000', '64000', '65000', '66000', '67000', '68000'), c_U=T.loc[c, 'c_U'],
                         GG=Lg.loc[c, 'c_G'], BB=Lb.loc[c, 'c_B'], BG=Lg.loc[c, 'c_B'], GB=Lb.loc[c, 'c_G']) for c in T.index if c in Lg.index and c in Lb.index])
loy['loyal'] = (loy.GG + loy.BB) / 2; loy['cross'] = (loy.BG + loy.GB) / 2
OUT['loyal'] = loy.round(5).to_dict('records')
say('\n## Loyalty: mean of pan-green->green and pan-blue->blue; crossover: mean of the two crossovers')
say(loy.sort_values('loyal', ascending=False).round(2).to_string(index=False))
say(f"  means: municipalities loyalty {loy[loy.muni].loyal.mean():.3f}, crossover {loy[loy.muni].cross.mean():.3f}, unaligned {loy[loy.muni].c_U.mean():.1f}; "
    f"others {loy[~loy.muni].loyal.mean():.3f}, {loy[~loy.muni].cross.mean():.3f}, {loy[~loy.muni].c_U.mean():.1f}; corr(unaligned, loyalty) {np.corrcoef(loy.c_U, loy.loyal)[0, 1]:.2f}")
# ---- groups: special municipalities vs other head-to-head races (third candidates under 10% of the mayoral vote)
h2h = loy.merge(T[['county', 'm_U', 'c_G', 'c_B', 'm_G', 'm_B']].reset_index(drop=True), on='county')
h2h = h2h[h2h.m_U < 10].copy(); h2h['grp'] = np.where(h2h.muni, 'cities', 'counties')
h2h['G_other'] = 1 - h2h.GG - h2h.GB; h2h['B_other'] = 1 - h2h.BB - h2h.BG
gr = h2h.groupby('grp')[['c_G', 'c_U', 'c_B', 'm_G', 'm_U', 'm_B', 'GG', 'GB', 'G_other', 'BB', 'BG', 'B_other', 'loyal', 'cross']].mean()
gr['n'] = h2h.groupby('grp').size(); gr['members'] = h2h.groupby('grp').county.agg(', '.join)
OUT['groups'] = gr.reset_index().round(5).to_dict('records')
say('\n## Special municipalities vs other head-to-head races (simple means across races)'); say(gr.round(3).to_string())
json.dump(OUT, open(f'{A}/extras.json', 'w'), ensure_ascii=False, default=float)
open(f'{A}/extras.md', 'w').write('\n'.join(LOG) + '\n')

camps_executive.csv

mayoral candidates without a party label
year,county,name,party_label,camp_race,origin,status,opponents,basis,source
2026,10018新竹市,高虹安,無,pan_blue,TPP (not a member on the ballot),decided by user,DPP nominee 莊競程; KMT fielded none,"Effectively TPP (user, 2026-11-30); the only pan-blue candidate in the race, so the pan-blue standard-bearer",
2026,10010嘉義縣,吳品叡,無,pan_blue,independent (township mayor),standard-bearer rule,DPP nominee 蔡易餘; KMT and TPP fielded none,"CNA (2026-09-03, read): 'KMT-backed independent' (中國國民黨支持的無黨籍); KMT county chair accompanied her registration; no KMT candidate on the ballot (CEC). TPP backing reported in search results only, not read",https://www.cna.com.tw/news/aipl/202609030072.aspx
2026,10015花蓮縣,張峻,無,pan_green,KMT (former county chair; expelled over the speakership race),decided by user,KMT nominee 游淑貞; independent 魏嘉賢; DPP fielded none,"NextApple (2026-11-17, read): DPP Hualien chapter chair said the DPP's councillors and officeholders support him; the DPP nominated no candidate. KMT background from search results only, not read (user decision 2026-11-30: pan-green for this race)",https://news.nextapple.com/politics/20261117/B78F1052362C4515C90EF7313C2A6B2B
2026,10015花蓮縣,魏嘉賢,無,unaligned,KMT (former county councillor),standard-bearer rule,KMT nominee 游淑貞; DPP-backed 張峻,Blue-origin splinter running against the KMT nominee; pan-blue's yardstick belongs to 游淑貞,https://www.cna.com.tw/news/aloc/202602220076.aspx
2026,10016澎湖縣,葉竹林,無,unaligned,KMT (left 2021),standard-bearer rule,KMT nominee 陳振中; DPP nominee 吳淑瑾,Both camps had nominees; blue-origin splinter,https://newtalk.tw/news/view/2021-02-19/538344
2026,09007連江縣,曹爾元,無,unaligned,KMT (sought 2022 nomination),standard-bearer rule,KMT incumbent 王忠銘; DPP fielded none,Challenger to the KMT nominee from the same camp; no party backed him,https://www.ettoday.net/news/20260615/3183959.htm
2026,09020金門縣,李文良,無,unaligned,independent (deputy magistrate under KMT magistrate 楊鎮浯),standard-bearer rule,KMT nominee 陳玉珍; five other independents; DPP fielded none,Ran against the KMT nominee as 'beyond party'; no party backed him,https://udn.com/news/story/124652/9520250
2026,10007彰化縣,邱建富,無,unaligned,DPP (left after the nomination),standard-bearer rule,DPP nominee 陳素月; KMT nominee 魏平政,Both camps had nominees; green-origin splinter,https://news.nextapple.com/politics/20260616/EA2F89F55310BC9B066C77E1857E994D
2026,10020嘉義市,張啓楷,台灣民眾黨,pan_blue,TPP,rule,DPP nominee 王美惠; KMT fielded none,TPP counts as pan-blue in 2026 (CLAUDE.md heuristic); the only pan-blue candidate,
2026,10016澎湖縣,周倪安,台聯黨,unaligned,TSU (pan-green label),standard-bearer rule,DPP nominee 吳淑瑾; KMT nominee 陳振中,Second pan-green-labelled candidate (1.5%); the DPP nominee is the pan-green standard-bearer,

camps_council_2026.csv

researched council candidates, with sources
county,dist,seat_type,name,party,total,share,elected,camp,evidence_type,confidence,source_url,source_date,quote_zh,notes,check,past_labels
09007連江縣,01,general,曹以標,無,871,20.7,True,unaligned,none,low,,,,Searched Lienchiang 2026 coverage; candidate not named. KMT Lienchiang nominees listed (udn) do not include him; independent magistrate candidate 曹爾元 ran vs KMT 王忠銘 but no link found.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
09007連江縣,01,general,林惠萍,無,640,15.2,True,unaligned,none,low,,,,"Searched; not named in 2026 coverage found. Past labels KMT 2014/2018, independent 2022.",,2014.0 council 中國國民黨 | 2018.0 council 中國國民黨* | 2022.0 council 無黨籍及未經政黨推薦
09007連江縣,01,general,曹爾章,無,637,15.1,True,unaligned,none,low,,,,"Searched; not named in 2026 coverage found. Past labels KMT 2014/2018, independent 2022.",,2014.0 council 中國國民黨 | 2018.0 council 中國國民黨* | 2022.0 council 無黨籍及未經政黨推薦*
09007連江縣,02,general,謝秉軒,無,607,37.2,True,unaligned,none,low,,,,"Searched; KMT Lienchiang nominees for 北竿 were 周瑞國、陳玉發 per snippet, not him; no evidence found",,
09007連江縣,03,general,王孝榛,無,452,42.7,False,unaligned,none,low,,,,Searched 1x: KMT Lienchiang nominations (莒光: 陳貽斌) do not include him; no party ties found.,,2018.0 council 無黨籍及未經政黨推薦*
09007連江縣,04,general,馮印才,無,352,39.9,False,unaligned,none,low,,,,Searched 1x: KMT Lienchiang nomination list (udn) names other council nominees for 東引; no ties found.,,2014.0 council 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦
09020金門縣,01,general,董森堡,無,2924,11.9,True,unaligned,none,low,,,,Searched; no 2025-26 source found. KMT magistrate candidate was 陳玉珍; no joint campaign with him found.,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
09020金門縣,01,general,莊勝騏,無,1857,7.6,True,unaligned,none,low,,,,search snippet (ettoday 2026-09-02) confirms registration in Kinmen district 1 only; no party tie found,,
09020金門縣,01,general,許大鴻,無,1789,7.3,True,unaligned,none,low,,,,searched; only pre-2025 CEC docs; no 2025-26 tie found,,2022.0 council 無黨籍及未經政黨推薦*
09020金門縣,01,general,許玉仙,無,1672,6.8,True,unaligned,none,low,,,,"Searched; ETtoday 2026-09-02 and udn 2026-09-04 (fetched) list her without party; search snippet notes not to confuse with KMT ex-councilor 許玉昭 (lead only, no tie shown)",,
09020金門縣,01,general,唐麗輝,無,1646,6.7,True,unaligned,none,low,,,,Searched; 2026-09-04 udn Kinmen registration article (fetched) lists candidate with no party mention; no party backing/caucus evidence found,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
09020金門縣,01,general,陳泱瑚,無,1593,6.5,True,unaligned,none,low,,,,"Searched; 2026-09-04 udn Kinmen registration article (fetched) lists candidate with no party mention; no party backing/caucus evidence found; older (2023) snippets show cross-party caucus convener, pre-2025 not evidence",,2022.0 council 無黨籍及未經政黨推薦*
09020金門縣,01,general,楊忠俊,無,1351,5.5,False,unaligned,none,low,,,,"Searched 2x: 2022 KMT township-chief label (lead); 2026 snippet confirms registration in Kinmen district 1 only; no nomination, expulsion or membership report found",,2014.0 township_chief 無黨籍及未經政黨推薦 | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 中國國民黨*
09020金門縣,01,general,李慧艷,無,1114,4.5,False,unaligned,none,low,,,,"Searched 1x: snippet says she attended 金寧 township candidate 翁紹輝's HQ launch (attendance only, not evidence); no party ties found.",,
09020金門縣,02,general,陳麒翔,無,2927,17.2,True,unaligned,none,low,,,,Searched; no 2025-26 source found.,,
09020金門縣,02,general,李文益,無,1809,10.6,True,unaligned,none,low,,,,searched; no 2025-26 coverage found,,
09020金門縣,02,general,陳錦偉,無,1697,10.0,True,unaligned,none,low,,,,"Searched; udn 2026-09-04 (fetched) says registered as sitting councilor, no party mentioned; no evidence found",,2022.0 council 無黨籍及未經政黨推薦*
09020金門縣,02,general,楊育菡,無,1583,9.3,True,unaligned,none,low,,,,Searched; 2026-09-04 udn Kinmen registration article (fetched) lists candidate with no party mention; no party backing/caucus evidence found,,2022.0 council 無黨籍及未經政黨推薦*
09020金門縣,02,general,蔡水游,無,1416,8.3,True,unaligned,none,low,,,,Searched; 2026-09-04 udn Kinmen registration article (fetched) lists candidate with no party mention; no party backing/caucus evidence found; past KMT council labels 2014/2018 lead only,,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 無黨籍及未經政黨推薦*
09020金門縣,02,general,吳佩雯,無,1282,7.5,False,unaligned,none,low,,,,"Searched 2x (incl. Kinmen KMT nomination list): snippet calls her a Kinmen councillor in 2025 and a former spokesperson for 楊鎮浯's office (pre-2025, not evidence); no 2025-26 party ties found",,2022.0 council 無黨籍及未經政黨推薦
09020金門縣,02,general,黃萱萱,無,1056,6.2,False,unaligned,none,low,,,,Searched 1x: only in 2026 Kinmen registration list; no party ties found,,
09020金門縣,02,general,李應文,無,838,4.9,False,unaligned,none,low,,,,"Searched 2x (lead: KMT councillor 2014-18, 無 county-magistrate run 2022): no 2025-26 party ties found.",,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 executive 無黨籍及未經政黨推薦
09020金門縣,03,general,洪毓壕,無,1535,37.1,True,unaligned,none,low,,,,Searched; 2026-09-04 udn Kinmen registration article (fetched) lists candidate with no party mention; no party backing/caucus evidence found,,
09020金門縣,03,general,洪若珊,無,1492,36.1,True,unaligned,none,low,,,,Searched; 2026-09-04 udn Kinmen registration article (fetched) lists candidate with no party mention; no party backing/caucus evidence found; past KMT labels (2014-22 township) are lead only,,2014.0 township_rep 中國國民黨* | 2018.0 township_chief 中國國民黨* | 2022.0 township_chief 中國國民黨*
09020金門縣,03,general,洪長享,無,966,23.3,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10002宜蘭縣,01,general,林錫明,無,3654,7.6,True,unaligned,none,low,,,,Searched; no 2025-26 source found. Past labels independent 2014-2022.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10002宜蘭縣,01,general,楊易林,無,2920,6.1,False,unaligned,none,low,,,,Searched 1x and opened udn 2026-06-07 Yilan City race story (does not mention him): no 2025-26 party ties found.,,
10002宜蘭縣,02,general,林瑞文,無,3767,23.3,False,unaligned,none,low,,,,Searched; no 2025-26 source found. Past labels: 2018 NPP council; 2022 DPP township chief.,,2018.0 council 時代力量 | 2022.0 township_chief 民主進步黨
10002宜蘭縣,03,general,林聰池,無,5342,26.8,True,unaligned,none,low,,,,Searched; no 2025-26 source found.,,2022.0 council 無黨籍及未經政黨推薦*
10002宜蘭縣,03,general,吳秋玟,無,2187,11.0,False,unaligned,none,low,,,,Not found in searches. Past labels: DPP 2014 township rep and 2018 township chief.,,2014.0 township_rep 民主進步黨* | 2018.0 township_chief 民主進步黨
10002宜蘭縣,03,general,游順評,無,1411,7.1,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10002宜蘭縣,04,general,陳玉麟,無,4260,23.8,False,pan_green,B,medium,https://newtalk.tw/news/view/2025-11-27/1006802,2025-11-27,擊退另一位參選人陳玉麟的 46.94%,"Searched 2x, page opened. Lost DPP Yilan Yuanshan council primary (53.06 vs 46.94) to 李姿婷; aide to DPP legislator 陳俊宇 (正國會). Ran as independent in 2026. No report found of his membership status at registration or of party discipline, hence medium.",,
10002宜蘭縣,05,general,陳福山,無,4495,31.2,True,unaligned,none,low,,,,Searched; no 2025-26 caucus or endorsement source found. Search snippet citing older CEC lists showed DPP label in an earlier election (pre-2014?) - not evidence.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10002宜蘭縣,05,general,沈清山,無,3819,26.5,False,pan_blue,A,high,https://udn.com/news/story/124652/9538945,2026-06-01,第五選區(壯圍鄉)沈清山…以報准方式參選,Listed in KMT Yilan chapter 2026 徵召/提名 list as running by 報准 (party-approved) although ballot label is 無. Past labels: KMT township chief 2018/2022.,,2018.0 township_chief 中國國民黨* | 2022.0 township_chief 中國國民黨*
10002宜蘭縣,06,general,林宜弘,無,4552,13.5,True,unaligned,none,low,https://news.ltn.com.tw/news/Yilan/breakingnews/5656934,2026-11-28,擠下國民黨提名的副議長陳漢鍾,"Conflict: son of KMT magistrate 林姿妙 (she campaigned for him, but she was not a 2026 candidate), yet ran as independent and beat KMT nominee. No party action for him -> unaligned.",,
10002宜蘭縣,07,general,黃子堯,無,4908,22.2,True,unaligned,none,low,,,,Searched; no 2025-26 source found. Past labels independent township rep 2018/2022.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10002宜蘭縣,07,general,沈信雄,無,4150,18.8,False,pan_green,A,high,https://news.ltn.com.tw/amp/news/politics/breakingnews/5466406,2026-06-09,林國漳偕同…縣議員沈信雄、議員參選人張明華等人,DPP magistrate candidate 林國漳 campaigned in Wujie with 沈信雄. Search snippets of udn 2026 DPP nomination story (udn.com/news/story/6656/9124351; returned 404 when opened) say DPP county chapter 與現任無黨籍的沈信雄結盟. Past labels: 2014 DPP township rep; 2018/2022 independent.,,2014.0 township_rep 民主進步黨* | 2018.0 council 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
10002宜蘭縣,08,general,邱素梅,無,3920,14.1,True,unaligned,none,low,,,,Searched; no 2025-26 source found. Search snippet citing older CEC list showed DPP label in an earlier election - not evidence.,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10002宜蘭縣,10,general,陳玉萍,無,5282,26.5,False,unaligned,none,low,,,,Searched 2x: no 2025-26 party ties found,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10002宜蘭縣,11,plain_indigenous,孫湯玉惠 aly saku,無,1239,100.0,True,unaligned,none,low,,,,Lead only: KMT Yilan chapter left plain-indigenous seat (dist 11) unnominated to 保留與無黨籍合作空間 (udn 9538945 2026-06-01) but does not name her. Sole candidate. Past label 2014 independent.,,2014.0 council 無黨籍及未經政黨推薦*
10002宜蘭縣,13,mountain_indigenous,曹天民,無,1877,44.4,False,unaligned,none,low,,,,KMT backed 李勝雄 by 報准 in dist 13 (南澳鄉) per udn 9538945; no evidence about 曹天民 himself.,,
10004新竹縣,01,general,鄭美琴,無,4171,12.2,False,unaligned,none,low,,,,UDN 2026-08-04 (udn.com/news/story/124652/9668755) lists her as 無黨籍 incumbent 竹北西區 with no party support mentioned,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10004新竹縣,02,general,朱健銘,無,5714,8.2,True,unaligned,none,low,,,,searched; UDN 2026-08-04 (udn.com/news/story/124652/9668755) lists him only as 無黨籍 incumbent in 竹北東區 with no party support; Yahoo snippet says he quit KMT (likely pre-2022); past KMT township rep 2018,,2018.0 township_rep 中國國民黨* | 2022.0 council 無黨籍及未經政黨推薦*
10004新竹縣,03,general,羅美文,勞動黨,4445,10.7,True,unaligned,none,low,,,,"Ballot label 勞動黨 (Labour Party), which is in neither camp under the rules; searched 1x: twreporter piece on Labour Party 2026 slate (lead only, not opened); no 2025-26 pan-green/blue ties found",,2018.0 council 勞動黨* | 2022.0 council 勞動黨*
10004新竹縣,03,general,翁紹軒,無,3871,9.3,False,unaligned,none,low,,,,Searched 2x (lead: KMT township rep 2014-22): no 2025-26 reports found; past label not evidence.,,2014.0 township_rep 中國國民黨* | 2018.0 township_rep 中國國民黨* | 2022.0 township_rep 中國國民黨*
10004新竹縣,04,general,林茂青,無,3658,12.3,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2014.0 village_chief 無黨籍及未經政黨推薦* | 2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10004新竹縣,05,general,蔡澄均,無,4379,28.3,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10004新竹縣,06,general,呂宛庭,無,8711,45.7,True,unaligned,none,low,,,,searched; no results,,2022.0 council 無黨籍及未經政黨推薦*
10004新竹縣,06,general,陳新源,勞動黨,6733,35.3,True,unaligned,none,low,,,,"Ballot label 勞動黨 (Labour Party; not in either camp). Searched 1x and opened twreporter 2026-11-15 Labour Party story (https://www.twreporter.org/a/2026-local-elections-labor-party-china-united-front): reports his win, no KMT/TPP backing or 禮讓 mentioned.",,2014.0 township_rep 勞動黨* | 2014.0 township_rep 中國國民黨 | 2018.0 council 勞動黨* | 2022.0 township_chief 勞動黨
10004新竹縣,09,general,鄭朝鐘,無,5849,12.6,True,unaligned,none,low,,,,lead only: UDN search snippet (story 6656/9166370; page 404 on fetch) says he appeared on stage for KMT's 陳見賢 county-magistrate bid (陳 later lost KMT primary); brother of DPP magistrate candidate 鄭朝方; not party backing of him -> unaligned,,2022.0 council 無黨籍及未經政黨推薦*
10004新竹縣,09,general,林昭錡,無,4492,9.7,False,unaligned,none,low,,,,"Searched 2x: only 2014 DPP label (CEC 遞補 notice, pre-2025, not evidence); no 2025-26 party ties found",,2014.0 council 民主進步黨 | 2018.0 council 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
10004新竹縣,10,general,何時名,無,2551,32.7,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2018.0 township_rep 無黨籍及未經政黨推薦 | 2022.0 township_rep 無黨籍及未經政黨推薦*
10004新竹縣,12,plain_indigenous,林秉君 kaying.kuying.kalang,無,998,77.7,True,unaligned,none,low,,,,searched; no results,,
10004新竹縣,12,plain_indigenous,法隆伊佑,無,286,22.3,False,unaligned,none,low,,,,searched; no results; past label DPP 2022,,2022.0 council 民主進步黨
10004新竹縣,13,mountain_indigenous,高忠正,無,1632,29.0,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2014.0 township_rep 無黨籍及未經政黨推薦 | 2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10004新竹縣,13,mountain_indigenous,羅恩加,無,1010,18.0,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10004新竹縣,13,mountain_indigenous,范經生,無,762,13.6,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10004新竹縣,14,mountain_indigenous,張益生,無,2092,55.6,True,unaligned,none,low,,,,searched; past label KMT 2022 council; 2023 vote-buying case reported; no 2025-26 evidence of party status found,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 中國國民黨*
10004新竹縣,14,mountain_indigenous,張雁萍,無,937,24.9,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2022.0 council 無黨籍及未經政黨推薦
10005苗栗縣,01,general,彭晧宇,無,7250,11.1,True,unaligned,none,low,,,,searched; no results,,
10005苗栗縣,01,general,呂晟,無,4631,7.1,True,unaligned,none,low,,,,Searched once; only appears in results lists as 無黨籍 newcomer (dist 1); no camp evidence.,,
10005苗栗縣,01,general,湯維岳,無,4404,6.7,True,unaligned,none,low,,,,searched 2026 Miaoli coverage; no 2025-26 party tie found,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦
10005苗栗縣,01,general,彭賢淳,無,3395,5.2,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10005苗栗縣,01,general,巫召清,無,3242,4.9,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10005苗栗縣,01,general,林志豪,無,2224,3.4,False,unaligned,none,low,,,,searched; no results; past label 時代力量 2022,,2022.0 council 時代力量
10005苗栗縣,02,general,謝昌年,無,4545,21.5,True,unaligned,none,low,https://www.cna.com.tw/news/aipl/202611285007.aspx,2026-11-28,,"Researched via search; ex-銅鑼鄉長, ran against KMT and DPP nominees in 3-way race for 3 seats; no party support found. Page not opened for quote.",,2014.0 township_chief 無黨籍及未經政黨推薦 | 2018.0 township_chief 無黨籍及未經政黨推薦 | 2022.0 township_chief 無黨籍及未經政黨推薦*
10005苗栗縣,03,general,徐瑞轅,無,7627,18.2,True,unaligned,none,low,,,,searched; no results,,
10005苗栗縣,03,general,陳薈茗,無,7026,16.8,True,unaligned,none,low,,,,Lead only (snippets): described as 陳品安特助 (DPP magistrate nominee) and long-time team member; no report of DPP/陳品安 backing her council bid found; udn 9394683 DPP nomination list (opened) does not mention her.,,2014.0 village_chief 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦
10005苗栗縣,03,general,周玉滿,無,5957,14.2,True,unaligned,none,low,https://news.ltn.com.tw/news/politics/paper/1746783,2026,現任無黨籍議員徐永煌及周玉滿,Researched; described only as 無黨籍 incumbent; no party support found.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
10005苗栗縣,03,general,郭汶沂,無,5818,13.9,True,unaligned,none,low,https://news.ltn.com.tw/news/politics/paper/1746783,2026,無黨籍苑裡鎮代郭汶沂,"Researched (also udn 9293813, 2026-01-28); no party support found.",,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10005苗栗縣,03,general,王建鑫,無,2518,6.0,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10005苗栗縣,04,general,張佳玲,無,7475,10.9,True,unaligned,none,low,,,,searched; only council-activity news found,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10005苗栗縣,04,general,鄭秋風,無,5477,8.0,True,unaligned,none,low,,,,searched; no results; past label KMT 2014-2022,,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨*
10005苗栗縣,04,general,陳碧華,無,5344,7.8,True,unaligned,none,low,,,,searched; only LTN 2026-09 snippet on road inspection with 張佳玲; past KMT 2014/2018,,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10005苗栗縣,04,general,謝美香,無,1731,2.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2018.0 village_chief 無黨籍及未經政黨推薦* | 2022.0 village_chief 無黨籍及未經政黨推薦*
10005苗栗縣,05,general,彭茜柔,無,6761,11.4,True,unaligned,none,low,,,,Searched; no coverage found.,,
10005苗栗縣,05,general,蕭詠萱,無,5425,9.1,True,unaligned,none,low,https://news.ltn.com.tw/news/politics/breakingnews/5373490,2026-03-17,,"Researched; LTN reporter lists her among 泛藍陣營 incumbents (journalist characterisation, not party action; not A-D). Lead toward pan_blue only.",,2022.0 council 無黨籍及未經政黨推薦*
10005苗栗縣,05,general,陳永賢,無,4598,7.7,True,pan_blue,B,medium,https://udn.com/news/story/124652/9388134,2026-03-18,以張淑芬、縣議員陳永賢、徐功凡,KMT Miaoli chapter included him in its internal poll for the KMT Toufen mayor nomination (implies KMT member); he then ran for council as 無 without KMT nomination; membership not stated explicitly; past KMT 2014/2018,,2014.0 council 中國國民黨* | 2018.0 township_chief 中國國民黨 | 2022.0 council 無黨籍及未經政黨推薦*
10005苗栗縣,05,general,黎煥強,無,4457,7.5,True,unaligned,none,low,https://news.ltn.com.tw/news/politics/breakingnews/5373490,2026-03-17,,Researched; described only as 前縣議員 回鍋參選; no party/camp stated.,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦
10005苗栗縣,05,general,鍾孟儒,無,2884,4.8,False,unaligned,none,low,,,,Searched 1x: 頭份 village chief switching to council run; no party ties found.,,2022.0 village_chief 無黨籍及未經政黨推薦*
10005苗栗縣,05,general,温俊勇,無,2276,3.8,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2020.0 legislator 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
10005苗栗縣,06,general,盛瑛,無,8336,43.1,True,unaligned,none,low,,,,searched; no results,,2022.0 council 無黨籍及未經政黨推薦
10005苗栗縣,06,general,楊恭林,無,6653,34.4,True,unaligned,none,low,,,,lead: LTN 2026-04-01 (news.ltn.com.tw/news/Miaoli/paper/1749143) calls him 同屬泛藍陣營的縣議員 - journalist camp label not an A-D evidence type,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10005苗栗縣,06,general,詹錦章,無,4353,22.5,False,unaligned,none,low,,,,Searched 2x: only lead is a CEC document listing him as 卓蘭鎮長 (pre-2025); no 2025-26 party ties found,,2014.0 village_chief 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦*
10005苗栗縣,07,plain_indigenous,風志雄,無,1111,53.0,True,unaligned,none,low,,,,Searched once; no 2025-26 results found,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10005苗栗縣,07,plain_indigenous,朱仲一 Kalih.Tahes.Didiyun,無,984,47.0,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10005苗栗縣,08,mountain_indigenous,黃茹君 Haking Yuma’,無,1972,50.8,True,unaligned,none,low,,,,searched; no 2025-26 coverage found,,
10007彰化縣,01,general,謝宗樺,無,7984,5.4,True,unaligned,none,low,,,,searched; no qualifying 2025-26 evidence found,,
10007彰化縣,01,general,黃玉如,無,6779,4.6,False,unaligned,none,low,,,,"Searched 1x, fetched udn 9664456 (2026-08-01): first-time 無 candidate, sister of KMT member 黃玉芬 (who planned to quit KMT to run for Changhua City mayor, described as 泛藍). Family tie only, no party action for 黃玉如; unaligned.",,
10007彰化縣,01,general,陳銌銌,無,6054,4.1,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10007彰化縣,02,general,郭燕陵,無,11785,13.5,True,unaligned,none,low,,,,searched; no qualifying 2025-26 evidence found; named without party label in LTN 2026-01-11 (5306590).,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10007彰化縣,02,general,林英嘉,無,9547,10.9,True,unaligned,none,low,,,,searched; no qualifying 2025-26 evidence found; LTN 2026-01-11 (5306590) lists him as outgoing Xiushui township chief moving to council race without party label.,,2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦*
10007彰化縣,03,general,林明鴻,無,8796,12.2,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found.,,2022.0 township_rep 無黨籍及未經政黨推薦*
10007彰化縣,03,general,林宗翰,無,6617,9.2,True,unaligned,none,low,,,,searched; no qualifying 2025-26 evidence found; CEC registration list snippet shows party 無.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10007彰化縣,04,general,詹雅婷,無,9532,9.0,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦
10007彰化縣,04,general,劉惠娟,無,5117,4.9,False,pan_blue,B,medium,https://udn.com/news/story/124652/9567271,2026-06-15,國民黨彰化縣議員劉惠娟,KMT incumbent lost KMT Yuanlin mayor primary (Jun 2026); did not register for KMT council nomination (udn 9605524 2026-07-03: 外界猜測是否以無黨參選); ballot label 無. Membership at filing not separately confirmed.,,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨*
10007彰化縣,04,general,張詩怡,無,3971,3.8,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2022.0 township_rep 無黨籍及未經政黨推薦*
10007彰化縣,05,general,許文萍,無,14793,23.0,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found.,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦*
10007彰化縣,05,general,張春洋,無,9241,14.4,True,unaligned,none,low,,,,Searched; MOI roster lists party 無; no 2025-26 backing found.,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10007彰化縣,07,general,杜懿彩,無,9124,14.8,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found.,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦*
10007彰化縣,07,general,陳世凱,無,5063,8.2,False,unaligned,none,low,,,,Searched 1x (joint with 鄭朝元): no 2025-26 party ties found.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10007彰化縣,07,general,江熊一楓,無,4540,7.4,False,pan_green,B,high,https://udn.com/news/story/6656/9689663,2026-08-13,決議予以停權2年處分,DPP Changhua chapter suspended her 2 yrs (assistant-fee case); suspension bars DPP nomination; ran as 無. Past DPP labels 2014-22. CNA 2026-10-22 snippet (not opened): husband says she will not give up running.,,2014.0 council 民主進步黨* | 2018.0 council 民主進步黨* | 2022.0 council 民主進步黨
10007彰化縣,07,general,鄭朝元,無,4510,7.3,False,unaligned,none,low,,,,Searched 1x (joint with 陳世凱): no 2025-26 party ties found.,,
10007彰化縣,08,general,吳淑娟,無,5870,10.2,True,unaligned,none,low,https://udn.com/vote2026/story/124652/9730898,2026-09-03,無黨籍現任議員吳淑娟,Researched; no camp or party support stated.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10007彰化縣,08,general,黄淑儀,無,5643,9.8,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found (no coverage of her).,,
10007彰化縣,09,plain_indigenous,陳明義,無,371,29.1,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10008南投縣,01,general,張婉慈,無,6686,8.9,True,unaligned,none,low,,,,searched; no qualifying 2025-26 evidence found; udn 9387535 (2026-03-18) describes her as independent with stable base.,,2022.0 council 無黨籍及未經政黨推薦*
10008南投縣,01,general,張秀枝,無,5834,7.8,True,unaligned,none,low,,,,searched; no qualifying 2025-26 evidence found; udn 9387535 groups her with independents (replacement councilor).,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦
10008南投縣,01,general,簡千翔,無,5741,7.6,True,unaligned,none,low,,,,Quit TPP 2026-04-09 and said he would run as 無黨籍 and not join other parties (udn 124652/9430930 opened). Quitting over disagreement is not alignment. udn 9387535 (2026-03-18) says locals see him as 泛藍協力者 - descriptive only. Past label TPP 2022.,,2022.0 council 台灣民眾黨*
10008南投縣,01,general,陳聰鑑,無,5693,7.6,True,unaligned,none,low,,,,"Searched (2 queries), no 2025-26 page found mentioning him. Lead: 2018 DPP township chief label (not evidence).",,2014.0 township_chief 無黨籍及未經政黨推薦 | 2018.0 township_chief 民主進步黨
10008南投縣,01,general,洪明科,無,4530,6.0,True,unaligned,none,low,,,,searched; no qualifying 2025-26 evidence found; udn 9387535 (2026-03-18) describes him as independent.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10008南投縣,01,general,廖詒綉,無,3645,4.8,False,unaligned,none,low,,,,udn 9387535 (2026-03-18) lists 南投市代 廖怡琇 (variant character; identity unconfirmed) under KMT section without confirming membership. Lead only.,,
10008南投縣,01,general,張錫淵,無,3038,4.0,False,unaligned,none,low,,,,udn 9387535 (2026-03-18) lists 南投市代 張錫淵 under KMT section without confirming membership; not qualifying. Lead only.,,2022.0 council 無黨籍及未經政黨推薦
10008南投縣,01,general,陳志斌,無,3023,4.0,False,unaligned,none,low,,,,udn 9387535 (2026-03-18) lists 南投市代 陳志斌 under KMT section but does not confirm membership or nomination; not qualifying. Past KMT township_rep labels 2014-22. Lead for B.,,2014.0 township_rep 中國國民黨 | 2018.0 township_rep 中國國民黨* | 2022.0 township_rep 中國國民黨*
10008南投縣,02,general,簡峻庭,無,6193,9.9,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10008南投縣,02,general,林友友,無,5818,9.3,True,unaligned,none,low,https://news.ltn.com.tw/news/Nantou/paper/1755366,2026-05-19,她是前縣議員林永鴻的女兒,"Researched; 2026 page gives no camp. Lead only: 2022 LTN headline (4044457) called her 綠營 (pre-2025, not evidence). No DPP endorsement found in 2025-26.",,2022.0 council 無黨籍及未經政黨推薦*
10008南投縣,02,general,洪宗呈,無,4049,6.5,True,unaligned,none,low,,,,LTN 2026-05-19 (Nantou/paper/1755366): father ex-草屯鎮長洪國浩 campaigns for him; no party affiliation stated,,
10008南投縣,02,general,張至順,無,3830,6.1,True,unaligned,none,low,,,,searched; no 2025-26 coverage found,,
10008南投縣,02,general,廖梓佑,無,3816,6.1,True,unaligned,none,low,,,,searched; no qualifying 2025-26 evidence found; past DPP labels 2014-22; now 無 - possible B lead but no 2025-26 source found on her status.,,2014.0 council 民主進步黨* | 2018.0 council 民主進步黨* | 2022.0 council 民主進步黨*
10008南投縣,02,general,林佳穎,無,3776,6.0,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10008南投縣,02,general,莊士傑,無,3636,5.8,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10008南投縣,02,general,簡百聰,無,2133,3.4,False,unaligned,none,low,,,,Searched 2x (lead: 2022 DPP-labelled township rep): no 2025-26 news found on him or any DPP tie,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 民主進步黨*
10008南投縣,03,general,蕭志全,無,7367,26.5,True,pan_blue,B,high,https://news.ltn.com.tw/news/politics/breakingnews/5442543,2026-05-19,黨內有意角逐的前議員蕭志全,Former KMT councilor; did not register for KMT nomination; asked party for 報准 (would allow KMT label); ballot label 無 so not 報准. Past KMT labels 2014-22.,,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 township_chief 中國國民黨
10008南投縣,04,general,何勝豐,無,4673,12.2,True,unaligned,none,low,https://news.ltn.com.tw/news/politics/breakingnews/5639715,2026-11-13,總統致詞時也不忘呼籲支持何勝豐,"Conflict: DPP chair/President Lai urged support for him at 温世政 rally (green A-type), but he says he backs KMT's 許淑華 for magistrate (縣長他支持許淑華); described as 無黨籍. Conflicting -> unaligned.",,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 無黨籍及未經政黨推薦*
10008南投縣,04,general,林哲生,無,4200,10.9,True,unaligned,none,low,,,,searched; no 2025-26 coverage found,,
10008南投縣,04,general,許耿禎,無,3915,10.2,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2014.0 council 無黨籍及未經政黨推薦
10008南投縣,04,general,邱如平,無,3489,9.1,False,unaligned,none,low,,,,"Searched 1x: past independent 鹿谷鄉長 candidate (2018, 2022 CEC lists); no 2025-26 party ties found",,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦*
10008南投縣,04,general,李廣演,勞動黨,3133,8.2,False,unaligned,none,low,,,,Ballot label 勞動黨 (Labour Party; not in either camp). Searched 2x plus twreporter Labour Party story (does not name him): no KMT/TPP backing found.,,2022.0 council 無黨籍及未經政黨推薦
10008南投縣,05,general,林奕辰,無,6693,13.0,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found.,,
10008南投縣,05,general,戴世詮,無,5334,10.4,True,unaligned,none,low,,,,"Searched (2 queries), no 2025-26 page found mentioning him. Lead: 2014 KMT township chief label (not evidence).",,2014.0 township_chief 中國國民黨 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10008南投縣,05,general,吳維倫,無,4560,8.9,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10008南投縣,06,plain_indigenous,石慶龍 Rungquan‧Lhkatafatu,無,500,52.2,True,unaligned,none,low,,,,"Searched; snippets show sitting Nantou councilor, no party tie found",,2014.0 council 台灣第一民族黨*
10008南投縣,06,plain_indigenous,江秉翰,無,458,47.8,False,unaligned,none,low,,,,Searched 2x (lead: 2022 council DPP label): no 2025-26 news found on his candidacy or DPP ties; ran as independent 2026,,2022.0 council 民主進步黨
10008南投縣,07,mountain_indigenous,王榮儀,無,2017,36.1,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2018.0 council 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦
10008南投縣,07,mountain_indigenous,田東憲,無,1093,19.6,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10009雲林縣,01,general,林岳璋,無,6109,7.3,True,pan_blue,B,medium,https://udn.com/news/story/6656/9753408,2026-09-14,同黨縣議員林岳璋(右)力挺,UDN calls him a fellow KMT (同黨) councilor of KMT councilor 賴淑娞 and lists him among 黨籍人士 at her HQ launch; he ran under 無 label = KMT member without party label. Also attended KMT magistrate nominee 張嘉郡 policy event (udn 9495244 2026-05-11: 雲林縣議員林岳璋...出席相挺). Council website lists him 無黨籍; past_labels all 無.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,01,general,鍾明馨,無,5305,6.3,True,unaligned,none,low,,,,Searched; no 2025-26 party backing found. Lead only: snippet says he attended a county-government 縣政說明會 with 張嘉郡 (not opened). Council site label 無黨籍.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,01,general,曾博鴻,無,5295,6.3,True,unaligned,none,low,,,,Searched; no 2025-26 evidence. past_labels: 2022 council DPP but council website now lists him 無黨籍 and profile cites past post as 立法委員劉建國服務團隊秘書 (biography not cycle evidence). Possible ex-DPP; departure circumstances not found.,,2014.0 township_rep 民主進步黨* | 2018.0 township_rep 民主進步黨* | 2022.0 council 民主進步黨*
10009雲林縣,01,general,邱世文,無,4788,5.7,False,pan_green,B,high,https://news.ltn.com.tw/news/life/paper/1758339,2026-06-11,民進黨邱世文退黨參選,DPP member not nominated (未獲黨徵召提名) quit DPP to run as independent; DPP county chapter said 違紀參選 review would follow. Also ETtoday 2026-06-11 (ettoday.net/news/20260611/3181789.htm). Not in CNA 2026-09-24 list of 18 expelled.,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 township_chief 民主進步黨
10009雲林縣,01,general,王竣毅,無,3609,4.3,False,pan_blue,B,medium,https://udn.com/news/story/6656/9565837,2026-06-14,兩位參選人王竣毅、張家閎參加,"Attended TPP county members meeting as TPP council aspirant (June 2026); TPP had put him in district-1 primary (nownews 6797283 snippet, Mar 2026). Ran under 無 label; no report found of quitting TPP or of party endorsement. Father 王又民 is KMT councilor. Indirect -> medium.",,
10009雲林縣,01,general,許百芳,無,3314,3.9,False,unaligned,none,low,,,,Searched; only listed as aspirant in district 1 (udn 9505070 2026-05-15) with no party stated. past_labels DPP township chief/rep 2014-2022 (lead only).,,2014.0 township_chief 民主進步黨 | 2018.0 township_rep 民主進步黨* | 2022.0 township_chief 民主進步黨
10009雲林縣,01,general,張光儀,無,2448,2.9,False,unaligned,none,low,,,,Listed as aspirant in udn 9505070 (2026-05-15) with no party stated. Dedicated search not performed (search budget exhausted).,,2022.0 council 無黨籍及未經政黨推薦
10009雲林縣,02,general,賴明源,無,6967,13.6,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,02,general,林森寳,無,6162,12.0,True,unaligned,none,low,https://udn.com/news/story/125080/9909241,2026-11-29,,"Researched: opened udn 9909241, LTN 5657890, chinatimes 20261129001628; former 大埤鄉長, no party/camp stated in any page.",,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦*
10009雲林縣,02,general,洪惠玲,無,5754,11.2,True,unaligned,none,low,https://news.ltn.com.tw/news/politics/breakingnews/5657890,2026-11-30,,"Researched (Yunlin post-election pages); first-time winner, no party/camp stated.",,
10009雲林縣,02,general,黃景鴻,無,4097,8.0,False,unaligned,none,low,,,,Searched 1x (joint with 陳麗蘭): no 2025-26 party ties found.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10009雲林縣,02,general,陳麗蘭,無,3757,7.3,False,unaligned,none,low,,,,Searched 1x (joint with 黃景鴻): no 2025-26 party ties found.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10009雲林縣,03,general,黃美瑤,無,10727,14.6,True,unaligned,none,low,,,,Registration covered in LTN 5557993 (2026-08-31) with no party stated; no further research (search budget exhausted).,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,03,general,沈昱霆,無,8246,11.3,True,unaligned,none,low,,,,"Snippet (LTN 5559710): son of ex-speaker 沈宗隆 (KMT per udn snippet), registered 第3選區; no party backing found.",,
10009雲林縣,03,general,王鈺齊,無,7021,9.6,True,unaligned,none,low,,,,Searched 2x; past label 台聯 but no 2025-26 coverage found.,,2018.0 council 台灣團結聯盟* | 2022.0 council 台灣團結聯盟*
10009雲林縣,03,general,黃凱,無,6722,9.2,True,unaligned,none,low,,,,"Searched; incumbent speaker, 無黨籍, convicted at first instance (2025); no 2026 party backing found.",,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,03,general,蔡明水,無,5677,7.7,True,unaligned,none,low,https://udn.com/news/story/124652/9908480,2026-11-29,蔡明水(現任),"Researched; incumbent independent. Lead: quit DPP in 2018 (LTN 1254666, pre-2025, not evidence). No 2025-26 party tie found.",,2014.0 township_chief 民主進步黨 | 2018.0 council 民主進步黨* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,03,general,陳俊龍,無,4210,5.7,True,unaligned,none,low,,,,"searched; only pre-2025 CEC docs (once 台聯-nominated, pre-2025, not evidence); no 2025-26 tie found",,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦* | 2024.0 legislator 無黨籍及未經政黨推薦
10009雲林縣,03,general,張維心,無,4054,5.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,04,general,楊智凱,無,5418,10.7,True,unaligned,none,low,https://news.ltn.com.tw/news/politics/breakingnews/5657890,2026-11-30,,Researched; per search snippets son/successor of outgoing councillor 楊國寬; no party/camp stated.,,
10009雲林縣,04,general,游淑雲,無,5349,10.6,True,unaligned,none,low,https://udn.com/news/story/124652/9908480,2026-11-29,游淑雲(現任、女),"Researched; incumbent independent, no party/camp stated.",,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,04,general,廖庭輝,無,3930,7.8,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2022.0 township_rep 無黨籍及未經政黨推薦*
10009雲林縣,05,general,吳蕙蘭,無,7712,14.2,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found.,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,05,general,吳宗典,無,5876,10.8,True,unaligned,none,low,https://udn.com/news/story/124652/9702284,2026-08-20,連任兩屆麥寮鄉代的吳宗典,"Researched; former 麥寮鄉代, no party/camp stated.",,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10009雲林縣,05,general,蘇國誼,無,5632,10.3,True,unaligned,none,low,https://udn.com/news/story/124652/9702284,2026-08-20,「代兄出征」承接胞兄蘇國瓏,Researched; successor to brother 蘇國瓏 (無黨籍); no party support stated.,,
10009雲林縣,05,general,蔡梨美,無,5357,9.8,True,unaligned,none,low,https://udn.com/news/story/124652/9702284,2026-08-20,林深力挺麥寮前鄉長蔡長昆之女蔡梨花,"Researched; article names 蔡梨花 (likely same person) backed by outgoing KMT councillor 林深 - individual councillor support, not party/magistrate candidate; not A. Weak pan_blue lead.",,
10009雲林縣,05,general,趙育祥,無,4099,7.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10009雲林縣,05,general,許留賓,無,2851,5.2,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,06,general,黃文祥,無,8950,19.5,True,unaligned,none,low,,,,Searched; mirrormedia 2026-06 snippet calls him 無黨籍 incumbent; no party backing found.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10009雲林縣,06,general,王新堯,無,6533,14.2,True,unaligned,none,low,,,,Searched; past label TPP 2022 but no 2025-26 coverage of him found.,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦 | 2022.0 council 台灣民眾黨
10009雲林縣,06,general,陳定鈞,無,5814,12.6,True,unaligned,none,low,https://udn.com/news/story/124652/9908480,2026-11-29,,"Researched; new councillor, Yunlin dist 6; no party/camp stated in opened pages.",,
10009雲林縣,06,general,黃美蘭,無,5558,12.1,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10009雲林縣,07,plain_indigenous,周志祥 Kacaw.Kaco,無,200,29.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10009雲林縣,07,plain_indigenous,鄭玫惠,無,138,20.3,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10009雲林縣,08,mountain_indigenous,蔡嘉峻 Pisaw Hakaw,無,273,38.8,True,unaligned,none,low,,,,"Searched; LTN snippet on registration, no party tie found",,
10009雲林縣,08,mountain_indigenous,高瑛翠,無,258,36.7,False,unaligned,none,low,,,,Searched 1x (shared with 李丘威達): LTN snippet only says she registered in traditional dress for new Yunlin mountain-indigenous seat; no party ties found,,
10009雲林縣,08,mountain_indigenous,李丘威達,無,108,15.4,False,unaligned,none,low,,,,Searched 1x (shared with 高瑛翠): no 2025-26 party ties found,,
10010嘉義縣,01,general,賴瓊如,無,4745,8.7,True,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past labels independent 2014-22.,,2014.0 township_chief 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10010嘉義縣,01,general,楊秀琴,無,4234,7.7,False,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past labels independent 2018-22.,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10010嘉義縣,02,general,林岱杰,無,6196,11.2,True,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past label independent 2022.,,2022.0 council 無黨籍及未經政黨推薦*
10010嘉義縣,02,general,陳慶桐,無,5551,10.1,True,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). No past labels.,,
10010嘉義縣,02,general,何秀英,無,4708,8.5,True,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past township_rep independent.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10010嘉義縣,02,general,陳文忠,無,2942,5.3,False,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past labels independent 2014-22.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10010嘉義縣,03,general,江明赫,無,3576,10.3,False,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past township_rep independent.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦
10010嘉義縣,03,general,簡志偉,無,3029,8.7,False,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past label: 2014 township chief KMT; independent 2018-22 (lead only).,,2014.0 township_chief 中國國民黨 | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦
10010嘉義縣,04,general,蔡政宜,無,6170,13.0,True,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Snippet lead: indicted Dec 2025 for money laundering (search snippet only); irrelevant to camp. Past label independent 2022.,,2022.0 council 無黨籍及未經政黨推薦*
10010嘉義縣,04,general,潘麗惠,無,5465,11.5,True,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). No past labels.,,
10010嘉義縣,04,general,姜鈞翔,無,4366,9.2,False,unaligned,B,medium,https://news.ltn.com.tw/news/ChiayiCounty/breakingnews/5593499,2026-10-02,提送評委會進行裁決處分,LTN: son of 6-term DPP councillor 姜梅紅; did not register for DPP nomination (並未參與黨內提名登記) and ran as independent in D4; DPP county chapter sent case to disciplinary committee; he says party had 'kicked him out'. Caveat: article reports his mother was accused of leaning KMT/黃文峰 camp (she denies 背骨) - accusation only; outcome of discipline not found. Reviewer may prefer unaligned. | user decision: unaligned (conflicting evidence),,
10010嘉義縣,05,general,黃金茂,無,6241,26.5,True,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past label KMT 2014; independent 2018-22 (lead only).,,2014.0 council 中國國民黨* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10010嘉義縣,06,general,莊竣傑,無,5415,11.1,True,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past labels independent 2018-22.,,2018.0 council 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
10010嘉義縣,06,general,詹志暉,無,3566,7.3,False,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past label KMT 2022 council (lead for B). KMT D6 nominee in 2026 was only 詹黃素蓮 (LTN 5535615) but no source found on his membership status in 2026.,,2022.0 council 中國國民黨
10010嘉義縣,07,mountain_indigenous,武清山,無,2118,100.0,True,unaligned,none,low,,,,Searched name+嘉義縣議員; no 2025-26 source found tying candidate to a party. KMT backed independent 吳品叡 for magistrate via 在野大聯盟 but opened articles (udn 9608450/9642928/9608767/9654397) name no council candidates. Not on DPP list (LTN 5488747) or KMT first-phase list (LTN 5535615). Past labels independent; mountain indigenous seat uncontested.,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,01,general,蔣家煌,無,6066,6.3,True,unaligned,none,low,,,,searched (1-2 queries); no 2025-26 page found tying candidate to a party,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,01,general,龔書翩,無,5350,5.6,True,unaligned,none,low,,,,LTN 2026-11-29 (https://news.ltn.com.tw/news/politics/breakingnews/5657675) lists her as one of 3 無黨籍 newcomers elected with no party or faction backing; no party tie found,,2022.0 village_chief 無黨籍及未經政黨推薦
10013屏東縣,01,general,蔣月惠,無,4665,4.8,True,unaligned,none,low,,,,LTN 2026-08-31 (5558594) registered as 無黨籍 seeking re-election; LTN 2026-11-29 calls her 孤鳥 independent elected without party/faction backing; past labels all independent,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2020.0 legislator 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦* | 2024.0 legislator 無黨籍及未經政黨推薦
10013屏東縣,01,general,林明順,無,4267,4.4,False,unaligned,none,low,,,,LTN 2026-08-31 lists as 無黨籍 registrant; searched (1-2 queries); no 2025-26 page found tying candidate to a party,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,01,general,張平原,無,3924,4.1,False,unaligned,none,low,,,,LTN 2026-08-31 lists as 無黨籍 registrant; searched (1-2 queries); no 2025-26 page found tying candidate to a party,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,02,general,鍾慶平,無,8759,11.3,True,unaligned,none,low,,,,LTN 2026-09-03 (5562418) lists as 無黨籍 in district 2; no party tie found,,2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦*
10013屏東縣,02,general,葉明博,無,6802,8.8,True,unaligned,none,low,,,,searched (1-2 queries); no 2025-26 page found tying candidate to a party; only older news (2015-17 Yanpu township chief by-election/vote-buying annulment),,2014.0 township_chief 無黨籍及未經政黨推薦 | 2018.0 township_chief 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,02,general,莊瓊如,無,5734,7.4,True,pan_green,A,medium,https://www.mirrormedia.mg/story/20261112edi050,2026-11-12,沈伯洋變身小丑魚助攻莊瓊如,"Mirror Media: 台北市長候選人沈伯洋 filmed a joint campaign video with her (魚你同行). Page does not name his party; 沈伯洋 is the DPP Taipei mayoral candidate (not Pingtung) - hence medium. CNA 2026-08-31 and Mirror 2026-11-12 interview give no party label; LTN 2026-08-31 lists her as 無黨籍. Also campaigned with 王必勝 (Mirror 20261120edi040, not opened).",,
10013屏東縣,02,general,蘇孟淳,無,5632,7.3,True,unaligned,none,low,,,,"LTN 2026-09-03 (5562418) registered as 無黨籍 taking over from sister councilor 蘇孟婕; family of ex-legislator 蘇震清 (formerly DPP; old, not evidence); 2024 independent legislative run; no 2025-26 party tie found",,2024.0 legislator 無黨籍及未經政黨推薦
10013屏東縣,02,general,何春美,無,5273,6.8,False,unaligned,none,low,,,,"LEAD: KMT councilor 2014-2022 and KMT caucus secretary-general in 2022 (LTN 4130663, 2022 - not this cycle). Ran on 無 ballot label in 2026; possible type B but no opened 2025-26 page confirms party status/nomination; Mirror Media 2026-10-08 names her as current councilor without party. Recommend follow-up",,2014.0 council 中國國民黨 | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨*
10013屏東縣,02,general,陳秋豪,無,4945,6.4,False,unaligned,none,low,,,,LEAD: 2022 台灣基進 nominee (old). No 2025-26 page found on why now independent; LTN topic page 404,,2022.0 council 台灣基進
10013屏東縣,02,general,鍾詔元,無,4720,6.1,False,unaligned,none,low,,,,searched (1-2 queries); no 2025-26 page found tying candidate to a party,,2022.0 council 無黨籍及未經政黨推薦
10013屏東縣,03,general,陳宗廷,無,8794,9.6,True,unaligned,none,low,,,,searched (1-2 queries); no 2025-26 page found tying candidate to a party,,2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,03,general,林國順,無,5951,6.5,True,unaligned,none,low,,,,LEAD: DPP-nominated Wanluan township chief in 2018 (LTN 2341672; old). LTN 2025-07-01 (def.ltn 5092854) describes him as 無黨籍 township chief - points away from current DPP membership; no 2025-26 party tie found,,2014.0 village_chief 無黨籍及未經政黨推薦 | 2014.0 village_chief 民主進步黨* | 2018.0 township_chief 民主進步黨* | 2022.0 township_chief 民主進步黨*
10013屏東縣,03,general,陳志成,無,5810,6.3,True,unaligned,none,low,https://udn.com/vote2026/story/124652/9708140,2026-08-23,無黨籍陳志成、林郁虹、陳宗廷,"Researched; 枋寮 base, no camp or party support stated.",,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,03,general,潘連周,無,5418,5.9,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2014.0 township_chief 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,03,general,林郁虹,無,4453,4.9,False,unaligned,none,low,,,,"LEAD: KMT label 2014, independent since 2018 (old). searched (1-2 queries); no 2025-26 page found tying candidate to a party",,2014.0 council 中國國民黨* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,04,general,林宇澤,無,15444,21.1,True,unaligned,none,low,,,,LTN 2026-11-29 (https://news.ltn.com.tw/news/politics/breakingnews/5657675): 31-year-old 無黨籍 top vote-getter; article says the 3 newcomers had no political background or faction resources; no party tie,,2022.0 council 無黨籍及未經政黨推薦
10013屏東縣,04,general,林蔡鳯梅,無,6705,9.2,True,unaligned,none,low,,,,searched (1-2 queries); no 2025-26 page found tying candidate to a party,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,04,general,鄭喬云,無,6336,8.7,True,unaligned,none,low,,,,no 2025-26 page found (LTN topic page 404),,
10013屏東縣,05,general,張榮傑,無,4845,14.4,True,unaligned,none,low,https://udn.com/news/story/124652/9840381,2026,,"Researched via search only (former 中科院 engineer, 2022 independent); no camp evidence found; page not opened for quote.",,2022.0 council 無黨籍及未經政黨推薦
10013屏東縣,05,general,黃盈裕,無,4793,14.2,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2014.0 township_chief 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,07,general,陳國在,無,4644,63.6,True,unaligned,none,low,https://udn.com/news/story/124652/9908660,2026-11-29,,"Researched via search snippets; ex-琉球鄉長, independent; vote-buying probe; no camp evidence. Page not opened for quote.",,2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦*
10013屏東縣,07,general,陳建興,無,2663,36.4,False,unaligned,none,low,,,,LTN 2026-08-31 lists as 無黨籍 registrant (district 7); no party tie found,,2022.0 council 無黨籍及未經政黨推薦
10013屏東縣,09,mountain_indigenous,江金妹,無,2448,46.8,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2014.0 township_rep 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦
10013屏東縣,10,mountain_indigenous,蕭惠美 Zuljezulje Qapulu,無,2811,40.1,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10013屏東縣,11,mountain_indigenous,何長成,無,2091,52.4,True,unaligned,none,low,,,,searched combined indigenous-district query; no result naming candidate,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,12,mountain_indigenous,越秋女,無,2786,46.6,True,unaligned,none,low,,,,searched combined indigenous-district query; no result naming candidate,,2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,12,mountain_indigenous,莊景星,無,1767,29.5,False,unaligned,none,low,,,,Searched 2x (lead: 2014 KMT label): no 2025-26 news found; not in KMT Pingtung 2026 township-chief registration snippets,,2014.0 township_rep 中國國民黨* | 2018.0 township_chief 無黨籍及未經政黨推薦 | 2022.0 township_chief 無黨籍及未經政黨推薦*
10013屏東縣,12,mountain_indigenous,鄭鴻耀,無,1428,23.9,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10013屏東縣,13,mountain_indigenous,周陳曉玟,無,2145,66.8,True,unaligned,none,low,,,,LTN 2026-08-31 lists as 無黨籍 registrant (district 13); no party tie found,,2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,13,mountain_indigenous,鄭志偉,無,1067,33.2,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2022.0 township_chief 無黨籍及未經政黨推薦
10013屏東縣,14,mountain_indigenous,侯廉聰 Aljim Pacikel,無,902,28.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2022.0 township_rep 無黨籍及未經政黨推薦*
10013屏東縣,14,mountain_indigenous,李振榮,無,823,26.0,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦
10013屏東縣,15,mountain_indigenous,洪亞男,無,1648,47.0,True,unaligned,none,low,,,,Searched once; no 2025-26 results found,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10013屏東縣,15,mountain_indigenous,劉忠義,無,888,25.3,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2018.0 township_rep 無黨籍及未經政黨推薦 | 2022.0 township_rep 無黨籍及未經政黨推薦
10013屏東縣,16,mountain_indigenous,杜仁勇,無,1340,59.3,True,unaligned,none,low,,,,searched combined indigenous-district query; no result naming candidate,,2014.0 township_rep 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10013屏東縣,16,mountain_indigenous,杜玉慧,無,920,40.7,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10014臺東縣,01,general,林參天,無,2915,6.7,True,unaligned,none,low,,,,Searched. 2026 reports (udn 9501996; CNA 202608050154 snippet) show him attacking KMT magistrate candidate 吳秀華 - anti-KMT lead only; no party endorsement found. KMT Taitung nomination list (LTN 2026-06-10 https://news.ltn.com.tw/news/Taitung/breakingnews/5466950) opened: name not among 19 nominated/9 approved. Past labels all 無.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10014臺東縣,01,general,王文怡,無,2781,6.4,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found. KMT Taitung nomination list (LTN 2026-06-10 https://news.ltn.com.tw/news/Taitung/breakingnews/5466950) opened: name not among 19 nominated/9 approved.,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10014臺東縣,01,general,江家榛,無,2416,5.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10014臺東縣,02,general,張家瑋,無,3024,51.7,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found. KMT Taitung nomination list (LTN 2026-06-10 https://news.ltn.com.tw/news/Taitung/breakingnews/5466950) opened: name not among 19 nominated/9 approved. 2022 township chief as 無.,,2022.0 township_chief 無黨籍及未經政黨推薦
10014臺東縣,03,general,許進榮,無,2798,42.3,True,unaligned,none,low,,,,searched; only issue coverage (ctee 2026-05); no party tie found,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10014臺東縣,04,general,潘貴蘭,無,2388,29.4,True,unaligned,none,low,,,,searched only via combined Taitung queries; no coverage found,,2022.0 council 無黨籍及未經政黨推薦*
10014臺東縣,07,plain_indigenous,陳政宗,無,1864,20.5,True,unaligned,none,low,,,,searched only via combined Taitung queries; no coverage found,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10014臺東縣,07,plain_indigenous,巫化‧巴阿立佑司,無,1333,14.7,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2022.0 township_rep 無黨籍及未經政黨推薦*
10014臺東縣,10,plain_indigenous,楊清順 Cinsun Pawtawan,無,2703,100.0,True,unaligned,none,low,,,,searched only via combined Taitung query; no coverage found,,
10014臺東縣,11,plain_indigenous,高美珠,無,2166,28.9,True,unaligned,none,low,,,,"Lead for B: KMT label 2014/2018/2022 but ran as 無 in 2026; KMT nominated 楊秋珍 in dist 11 (LTN 2026-06-10 list opened; 高美珠 absent). No opened 2025-26 source states her membership status, suspension or 未獲提名; older LTN report of her quitting KMT to run for legislator (pre-2025) not evidence.",,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨
10014臺東縣,11,plain_indigenous,武雪恩,無,1900,25.4,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2014.0 village_chief 無黨籍及未經政黨推薦* | 2018.0 village_chief 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦
10014臺東縣,12,mountain_indigenous,温源田,無,876,37.6,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10014臺東縣,13,mountain_indigenous,胡淑貞,無,908,37.6,True,unaligned,none,low,,,,Searched once; no 2025-26 results found,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10014臺東縣,13,mountain_indigenous,余桂花,無,856,35.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10014臺東縣,16,mountain_indigenous,董昌華,無,1078,60.3,True,unaligned,none,low,,,,Searched; not on KMT Taitung registration list per snippet; no evidence found,,2018.0 council 無黨籍及未經政黨推薦
10014臺東縣,16,mountain_indigenous,李奉祈,無,559,31.3,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10015花蓮縣,01,general,謝國榮,無,2950,6.9,True,unaligned,none,low,,,,"Searched; no 2025-26 source found. Past KMT label 2014-2022; Dec 2022 CNA: after speaker vote he was referred to 黃復興 party discipline (pre-2025, not evidence). Possible lead for B/C (2022-26 KMT caucus) but unverified. Hualien 2026 race: KMT 游淑貞 vs independent 張峻 (backed by council 無黨籍政團聯盟 of 10 councilors) vs independent 魏嘉賢; independent caucus is not a party caucus.",,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨*
10015花蓮縣,01,general,江躍辰,無,2343,5.4,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10015花蓮縣,01,general,傅國淵,無,1866,4.3,False,unaligned,none,low,,,,Searched; nothing found. Past labels DPP 2018 / TPP 2022 - not evidence.,,2014.0 township_rep 民主進步黨* | 2018.0 council 民主進步黨 | 2022.0 council 台灣民眾黨*
10015花蓮縣,01,general,謝豪杰,無,1339,3.1,False,pan_green,B,high,https://news.ltn.com.tw/news/politics/paper/1770107,2026-09-10,違紀參選 花蓮民進黨開除5人黨籍,LTN: DPP Hualien expelled 5 for running without nomination; 謝豪杰 ran DPP for Hualien mayor in 2022 and 未參加黨內初選逕自登記參選縣議員.,,2018.0 township_rep 民主進步黨* | 2022.0 township_chief 民主進步黨
10015花蓮縣,01,general,許願神,無,1305,3.0,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found (only pre-2025 coverage).,,2014.0 township_rep 中國國民黨* | 2018.0 township_rep 無黨籍及未經政黨推薦* | 2020.0 legislator 臺灣前進黨 | 2022.0 township_rep 無黨籍及未經政黨推薦* | 2024.0 legislator 無黨籍及未經政黨推薦
10015花蓮縣,02,general,鄭寶秀,無,4501,52.0,True,unaligned,none,low,,,,"Searched; nothing found for 2025-26. Past KMT label 2022 (2022 speaker vote coverage, pre-2025). Lead for B/C unverified. Hualien 2026 race: KMT 游淑貞 vs independent 張峻 (backed by council 無黨籍政團聯盟 of 10 councilors) vs independent 魏嘉賢; independent caucus is not a party caucus.",,2014.0 township_rep 中國國民黨* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 中國國民黨*
10015花蓮縣,03,general,彭建華,無,4711,9.2,True,pan_green,B,high,https://news.ltn.com.tw/news/politics/paper/1770107,2026-09-10,四年前加入民進黨 這次參選縣議員未辦理黨內登記,LTN: among 5 expelled by DPP Hualien for 違反黨紀 in running for council. Note CEC past labels show KMT township rep 2014-2022 (conflict with article; article says joined DPP ~2022). Expelled DPP member - per rule B -> pan_green.,,2014.0 township_rep 中國國民黨* | 2018.0 township_rep 中國國民黨* | 2022.0 township_rep 中國國民黨*
10015花蓮縣,03,general,鄭乾龍,無,4218,8.3,True,unaligned,none,low,,,,"Searched; nothing found. Past DPP label 2014/2018, 無 2022.",,2014.0 council 民主進步黨* | 2018.0 township_chief 民主進步黨 | 2022.0 council 無黨籍及未經政黨推薦*
10015花蓮縣,03,general,張宸瑋,無,3969,7.8,True,unaligned,none,low,,,,searched; no 2025-26 coverage found,,
10015花蓮縣,03,general,劉靜文,無,2602,5.1,True,unaligned,none,low,,,,"searched; only 2022 CEC list (KMT township rep, pre-2025); no 2025-26 coverage of 2026 run or KMT status found",,2014.0 township_rep 中國國民黨* | 2018.0 township_rep 無黨籍及未經政黨推薦* | 2022.0 township_rep 中國國民黨*
10015花蓮縣,04,general,黃玲蘭,無,3971,26.6,True,unaligned,none,low,,,,"Searched; nothing found. Past KMT 2014/2018, 無 2022.",,2014.0 township_chief 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 無黨籍及未經政黨推薦*
10015花蓮縣,04,general,林宏熙,無,2387,16.0,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
10015花蓮縣,05,plain_indigenous,笛布斯.顗賚,無,4196,34.4,True,unaligned,none,low,,,,searched; no 2025-26 party tie found,,2022.0 council 無黨籍及未經政黨推薦*
10015花蓮縣,05,plain_indigenous,周駿宥,無,1972,16.2,True,unaligned,none,low,,,,"Searched. CNA 2026-10-22 (https://cna.com.tw/news/asoc/202610220408.aspx, opened) calls him 無黨籍花蓮縣議員; no party backing or caucus found. Past KMT label 2014-2022 not evidence.",,2014.0 township_rep 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨*
10015花蓮縣,05,plain_indigenous,那莫 諾虎Namoh Nofu,無,1077,8.8,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10015花蓮縣,06,plain_indigenous,蔡依靜 Lamen‧Panay,無,3520,37.0,True,unaligned,none,low,,,,searched; MOI roster lists party 無; no 2025-26 tie found,,
10015花蓮縣,06,plain_indigenous,邱福順Kacaw.Folaw,無,1906,20.1,False,unaligned,none,low,,,,Searched 2x (lead: 2018 KMT township chief label): no 2025-26 news found; not in DPP's 2026-07-29 indigenous nominee list per search snippet (lead only),,2018.0 township_chief 中國國民黨*
10015花蓮縣,06,plain_indigenous,萬中興,無,1341,14.1,False,unaligned,none,low,,,,Searched 1x (lead: KMT village chief 2014): no 2025-26 party ties found.,,2014.0 village_chief 中國國民黨*
10015花蓮縣,07,plain_indigenous,哈尼.噶照Hani Kacaw,無,2156,37.5,False,unaligned,none,low,,,,"Searched 1x, fetched LTN 5636096 (2026-11-10): listed among companions (無黨籍議員…哈尼.噶照) when VP 蕭美琴 campaigned for DPP-backed 張峻. Attendance only, no endorsement of him; lead, not A. Unaligned.",,
10015花蓮縣,08,mountain_indigenous,田韻馨,無,1842,15.5,False,unaligned,none,low,,,,Searched 2x: snippet says she won a Hualien district 8 by-election as independent (date unclear); no caucus membership or 2025-26 party ties found,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 township_chief 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦
10015花蓮縣,09,mountain_indigenous,伊布.達納畢瑪Ibu·Tanapinma,無,1931,51.0,True,unaligned,none,low,,,,searched; no 2025-26 coverage found,,
10015花蓮縣,10,mountain_indigenous,李忠祥,無,1914,56.2,True,unaligned,none,low,,,,searched; no 2025-26 coverage found,,
10016澎湖縣,01,general,陳海山,無,2295,7.9,True,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10016澎湖縣,01,general,藍凱元,無,1904,6.5,True,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10016澎湖縣,01,general,陳偉澄,無,1818,6.2,True,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,
10016澎湖縣,01,general,莊光大,無,1778,6.1,True,pan_blue,A,medium,https://news.ltn.com.tw/amp/news/politics/breakingnews/5391065,2026-04-02,馬公市選區許國政、莊光大,"Attended KMT magistrate nominee 陳振中's launch press conference; LTN: councilors '都出席力挺'. Councilor backed KMT candidate (not KMT endorsing him), hence medium. 2022 label independent.",,2022.0 council 無黨籍及未經政黨推薦
10016澎湖縣,01,general,歐松林,無,1757,6.0,True,unaligned,none,low,,,,"Opened LTN 5594252 (2026-10-03): campaign office opening, no party link stated.",,
10016澎湖縣,01,general,蘇陳綉色,無,1639,5.6,True,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10016澎湖縣,01,general,吳仁祥,無,1363,4.7,False,unaligned,none,low,,,,Past DPP label (2014 township chief); one search found nothing for 2026.,,2014.0 township_chief 民主進步黨 | 2022.0 township_rep 無黨籍及未經政黨推薦*
10016澎湖縣,01,general,張惠雅,無,1308,4.5,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,
10016澎湖縣,01,general,陳慧娟,無,1012,3.5,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2018.0 council 無黨籍及未經政黨推薦 | 2024.0 legislator 無黨籍及未經政黨推薦
10016澎湖縣,01,general,胡正仁,無,826,2.8,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,
10016澎湖縣,01,general,鄭清發,無,772,2.6,False,unaligned,B,medium,https://news.ltn.com.tw/news/politics/breakingnews/5496756,2026-07-07,宣布退黨,以無黨籍身分參選議員,Former KMT Penghu chapter chair quit KMT to run for council after being denied 馬公市長 nomination. Caution: same article says he will '不支持任何國民黨提名人選' - caller may prefer unaligned. | user decision: unaligned (conflicting evidence),,2018.0 executive 無黨籍及未經政黨推薦 | 2022.0 township_chief 無黨籍及未經政黨推薦
10016澎湖縣,02,general,許育愷,無,2638,32.8,True,unaligned,none,low,,,,Named in LTN 5594252 (2026-10-03) without party info.,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10016澎湖縣,02,general,吳政杰,無,1849,23.0,True,pan_blue,A,medium,https://news.ltn.com.tw/amp/news/politics/breakingnews/5391065,2026-04-02,湖西鄉選區吳政杰,Attended KMT magistrate nominee 陳振中's launch; '都出席力挺'. Past labels KMT 2014-2024; 2026 ballot 無 - membership status in 2026 not verified (possible B).,,2014.0 township_chief 中國國民黨* | 2018.0 township_chief 中國國民黨* | 2022.0 council 中國國民黨* | 2024.0 legislator 中國國民黨
10016澎湖縣,02,general,李麗美,無,1564,19.5,False,pan_blue,A,medium,https://news.ltn.com.tw/news/Penghu/breakingnews/5594252,2026-10-03,致贈好彩頭給李麗美,"KMT Penghu chapter chair 陳雙全 presented gift at her campaign office opening; could be customary courtesy, hence medium. Past labels KMT 2018 township rep.",,2018.0 township_rep 中國國民黨* | 2022.0 township_rep 無黨籍及未經政黨推薦*
10016澎湖縣,03,general,魏睿宏,無,1962,36.4,True,unaligned,none,low,,,,Named in LTN 5594252 (2026-10-03) without party info.,,2022.0 council 無黨籍及未經政黨推薦*
10016澎湖縣,03,general,宋昀芝,無,1887,35.0,True,unaligned,none,low,,,,"Opened LTN 5594252 (2026-10-03): campaign office opening, no party link stated.",,2022.0 council 無黨籍及未經政黨推薦*
10016澎湖縣,03,general,宋萬富,無,1459,27.1,False,unaligned,none,low,,,,Named in LTN 5594252 (2026-10-03) without party info.,,2014.0 township_rep 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 township_chief 無黨籍及未經政黨推薦*
10016澎湖縣,04,general,許月里,無,1704,40.6,True,pan_blue,A,medium,https://news.ltn.com.tw/amp/news/politics/breakingnews/5391065,2026-04-02,西嶼鄉選區許月里,Attended KMT magistrate nominee 陳振中's launch; '都出席力挺'. Past labels independent.,,2014.0 township_chief 無黨籍及未經政黨推薦* | 2018.0 township_chief 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10016澎湖縣,04,general,許嘉峻,無,1459,34.8,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,
10016澎湖縣,04,general,李家萱,無,1030,24.6,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2018.0 township_rep 無黨籍及未經政黨推薦 | 2022.0 township_rep 無黨籍及未經政黨推薦*
10016澎湖縣,05,general,陳佩真,無,1675,69.6,True,pan_blue,A,medium,https://news.ltn.com.tw/amp/news/politics/breakingnews/5391065,2026-04-02,望安鄉選區陳佩真,Attended KMT magistrate nominee 陳振中's launch; '都出席力挺'. Past labels independent.,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10016澎湖縣,05,general,黃榮焜,無,730,30.4,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,
10016澎湖縣,06,general,夏晨榮,無,1239,56.6,True,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2014.0 council 中國國民黨 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦
10016澎湖縣,06,general,張仁和,無,894,40.8,False,pan_blue,A,medium,https://news.ltn.com.tw/amp/news/politics/breakingnews/5391065,2026-04-02,七美鄉選區張仁和等人,Attended KMT magistrate nominee 陳振中's launch; '都出席力挺'. Past labels: KMT 2014 township rep; independent 2018/2022.,,2014.0 township_rep 中國國民黨* | 2018.0 council 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
10017基隆市,01,general,張文彬,無,1393,5.5,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,
10017基隆市,02,general,李嘉濠,無,2948,10.3,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2022.0 council 無黨籍及未經政黨推薦
10017基隆市,03,general,林杏潔,無,4746,23.1,True,unaligned,none,low,,,,Opened udn 9659407 (2026-07-30): described as 無黨新人 (daughter of 林華生); no party endorsement.,,
10017基隆市,03,general,莊傑宇,無,2934,14.3,False,unaligned,none,low,,,,Opened udn 9659407 (2026-07-30): 無黨籍 son of ex-councilor 莊榮欽; no party endorsement.,,
10017基隆市,04,general,莊敬聖,無,1841,7.4,False,pan_blue,U,high,,,,"Searched 4x. Lead only (search snippet, article not located on fetch): 前議員莊敬聖擬捲土重來, among at least 4 seeking KMT nomination in Keelung 中山區. If he was a KMT member who ran 無 after not being nominated this would be B, but no opened page confirms; unaligned. | user decision: pan-blue (user knowledge; evidence U)",,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨
10017基隆市,04,general,李昀靜,無,1634,6.5,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,
10017基隆市,05,general,黃永翔,無,2010,4.8,False,pan_green,B,high,https://udn.com/news/story/124652/9663023,2026-07-31,遭黨中央除名,已喪失提名資格,Was DPP nominee for 安樂區; expelled by DPP over criminal conviction and ran as independent; calls himself '黨友'.,,2022.0 council 無黨籍及未經政黨推薦
10017基隆市,05,general,黃忠賢,無,1799,4.3,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,
10017基隆市,06,general,陳冠羽,無,5906,29.3,True,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2022.0 council 無黨籍及未經政黨推薦*
10017基隆市,06,general,蔡長宏,無,2775,13.8,False,unaligned,none,low,,,,Searched 2x: 2018 KMT label only (lead); no 2025-26 party ties found,,2018.0 council 中國國民黨
10017基隆市,07,general,張耿輝,無,4920,18.2,True,unaligned,none,low,,,,Opened udn 9670072 (2026-08-04): incumbent 七堵 independent; accused by recall leader 戴璟安 of defending city govt (謝國樑) in abuse case - he denies; no party/caucus link found.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2020.0 legislator 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
10017基隆市,07,general,陳安淇,無,1913,7.1,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,
10017基隆市,08,plain_indigenous,拔耐.茹妮老王,無,1999,55.9,True,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2022.0 council 無黨籍及未經政黨推薦
10017基隆市,08,plain_indigenous,陳明建,無,1576,44.1,False,unaligned,none,low,,,,Searched (county-level queries); no 2025-2026 party evidence found.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10017基隆市,09,mountain_indigenous,徐馬政妘,無,375,51.8,True,unaligned,none,low,,,,Opened LTN Keelung 5474911 (2026-06-17): declared mountain-indigenous candidacy; no party info.,,
10017基隆市,09,mountain_indigenous,林崇道 Motu Quyat,無,232,32.0,False,unaligned,none,low,,,,Opened LTN Keelung 5474911 (2026-06-17): declared candidacy; no party info. Past KMT village-chief labels are not evidence.,,2018.0 village_chief 中國國民黨* | 2022.0 village_chief 中國國民黨*
10018新竹市,01,general,林妤芬,無,5034,6.6,True,unaligned,none,low,https://news.ltn.com.tw/news/politics/paper/1780350,2026-11-29,以無黨籍黑馬之姿當選,"Researched; public-interest lawyer, first run; no caucus plan or party support stated.",,
10018新竹市,01,general,黃文政,無,4547,5.9,True,pan_blue,B,medium,https://news.ltn.com.tw/news/politics/breakingnews/5555639,2026-08-28,未獲國民黨竹市黨部提名及徵召的現任市議員黃文政,Outgoing KMT councillor (2022 KMT label) not nominated (court case); KMT nominated his assistant 黃婉嫣 who did not register; he ran as independent. udn 9659261 (2026-07-30): party 'will review 徵召'. Membership implied not explicitly stated -> medium. Also possible C (KMT caucus 2022-26) not verified.,,2014.0 village_chief 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨*
10018新竹市,01,general,劉崇顯,無,3890,5.1,True,pan_green,B,high,https://news.ltn.com.tw/news/politics/breakingnews/5618834,2026-10-26,劉崇顯未獲民進黨提名,改以無黨籍拚連任,Ran in DPP 2026 East-district primary and lost (CNA 2026-04-10 https://www.cna.com.tw/news/aloc/202604100197.aspx: 現任議員劉崇顯未出線); no report of quitting DPP,,2018.0 council 綠黨* | 2022.0 council 綠黨*
10018新竹市,01,general,許登淇,無,1524,2.0,False,pan_blue,A,medium,https://udn.com/news/story/124652/9420003,2026-04-03,在藍白合作架構下,將轉戰競爭更激烈的東區,"Kao Hung-an's mayoral office secretary (2022 TPP nominee); udn says his switch to 東區 was under the blue-white cooperation arrangement to expand TPP seats. Ran as 無黨籍 (udn 2026-07-30, https://udn.com/news/story/124652/9659261). No explicit endorsement quote found; indirect, hence medium.",,2022.0 council 台灣民眾黨
10018新竹市,02,general,田雅芳,無,3143,12.1,False,unaligned,none,low,,,,Searched 2x (incl. caucus): incumbent Hsinchu City south-district councillor; not in 新聯線 政團 list; no party caucus or 2025-26 party ties found,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10018新竹市,02,general,陳鶴文,無,2992,11.6,False,unaligned,none,low,,,,"Searched 3x, fetched udn 9665456 (2026-08-02): 欲以無黨籍參加…南區議員選舉. NPP nominee in 2022 (lead) but no 2025-26 report of NPP membership, backing or quitting found; unaligned.",,2022.0 council 時代力量
10018新竹市,04,general,鄭慶欽,無,5217,8.6,True,unaligned,none,low,https://www.cna.com.tw/news/aipl/202512040287.aspx,2025-12-04,未來將回到無黨身分,"Researched; left 新聯線政團 (mixed TPP/independent council group, not a party caucus) to return to independent status. No party support found.",,2022.0 council 無黨籍及未經政黨推薦*
10018新竹市,04,general,孫宗孝,無,3282,5.4,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10018新竹市,04,general,彭昆耀,無,3115,5.1,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10018新竹市,05,general,吳國寶,無,4347,10.8,True,unaligned,none,low,,,,"udn 2026-07-22 (9644377) lists as independent with local base, no camp; LTN 2026-10-26 says he backed ex-DPP-member 劉崇顯 (personal support, not party evidence)",,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10018新竹市,05,general,陳啓源,無,4233,10.5,True,unaligned,none,low,,,,udn 2026-07-22 (9644377) lists 陳啟源 as independent with local base; no party/camp tie found,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10018新竹市,05,general,蔡志堅,無,2977,7.4,False,pan_blue,B,medium,https://udn.com/news/story/124652/9644377,2026-07-22,原民眾黨籍樹下里長蔡志堅退黨後改以無黨籍參選,"Conflict: quit TPP to run as independent, but ran against TPP nominee 葉國文 in the same district (Xiangshan); per rule, unaligned. | user decision: pan-blue (B: quit the TPP to run; running against its nominee is not counted as a conflict)",,2022.0 village_chief 無黨籍及未經政黨推薦*
10018新竹市,07,mountain_indigenous,楊家玲,無,155,15.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
10020嘉義市,01,general,洪斐昭,無,4702,8.0,True,unaligned,none,low,https://udn.com/news/story/125080/9908313,2026-11-28,新人洪斐昭首次參選拿下第5名,Researched; independent newcomer (CNA 202611280202 also no camp). udn article mentions him in paragraph near 藍營 candidates but never labels him; no evidence.,,
10020嘉義市,01,general,顏翎熹,無,3443,5.9,True,unaligned,none,low,,,,search snippets (udn 9654893) describe independent incumbent seeking re-election; no party backing found,,
10020嘉義市,01,general,郭文居,無,2897,5.0,False,unaligned,none,low,,,,Searched 2x: 2014 KMT label only (lead); not in KMT Chiayi 2026 registration list per snippet; no 2025-26 party ties found,,2014.0 council 中國國民黨* | 2022.0 council 無黨籍及未經政黨推薦
10020嘉義市,01,general,柯莉絲汀,無,2057,3.5,False,unaligned,none,low,,,,Searched 1x: snippets (udn/LTN 2025-26) describe her as 無黨無派 influencer with no party or faction support; not opened. No party ties found.,,
10020嘉義市,02,general,王浩,無,6005,8.3,True,unaligned,none,low,https://udn.com/news/story/125080/9908313,2026-11-28,退出時代力量、無黨籍的王浩連任成功,Left 時代力量 (2022 時力 nominee); search snippets say 時力-led 台灣前進陣線 backed 林詩涵 in West district instead. Quit party + party backed rival = conflicting/no current tie; unaligned.,,2022.0 council 時代力量*
10020嘉義市,02,general,黃政融,無,4084,5.6,True,pan_blue,A,high,https://news.ltn.com.tw/news/politics/breakingnews/5618387,2026-10-25,張啓楷今天為無黨籍嘉市西區議員候選人黃政融競選總部成立站台,KMT-TPP joint mayoral nominee 張啓楷 (藍白共推) campaigned at his HQ launch; KMT mayor 黃敏惠 (his aunt) also attended,,
10020嘉義市,02,general,陳姿妏,無,4072,5.6,True,unaligned,none,low,,,,udn 2026-02-07 (9315354) lists her as independent speaker; no party/mayoral backing found,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10020嘉義市,02,general,黃敏修,無,3450,4.8,True,unaligned,none,low,,,,"udn 2026-02-07 (9315354) lists him among independent councilors (so not DPP caucus); search snippet says he left/was expelled from DPP in Dec 2022 (pre-2025); snippet calls him part of 王美惠 team (chinatimes 20260429900369, fetch 403) - lead only",,2022.0 council 民主進步黨*
10020嘉義市,02,general,李忠曆,無,3116,4.3,True,unaligned,none,low,,,,udn 2026-02-07 (9315354) lists him as independent councilor; no party/mayoral backing found,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
10020嘉義市,02,general,林子淨,無,2847,3.9,True,unaligned,none,low,,,,searched; no 2025-26 coverage found,,
10020嘉義市,02,general,蔡坤叡,無,2515,3.5,True,unaligned,none,low,,,,udn 2026-02-07 (9315354) lists him as independent councilor; no party/mayoral backing found,,2022.0 council 無黨籍及未經政黨推薦*
10020嘉義市,02,general,孫貫志,無,1735,2.4,False,pan_green,A,high,https://news.ltn.com.tw/news/politics/breakingnews/5618387,2026-10-25,邀請王美惠站台,為選戰進行最後衝刺,DPP Chiayi City mayoral candidate 王美惠 spoke at his campaign HQ launch (跨黨派輔選; LTN). No KMT figure reported at his event.,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
63000臺北市,01,general,陳怡潔,無,14575,5.0,True,pan_blue,P,high,https://claude.ai/artifact/VFYqmQxfkwzKrVAMqCg4AG,,,classification from the published Taipei page (sources in its appendix) | Ran as 無黨籍 (LTN 2026-10-15 /5607448 says 以無黨籍身分參選 不分黨派). Campaign HQ opening attended by KMT legislator 洪孟楷 (LTN 2026-10-04 /5595025) - not a party/mayoral-candidate endorsement so not type A. Not in KMT primary list per search snippets. Former PFP legislator; daughter of ex-councillor 陳政忠. Earlier page labelled pan-blue; this cycle evidence insufficient.,,
63000臺北市,01,general,陳重文,無,6031,2.1,False,pan_blue,P,high,https://claude.ai/artifact/VFYqmQxfkwzKrVAMqCg4AG,2026-10-28,今年因涉案而未獲提名 以無黨籍身分爭取連任,classification from the published Taipei page (sources in its appendix) | Three-term KMT councillor; KMT Taipei chapter said 一審有罪 makes him ineligible (udn 2026-02-26 https://udn.com/news/story/124652/9346789 where he said as KMT member he would follow party mechanism). LTN says 曾是國民黨籍 - membership status at filing unclear but ran as unnominated KMT member/ex-member.,,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨*
63000臺北市,04,general,陳怡君,無,6609,3.4,False,pan_green,P,high,https://claude.ai/artifact/VFYqmQxfkwzKrVAMqCg4AG,2026-03-13,因案遭停權的議員陳怡君,classification from the published Taipei page (sources in its appendix) | DPP councillor suspended by DPP 廉政會 (停權) and dropped from primary; vowed to run anyway; ran as 無 on ballot. Search snippets say she registered 脫黨參選. Past labels DPP 2018/2022.,,2018.0 council 民主進步黨* | 2022.0 council 民主進步黨*
63000臺北市,05,general,徐立信,無,20001,11.0,True,pan_blue,P,high,https://claude.ai/artifact/VFYqmQxfkwzKrVAMqCg4AG,,,classification from the published Taipei page (sources in its appendix) | Searches describe him as 無黨籍議員 not in KMT caucus (snippet: udn 9748864 he asked 蔣萬安 to campaign for councillors; 蔣 noncommittal). No opened source shows party backing or caucus membership. Earlier page labelled pan-blue; not supported by this-cycle evidence found.,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2020.0 legislator 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
63000臺北市,07,plain_indigenous,林筱薇 Icyang Tamana,無,1563,31.6,False,unaligned,none,low,,,,Searched 1x: only an undated PTT post naming her as Taipei plains-indigenous candidate; no 2025-26 party ties found,,
63000臺北市,08,mountain_indigenous,孔垂崢 Haisul Islituan,無,759,20.2,False,pan_blue,B,high,https://news.ltn.com.tw/news/politics/breakingnews/5632168,2026-11-06,決議予以開除黨籍處分,"Searched 1x, page opened. KMT member (Daan) registered for district 8 mountain-indigenous seat without nomination; KMT Taipei expelled him (committee 10-16); KMT nominee there was 李傅鈺婷.",,
64000高雄市,01,general,鍾炳光,無,8080,12.9,False,unaligned,none,low,,,,"Searched; snippets: retired district chief, backed by outgoing independent councilor 朱信強 (not a party); no party tie found",,
64000高雄市,02,general,鄭東元,無,6134,8.0,False,unaligned,none,low,,,,Searched 2x (KMT council 2018/2022 lead): no 2025-26 coverage of him found; no evidence of 停權/退黨 or backing.,,2018.0 council 中國國民黨 | 2022.0 council 中國國民黨
64000高雄市,03,general,張騏晟,無,15799,11.8,False,unaligned,none,low,https://news.ltn.com.tw/news/politics/breakingnews/5604045,2026-10-12,此次以無黨參選高雄市第三選區市議員,"Fetched: independent, son of ex-Kaohsiung marine bureau chief 張漢雄; no party membership/backing stated; vote-buying probe",,
64000高雄市,04,general,陳冠宇,無,13783,7.0,False,unaligned,none,low,,,,Searched; snippets: son of 無黨籍 councilor 陳善慧 succeeding him; no party tie found,,
64000高雄市,07,general,張博洋,無,18894,10.9,True,pan_green,A,high,https://www.nownews.com/news/6890448,2026-11-08,賴瑞隆與張博洋聯合競選總部正式成立,Joint campaign HQ with DPP mayoral candidate 賴瑞隆 in 三民區. Also udn 2026-07-23 (9644991): 退出台灣基進黨後與民進黨交好. Past label 台灣基進 2022.,,2022.0 council 台灣基進*
64000高雄市,07,general,曾俊傑,無,12230,7.0,True,pan_green,C,medium,https://udn.com/news/story/124652/9644991,2026-07-23,揮別國民黨 還加入民進黨黨團運作,Deputy speaker; elected 2022 as KMT then allied with DPP for deputy speakership and joined DPP caucus operations. Past labels KMT 2014-2022.,,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨*
64000高雄市,10,general,李順進,無,18053,10.3,True,unaligned,none,low,,,,udn 2026-07-29 (9656869): 無盟 incumbent 跨黨派服務 seeking 7th term; no party relation stated. Further search not possible (budget exhausted). Past labels 無黨團結聯盟.,,2014.0 council 無黨團結聯盟* | 2018.0 council 無黨團結聯盟* | 2022.0 council 無黨團結聯盟*
64000高雄市,10,general,吳銘賜,無,17493,10.0,True,unaligned,none,low,,,,Lead only: 是新聞網 article (vocus.cc mirror no date) says running as 無黨籍 with billboard of incumbent mayor 陳其邁 相挺 - incumbent mayor not the DPP mayoral candidate so not type A as defined. udn 2026-07-29 (9656869): 由民進黨轉台聯; nephew 吳昱鋒 is DPP nominee in same district (split-vote risk). Past labels DPP 2014 / 台聯 2018 2022. Whether still 台聯 member unconfirmed.,,2014.0 council 民主進步黨* | 2018.0 council 台灣團結聯盟* | 2022.0 council 台灣團結聯盟*
64000高雄市,13,mountain_indigenous,陳幸富,無,2148,55.8,True,unaligned,none,low,,,,searched; no 2025-26 coverage found (udn snippet: Kaohsiung mountain seats incl. one independent; not confirmed as him),,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
64000高雄市,14,mountain_indigenous,高忠德 Takiludun.Anu,無,1412,40.5,True,unaligned,none,low,https://udn.com/news/story/124652/9665201,2026-08-02,與民進黨友好…等同被民進黨保送參選,"Borderline: udn says DPP-friendly and DPP nominated no one in all three Kaohsiung mountain indigenous districts ('effectively sent forward'); reporter characterization, no targeted DPP endorsement/禮讓 for him found; left unaligned, possible pan_green A on review",,
64000高雄市,14,mountain_indigenous,林錫閔,無,931,26.7,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2022.0 council 無黨籍及未經政黨推薦
64000高雄市,15,mountain_indigenous,金禾雅,無,1966,45.2,False,unaligned,none,low,,,,Searched 1x: snippet (newtalk 2026-09-02) says first-time candidate; KMT nominated 陳奕蓁 in this district; no party ties found.,,
65000新北市,04,general,李翁月娥,無,24694,8.0,True,pan_blue,A,high,https://udn.com/news/story/124652/9654262,2026-07-27,懇請鄉親支持李翁月娥及現場里長連任,KMT New Taipei mayoral candidate 李四川 attended her 三蘆市政說明會 and asked voters to back her (reporter paraphrase); also reportedly attended in June. | past_labels: 2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2020.0 legislator 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦* (lead only),,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2020.0 legislator 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
65000新北市,04,general,蕭告,無,20282,6.6,False,unaligned,none,low,,,,1 search: no 2026 coverage found.,,
65000新北市,08,general,蘇泓欽,無,24908,7.8,True,unaligned,none,low,,,,2 searches (incl. with 李四川): no 2026 party/caucus evidence found. | past_labels: 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦* (lead only),,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
65000新北市,09,general,張柏詠,無,9875,5.2,False,unaligned,none,low,,,,1 search: no coverage found.,,
65000新北市,11,general,郭書成,無,13317,9.9,False,unaligned,none,low,https://www.mirrormedia.mg/story/20261016pol003,2026-10-16,正以無黨籍身分參選新北市第11選區市議員,Opened profile: independent ex-village chief (sunflower-era activist); no party endorsement or membership mentioned; says he avoided parties to not be tied down. | past_labels: 2018.0 village_chief 無黨籍及未經政黨推薦* | 2022.0 village_chief 無黨籍及未經政黨推薦* (lead only),,2018.0 village_chief 無黨籍及未經政黨推薦* | 2022.0 village_chief 無黨籍及未經政黨推薦*
65000新北市,12,plain_indigenous,宋雨蓁Nikar‧Falong,無,3085,20.6,True,unaligned,none,low,,,,2 searches: snippets say she quit KMT in March 2022 over policy disagreement (pre-cycle; not evidence); no 2025-26 party support found. Past label KMT 2014.,,2014.0 council 中國國民黨*
65000新北市,12,plain_indigenous,忠仁‧達祿斯,無,1093,7.3,False,unaligned,none,low,,,,Searched 1x (lead: KMT councillor 2014): no 2025-26 reports found; DPP New Taipei indigenous nominees were others.,,2014.0 council 中國國民黨
65000新北市,13,mountain_indigenous,馬見Lahuy‧Ipin,無,2727,34.2,True,unaligned,none,low,,,,1 search: snippet describes him as 無黨團結聯盟籍 councillor (undated); no 2025-26 green/blue evidence found.,,
65000新北市,13,mountain_indigenous,羅美菁,無,948,11.9,False,unaligned,none,low,,,,"Searched 2x: a 2022 report names a 羅美菁 as New Taipei 原民局長 appointed by 侯友宜 (KMT), identity with this candidate unconfirmed and pre-2025; no 2025-26 party ties found.",,
66000臺中市,02,general,陳廷秀,無,22777,17.0,True,pan_blue,A,high,https://news.ltn.com.tw/news/politics/breakingnews/5625881,2026-11-01,國民黨台中市長候選人江啟臣也到場站台力挺,"KMT mayoral candidate 江啟臣 and mayor 盧秀燕 at her campaign HQ opening. Also named by KMT Taichung chapter chair as KMT-friendly independent (LTN 5500288, 2026-07-10). | past_labels: 2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦* (lead only)",,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
66000臺中市,03,general,林汝洲,無,11863,10.6,True,unaligned,none,low,,,,"Lead only: son 林昊佑 (outgoing councillor who stepped aside for father) was named by KMT Taichung chapter chair as KMT-friendly independent (LTN 5500288, 2026-07-10), but 林汝洲 himself not mentioned. Past labels KMT 2014/2018 (not evidence).",,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨*
66000臺中市,04,general,王朝坤,無,11070,9.5,False,unaligned,none,low,,,,Searched; udn snippet: 無黨籍老將 returning; no party tie found,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦*
66000臺中市,05,general,徐瑄灃,無,19817,14.2,True,pan_blue,A,medium,https://news.ltn.com.tw/news/Taichung/breakingnews/5500288,2026-07-10,像無黨籍的林昊佑、徐瑄灃及陳廷秀,KMT Taichung chapter chair 蘇柏興 named him among KMT-friendly independents with whom 江啟臣 can 造勢及站台; no specific joint event opened. | past_labels: 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦* (lead only),,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
66000臺中市,05,general,林鈺梅,無,8744,6.2,False,pan_green,B,high,https://news.ltn.com.tw/news/politics/breakingnews/5576490,2026-09-16,未經提名違紀參選,"DPP member lost primary, filed 退黨 Aug 28, expelled by Taichung DPP for running without nomination; no opposition to DPP mayoral nominee reported",,
66000臺中市,07,general,吳佩芸,無,16735,17.5,True,unaligned,none,low,,,,1 search: snippets say she quit NPP Feb 2024 and joined no caucus; says she has no major-party backing for 2026. Not opened; past labels NPP 2018/2022.,,2018.0 council 時代力量 | 2022.0 council 時代力量*
66000臺中市,08,general,段體佩,無,19445,11.9,True,unaligned,none,low,,,,Searched; udn 9602265 (snippet) describes 素人 independent run in 北屯; no party backing found.,,2020.0 legislator 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦
66000臺中市,11,general,周啓揚,無,11838,10.7,False,pan_blue,B,high,https://cna.com.tw/news/aloc/202609080103.aspx,2026-09-08,周啓揚違紀選台中市議員 國民黨撤銷黨籍,KMT member; Taichung KMT revoked membership for running in violation of party discipline; no stance on mayoral nominee reported,,
66000臺中市,11,general,楊寶楨,無,6630,6.0,False,pan_blue,B,medium,https://udn.com/news/story/124652/9516552,2026-05-21,昨晚宣布退黨,獨立參選台中市東南區市議員選舉,"Former TPP spokesperson; quit TPP (2026-05-20) to run after TPP did not nominate her; cited 黨內霸凌文化 and criticised Huang Kuo-chang's leadership. No TPP nominee in Taichung dist 11 (CEC 2026 list), so no direct clash with a TPP candidate. B on 退黨 to run; hostile exit lowers confidence.",,
66000臺中市,12,general,閻泰利,無,7503,7.3,False,pan_blue,B,high,https://news.ltn.com.tw/news/Taichung/breakingnews/5433637,2026-05-12,因無法獲黨提名而退黨,KMT member and 太平區中山里 village chief; quit KMT to run after KMT nominated two incumbents in 太平 (LTN). Note: runs against KMT nominees in same district.,,2014.0 village_chief 中國國民黨* | 2018.0 village_chief 中國國民黨* | 2022.0 village_chief 中國國民黨*
66000臺中市,12,general,張書華,無,7074,6.9,False,pan_blue,B,high,https://cna.com.tw/news/aloc/202609080103.aspx,2026-09-08,撤銷違紀登記參選台中市議員的張書華及周啓揚黨籍,"Searched 1x, page opened. KMT member (former Taichung KMT deputy chair per snippet) registered without nomination; KMT Taichung revoked membership. Ran against KMT nominees in Taiping (per snippet).",,
66000臺中市,13,general,張滄沂,無,11553,7.9,False,unaligned,none,low,,,,"Searched; udn snippet: 無黨籍, narrowly lost last time; no party tie found",,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦
66000臺中市,13,general,段中仁,無,5976,4.1,False,unaligned,none,low,,,,Searched 2x: udn 9649628 snippet says he lost in 2022 and is running again in 大里霧峰; no party ties 2025-26 found.,,2022.0 council 無黨籍及未經政黨推薦
66000臺中市,15,plain_indigenous,楊玉花,無,2203,39.1,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found,,
66000臺中市,16,mountain_indigenous,黃永光,無,1371,29.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,2018.0 council 無黨籍及未經政黨推薦
66000臺中市,17,mountain_indigenous,呂秀惠,無,1511,30.9,False,unaligned,none,low,,,,"Searched 1x: only a DPP indigenous-affairs event listing her as Taichung indigenous women's association speaker (snippet, date unclear, not opened; attending is not A); no 2025-26 party ties found",,
66000臺中市,17,mountain_indigenous,瓦力司.比尤,無,970,19.8,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
67000臺南市,01,general,趙昆原,無,8629,8.7,False,unaligned,none,low,,,,Searched; snippets: incumbent 無黨籍; no party tie found,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
67000臺南市,01,general,張新斛,無,4179,4.2,False,unaligned,none,low,,,,"Searched 1x, fetched newtalk 2026-07-31: listed as 無黨籍, former political aide, seen as inheriting ex-councillor 張世賢 base; no party backing mentioned.",,
67000臺南市,02,general,陳昆和,無,14108,16.7,True,unaligned,none,low,,,,Searched; no party backing/caucus found in 2025-26 coverage.,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦* | 2024.0 legislator 無黨籍及未經政黨推薦
67000臺南市,02,general,王詩媛,無,9275,11.0,False,unaligned,none,low,,,,"Searched; newtalk snippet: 無黨籍 newcomer, daughter of 王文宗; no party tie found",,
67000臺南市,03,general,施朝清,無,4695,7.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
67000臺南市,04,general,周奕齊,無,12801,67.0,True,unaligned,none,low,,,,"Snippet (udn 9635139): DPP nominated 賴懋慶 against him in single-seat 第四選區; mother is ex-PFP legislator 周陳秀霞 (family, not evidence).",,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
67000臺南市,05,general,李文俊,無,12341,13.5,True,unaligned,none,low,,,,Snippet: ex-KMT deputy speaker expelled over 2022 speaker vote (pre-2025). No 2025-26 party backing found.,,2014.0 council 中國國民黨 | 2018.0 council 中國國民黨* | 2022.0 council 中國國民黨*
67000臺南市,06,general,郭信良,無,17547,16.3,True,unaligned,none,low,,,,"Lead only: newtalk 2026-09-07 (opened) lists him among 無黨籍 '挺妃派' councillors (his support for DPP mayoral nominee 陳亭妃, not party acting for him). Snippet (udn 9279324): 陳亭妃 said he had no role in her primary; DPP 挺憲派 demanded cutting ties. Ex-DPP, out of party pre-2025. Conflicting -> unaligned.",,2014.0 council 民主進步黨* | 2018.0 council 民主進步黨* | 2022.0 council 無黨籍及未經政黨推薦*
67000臺南市,06,general,黃麗招,無,9910,9.2,True,unaligned,none,low,,,,"Lead only: newtalk 2026-09-07 (opened) lists her among 無黨籍 '挺妃派' councillors (her support for DPP nominee, not party acting for her). Ex-KMT (past label 2014).",,2014.0 council 中國國民黨 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
67000臺南市,06,general,邱昭勝,無,7736,7.2,True,unaligned,none,low,,,,"Lead only: newtalk 2026-09-07 (opened) lists him among 無黨籍 '挺妃派' councillors (his support for DPP nominee, not party acting for him).",,2022.0 council 無黨籍及未經政黨推薦*
67000臺南市,06,general,林緯,無,7625,7.1,False,unaligned,none,low,https://newtalk.tw/news/view/2026-09-07/1058320,2026-09-07,無黨籍挑戰者林緯,"Fetched: independent, former LY aide (legislator unnamed); not placed in any camp",,2018.0 council 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦
67000臺南市,07,general,林冠維,無,26220,21.7,True,unaligned,none,low,,,,Searched 2x; incumbent (永康). 2024 news: member of council 無黨團結聯盟 (not a camp party). No 2025-26 party backing found.,,2022.0 council 無黨團結聯盟*
67000臺南市,09,general,李伯利,無,11391,11.1,True,unaligned,none,low,,,,Searched; no 2025-26 coverage found.,,2020.0 legislator 安定力量 | 2022.0 council 無黨籍及未經政黨推薦
67000臺南市,10,general,曾之婕,無,14592,15.8,True,pan_blue,A,high,https://cna.com.tw/news/aipl/202610110181.aspx,2026-10-11,尋求連任的無黨籍市議員曾之婕競選總部成立造勢活動站台,KMT mayoral nominee 謝龍介 stumped at her campaign HQ launch rally (CNA).,,2022.0 council 無黨籍及未經政黨推薦*
67000臺南市,10,general,李宗霖,無,13486,14.6,True,pan_green,C,high,https://news.ltn.com.tw/news/politics/breakingnews/5636675,2026-11-11,目前更擔任南市議會民進黨團副總召,"Also A: 黃偉哲, DPP mayoral nominee 陳亭妃, 林俊憲 attended HQ launch to campaign for him (same LTN article). Quit 台灣基進 June 2025 (TVBS snippet).",,2014.0 village_chief 無黨籍及未經政黨推薦* | 2018.0 council 基進黨 | 2018.0 village_chief 無黨籍及未經政黨推薦* | 2022.0 council 台灣基進* | 2022.0 village_chief 無黨籍及未經政黨推薦*
67000臺南市,11,general,許又仁,無,15053,14.9,True,unaligned,none,low,,,,"Lead only: udn 9663909 (2026-08-01, opened) says he 加入立委陳亭妃台南市長黨內初選團隊 (his own action, not DPP backing him).",,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦
67000臺南市,11,general,杜素吟,無,12703,12.6,True,unaligned,none,low,,,,"udn 9663909 (2026-08-01, opened): KMT 向來禮讓不提名 her, but this cycle KMT nominated 翁語含 in the district; she is 無黨團結聯盟. No 2026 禮讓 -> unaligned.",,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨團結聯盟*
67000臺南市,11,general,吳禹寰,無,10401,10.3,False,unaligned,none,low,,,,Searched; snippets: incumbent 無黨籍 Tainan councilor; no party tie found,,2014.0 council 無黨籍及未經政黨推薦 | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
67000臺南市,12,plain_indigenous,李美素,無,1208,63.6,True,unaligned,none,low,https://udn.com/news/story/124652/9666549,2026-08-03,三度獲綠營提名選此區、本屆無黨競選,Past DPP nominations (pre-2025) and ex-DPP legislator aide; this cycle runs 無黨 with no DPP backing or membership status reported; not B without evidence she is a current member,,2014.0 council 民主進步黨 | 2018.0 council 民主進步黨 | 2022.0 council 無黨籍及未經政黨推薦
67000臺南市,13,mountain_indigenous,施余興望 Tjakumay Tagaw,無,1247,56.9,True,unaligned,none,low,,,,Searched; snippets describe him as incumbent 無黨籍 with KMT nominating rival 辛晴晴; no party tie found,,
68000桃園市,01,general,王妃天崩開局穿越整頓霸凌者佀廣洋,無,29533,12.7,True,unaligned,none,low,https://news.pts.org.tw/article/826328,2026-09-09,,Satirical candidate (influencer) who legally renamed to mock 佀廣洋; PTS article mentions no party backing.,,
68000桃園市,01,general,李凱倫,無,11456,4.9,True,pan_blue,A,high,https://news.ltn.com.tw/news/politics/breakingnews/5633422,2026-11-08,是最好的接棒人選,KMT mayoral candidate 張善政 (and ex-KMT chair 朱立倫) spoke at her HQ launch; daughter of deputy speaker 李曉鐘.,,
68000桃園市,01,general,于北辰,無,10728,4.6,False,unaligned,none,low,,,,"No 2025-26 party backing found in search snippets (only AI poll mention as 無黨籍). Past label 2022 independent; former KMT figure (pre-2025, not evidence). Past labels: 2022.0 council 無黨籍及未經政黨推薦*.",,2022.0 council 無黨籍及未經政黨推薦*
68000桃園市,01,general,佀廣洋,無,5819,2.5,False,unaligned,none,low,https://news.ltn.com.tw/news/politics/breakingnews/5562095,2026-09-03,原獲國民黨提名,後因爭議放棄提名,"Son of KMT legislator 萬美玲; gave up KMT nomination (UDN 2026-07-14) and registered as independent; KMT chapter said it would 予以祝福. Opened sources never state he is a KMT member, so B not established; strong lean pan_blue.",,
68000桃園市,02,general,呂學記,無,4003,4.5,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
68000桃園市,03,general,段林淑婷,無,9233,9.1,False,pan_blue,A,high,https://news.ltn.com.tw/news/politics/paper/1776028,2026-10-26,八德區議員候選人段林淑婷聯合競總成立站台,KMT mayoral candidate 張善政 stood at joint HQ launch (event 2026-10-25).,,
68000桃園市,04,general,劉勝全,無,9431,11.4,False,unaligned,none,low,,,,Lead: elected 2022 as DPP (past_labels) and sitting councillor in 2025; now on ballot as 無. Could be B or C (DPP caucus 2022-26) but no opened 2025-26 page states his party status. Needs follow-up.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 民主進步黨*
68000桃園市,04,general,郭麗華,無,8183,9.9,False,pan_green,B,high,https://news.tvbs.com.tw/politics/3215390,2026-05-28,即日起退出民進黨,Quit DPP to run as independent in 蘆竹 after DPP nominated 許清順 and 胡家智; said she wanted the women's seat to stay in the 本土陣營 (per search snippet).,,2014.0 council 民主進步黨* | 2018.0 council 民主進步黨* | 2022.0 council 民主進步黨
68000桃園市,05,general,吳文凱,無,4291,10.4,False,unaligned,none,low,,,,Searched 2x (2020 台灣維新 lead): no 2025-26 coverage or party ties found.,,2020.0 legislator 台灣維新
68000桃園市,06,general,江國輝,無,6701,14.3,False,unaligned,none,low,,,,Searched once; nothing found.,,
68000桃園市,07,general,謝美英,無,13825,6.6,True,pan_blue,A,high,https://news.ltn.com.tw/news/politics/paper/1776028,2026-10-26,為無黨籍中壢區議員謝美英(右) 站台,Photo caption: KMT mayoral candidate 張善政 stood for her; joint HQ launch 2026-10-25.,,2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
68000桃園市,07,general,劉曾玉春,無,9886,4.7,True,unaligned,none,low,,,,Searched; no 2025-26 party backing found. Not named in 張善政 站台 article (LTN 1776028). Snippet lead: appeared with KMT legislator 呂玉玲 (page not located). Past labels: 2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*.,,2014.0 council 無黨籍及未經政黨推薦* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
68000桃園市,07,general,毛嘉慶,無,7621,3.6,False,pan_blue,B,medium,https://www.storm.mg/article/11091666,2025-12-30,近日加入民眾黨成為終身黨員,"TPP (pan-blue 2026) lifetime member from Dec 2025, sought TPP Zhongli (dist 07) nomination; primary suspended by TPP 中評會 2026-02-03 (mirrormedia 20260203edi056) and he withdrew; ran as 無黨籍 (storm 11170154, 2026-10-06: 中壢區無黨籍市議員參選人). No report found of him quitting TPP, so B (member running without nomination); medium because membership after withdrawal is unconfirmed. Searched 3x, fetched 4 pages.",,2022.0 council 無黨籍及未經政黨推薦
68000桃園市,07,general,李欣,無,7600,3.6,False,unaligned,none,low,,,,Searched 2x (name + Taoyuan dist 07/中壢): candidate not found in 2025-26 news; no party ties found,,
68000桃園市,08,general,白丞堯,無,5787,5.3,False,unaligned,none,low,,,,"Searched 1x + opened LINE TODAY/桃園電子報 2026-08-05 (https://today.line.me/tw/v3/article/PG5Vozo): ran with self-made '楊家俍議員推薦' signs (DPP councillor not running); article says Yang had not publicly backed him and DPP nominated 王珮毓, 劉仁照. Not party action: unaligned.",,
68000桃園市,09,general,黃盈淇,無,15251,17.6,True,pan_green,B,high,https://news.ltn.com.tw/news/Taoyuan/breakingnews/5499483,2026-07-09,已在6月29日完成退黨手續,Lost DPP primary in 楊梅 (district 9) and quit DPP to run as independent.,,2018.0 village_chief 無黨籍及未經政黨推薦*
68000桃園市,09,general,李家興,無,10046,11.6,False,pan_blue,A,high,https://news.ltn.com.tw/news/politics/paper/1776028,2026-10-26,楊梅區無黨籍議員李家興,KMT mayoral candidate 張善政 stood at joint HQ launch (2026-10-25) incl. 李家興. Past label KMT 2014 (not evidence). Former convenor of 無黨團結聯盟 caucus (snippet).,,2014.0 council 中國國民黨* | 2018.0 council 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
68000桃園市,10,general,吳平娥,無,6618,11.0,False,unaligned,none,low,,,,Searched once; not mentioned in 龍潭 race coverage.,,
68000桃園市,11,general,邱文威,無,13982,51.6,True,unaligned,none,low,,,,Searched twice; only 2022 CEC bulletin found (former councillor/legislator aide). No 2025-26 party evidence. Past labels: 2022.0 council 無黨籍及未經政黨推薦.,,2022.0 council 無黨籍及未經政黨推薦
68000桃園市,12,general,許更生,無,11760,31.5,False,unaligned,none,low,,,,Searched once; nothing relevant found. Past labels: 2018.0 village_chief 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*.,,2018.0 village_chief 無黨籍及未經政黨推薦* | 2022.0 council 無黨籍及未經政黨推薦*
68000桃園市,13,plain_indigenous,楊進福,無,2855,18.7,True,unaligned,none,low,,,,Searched; council reports call him 無黨籍 incumbent. Past labels KMT 2014/2018 (not evidence). No 2025-26 party backing found. Past labels: 2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 無黨籍及未經政黨推薦*.,,2014.0 council 中國國民黨* | 2018.0 council 中國國民黨* | 2022.0 council 無黨籍及未經政黨推薦*
68000桃園市,13,plain_indigenous,張秀菊,無,2307,15.1,False,unaligned,none,low,,,,Searched (with other indigenous candidates); nothing found. Past labels: 2018.0 council 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*.,,2018.0 council 無黨籍及未經政黨推薦 | 2022.0 council 無黨籍及未經政黨推薦*
68000桃園市,13,plain_indigenous,李鴻志,無,1161,7.6,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found.,,
68000桃園市,14,mountain_indigenous,蘇偉恩,無,2125,14.5,True,unaligned,none,low,,,,Searched; nothing found. DPP nominee in this district is 謝卓儒. Past labels: 2022.0 council 無黨籍及未經政黨推薦*.,,2022.0 council 無黨籍及未經政黨推薦*
68000桃園市,14,mountain_indigenous,曾庭筠,無,1883,12.8,True,unaligned,none,low,,,,Searched twice; nothing found.,,
68000桃園市,14,mountain_indigenous,邱伯倫,無,1116,7.6,False,unaligned,none,low,,,,Searched 1x: no 2025-26 party ties found (DPP Taoyuan mountain-indigenous nominee was 謝卓儒),,

expected output: OUT/allcounty_researched/results.md

# Results: Taiwan 2026, mayoral vs council votes (all 22 counties)

Stations matched across ballots: 18,248 in 22 counties; general council districts: 161
Valid votes: mayor 12,556,956, council (all districts) 12,450,093; difference by county -1.1% to +1.9% of council
Nationwide council: pan-green 41.3, pan-blue 44.2 (TPP 4.9), unaligned 14.6
Nationwide mayoral: green standard-bearers 48.5, blue standard-bearers 49.3, others 2.2

## A. County table (percent of valid votes on each ballot; gaps in points)
        county  c_G  c_B  c_TPP  c_U  m_G  m_B  m_U  gap_G  gap_B  two_gap winner_camp  valid_diff_pct
        Taipei 44.9 54.4    9.2  0.7 45.7 53.7  0.6    0.8   -0.7      0.8           B             1.2
    New Taipei 45.0 50.7    8.1  4.3 48.2 51.2  0.5    3.3    0.5      1.5           B             1.1
      Taichung 43.8 50.3    5.0  5.9 50.7 48.4  0.9    6.9   -1.9      4.6           G             1.2
     Kaohsiung 51.2 40.8    0.8  8.0 52.9 45.8  1.3    1.7    5.0     -2.1           G             0.6
       Taoyuan 39.4 47.4    3.2 13.2 44.3 55.7  0.0    4.9    8.3     -1.1           B             0.9
  Hsinchu City 38.0 47.0   12.9 15.1 39.7 57.4  2.9    1.7   10.5     -3.8           B             1.1
        Tainan 49.4 30.8    2.5 19.7 52.5 44.7  2.8    3.1   13.9     -7.6           G             0.6
       Keelung 35.2 44.9    5.6 19.9 47.6 51.3  1.1   12.4    6.3      4.2           B             0.8
      Changhua 33.5 46.5    5.1 20.0 46.2 40.8 13.0   12.8   -5.7     11.3           G            -0.1
         Yilan 43.5 35.4    1.5 21.1 53.7 44.3  1.9   10.2    9.0     -0.4           G             1.2
Hsinchu County 23.3 53.4    9.8 23.3 57.4 40.4  2.3   34.0  -13.0     28.3           G             1.5
 Chiayi County 54.1 18.8    0.6 27.1 55.9 44.1  0.0    1.7   25.3    -18.3           G            -0.1
   Chiayi City 35.5 35.3    2.3 29.3 53.3 42.3  4.5   17.8    7.0      5.6           G             0.2
       Taitung 10.0 60.0    0.0 30.0 36.4 61.4  2.3   26.4    1.4     22.9           B             1.3
       Hualien 19.0 48.2    2.4 32.8 37.5 37.7 24.9   18.5  -10.6     21.6           B             1.9
      Pingtung 33.0 30.3    0.7 36.7 61.5 38.5  0.0   28.5    8.2      9.3           G            -0.0
        Nantou 21.6 34.7    0.9 43.7 37.5 62.5  0.0   15.9   27.8     -0.8           B             0.6
        Miaoli 23.0 32.3    3.8 44.7 37.8 62.2  0.0   14.8   29.9     -3.8           B             0.7
        Yunlin 30.9 22.4    4.3 46.7 49.2 49.2  1.6   18.3   26.7     -7.9           G             0.3
    Lienchiang  0.0 53.1    0.0 46.9  0.0 58.3 41.7    NaN    5.2      NaN           B            -1.1
        Penghu 14.6 31.4    2.2 54.0 31.3 42.2 26.4   16.7   10.8     10.8           B             0.6
        Kinmen  4.6 27.1    6.4 68.3  0.0 63.5 36.5    NaN   36.4      NaN           B            -0.9

Two-standard-bearer races: 20; green gap mean +12.5 (range +0.8 to +34.0); blue gap mean +7.9 (range -13.0 to +29.9)
Two-camp gap: mean +3.8, median +1.1, range -18.3 to +28.3; positive (green ran ahead) in 11 of 20; |gap| < 2 in 5
Correlation of unaligned council share with (green gap + blue gap): 0.86; identity: gap_G + gap_B = c_U - m_U
Correlation of unaligned council share with two-camp gap: 0.10

## B. Loyalty (bounded ecological regression within general council districts, station-weighted)
  -> green standard-bearer: Yilan G 0.81 B 0.24 U 0.50; Hsinchu County G 0.73 B 0.48 U 0.50; Miaoli G 0.63 B 0.21 U 0.33; Changhua G 0.76 B 0.31 U 0.32; Nantou G 0.67 B 0.13 U 0.36; Yunlin G 0.62 B 0.34 U 0.49; Chiayi County G 0.68 B 0.27 U 0.48; Pingtung G 0.83 B 0.47 U 0.59; Taitung G 0.79 B 0.28 U 0.41; Hualien G 0.63 B 0.20 U 0.47; Penghu G 0.65 B 0.13 U 0.31; Keelung G 0.81 B 0.26 U 0.35; Hsinchu City G 0.75 B 0.10 U 0.39; Chiayi City G 0.89 B 0.09 U 0.62; Taipei G 0.93 B 0.07 U 0.52; Kaohsiung G 0.86 B 0.13 U 0.38; New Taipei G 0.88 B 0.13 U 0.42; Taichung G 0.87 B 0.20 U 0.39; Tainan G 0.75 B 0.18 U 0.51; Taoyuan G 0.85 B 0.13 U 0.37
  -> blue standard-bearer: Kinmen G 0.84 B 0.64 U 0.63; Yilan G 0.17 B 0.75 U 0.47; Hsinchu County G 0.27 B 0.50 U 0.48; Miaoli G 0.37 B 0.79 U 0.67; Changhua G 0.16 B 0.53 U 0.49; Nantou G 0.33 B 0.87 U 0.64; Yunlin G 0.36 B 0.64 U 0.50; Chiayi County G 0.32 B 0.73 U 0.52; Pingtung G 0.17 B 0.53 U 0.41; Taitung G 0.19 B 0.69 U 0.57; Hualien G 0.02 B 0.53 U 0.38; Penghu G 0.00 B 0.61 U 0.48; Keelung G 0.18 B 0.73 U 0.63; Hsinchu City G 0.23 B 0.85 U 0.59; Chiayi City G 0.06 B 0.87 U 0.35; Taipei G 0.07 B 0.92 U 0.35; Kaohsiung G 0.12 B 0.86 U 0.61; New Taipei G 0.11 B 0.87 U 0.55; Taichung G 0.12 B 0.79 U 0.58; Tainan G 0.22 B 0.79 U 0.43; Taoyuan G 0.15 B 0.87 U 0.63

## C. District gaps (general districts)
  G: 154 districts, mean +12.4, sd 15.2, within 3 points: 19%
  B: 161 districts, mean +7.5, sd 18.2, within 3 points: 24%

## D. Taipei by party label: pan-green 44.9, pan-blue 54.4, unaligned 0.7; Shen 45.7 (gap +0.8), Chiang 53.7 (gap -0.7)
   (published Taipei page, independents researched: pan-green 45.1, pan-blue 54.3; gaps +0.6, -0.6)

expected output: OUT/allcounty_researched/extras.md

# Extras: Taiwan 2026 mayor vs council (researched camps)

## Change in two-camp shift since 2022 (2022 TPP counted with pan-blue; comparable = third candidates under 10% in 2022)
 code         county  shift26  shift22_tpp_in  shift22_tpp_out  change  others22  comparable
10005         Miaoli     -3.8            24.6             18.5   -28.5      57.8       False
10018   Hsinchu City     -3.8            21.0             12.6   -24.9      46.2       False
10010  Chiayi County    -18.3            -6.8             -6.8   -11.5       0.0        True
10016         Penghu     10.8            18.8             16.5    -8.0      30.0       False
64000      Kaohsiung     -2.1             5.3              4.2    -7.4       1.7        True
10008         Nantou     -0.8             5.7              4.6    -6.5       1.2        True
63000         Taipei      0.8             2.3             -2.5    -1.5      25.8       False
10017        Keelung      4.2             5.0              3.7    -0.8       8.1        True
10014        Taitung     22.9            21.1             21.0     1.8       2.1        True
68000        Taoyuan     -1.1            -3.0             -4.8     2.0       8.0        True
67000         Tainan     -7.6            -9.8            -11.8     2.2       7.6        True
10009         Yunlin     -7.9           -14.5            -19.5     6.6       1.8        True
10002          Yilan     -0.4            -8.0             -8.9     7.6       8.1        True
65000     New Taipei      1.5            -6.8             -9.1     8.3       0.0        True
10015        Hualien     21.6            13.0             12.2     8.7       3.2        True
66000       Taichung      4.6            -4.9             -7.6     9.6       1.7        True
10013       Pingtung      9.3            -1.1             -1.6    10.4       4.3        True
10007       Changhua     11.3            -0.4             -2.7    11.7       1.3        True
10004 Hsinchu County     28.3             8.6              6.7    19.6       4.2        True
10020    Chiayi City      5.6           -15.9            -16.6    21.6       1.2        True

## TPP council voters -> mayoral candidates (bounded regression within general districts)
 code         county  tpp_council  to_B  lo_B  hi_B  districts  to_G  lo_G  hi_G  reliable
10018   Hsinchu City        12.92  1.00  0.92  1.00          5  0.00  0.00  0.06      True
10004 Hsinchu County         9.76  0.14  0.07  0.19         11  0.83  0.79  0.90      True
63000         Taipei         9.16  0.92  0.87  0.96          6  0.06  0.03  0.12      True
65000     New Taipei         8.05  0.93  0.88  0.97         11  0.07  0.03  0.12      True
09020         Kinmen         6.36  0.05  0.00  0.48          2   NaN   NaN   NaN      True
10017        Keelung         5.59  0.74  0.65  0.89          7  0.26  0.11  0.35      True
10007       Changhua         5.13  0.63  0.52  0.68          8  0.10  0.05  0.18      True
66000       Taichung         5.03  0.68  0.62  0.74         14  0.31  0.25  0.37      True
10009         Yunlin         4.33  0.91  0.82  0.96          6  0.08  0.04  0.17      True
10005         Miaoli         3.75  0.34  0.19  0.48          6  0.66  0.52  0.81      True
68000        Taoyuan         3.20  0.96  0.89  0.99         12  0.04  0.01  0.11      True
67000         Tainan         2.54  0.97  0.91  1.00         11  0.00  0.00  0.06     False
10015        Hualien         2.41  0.29  0.00  0.50          4  0.31  0.00  0.51     False
10020    Chiayi City         2.29  1.00  0.90  1.00          2  0.00  0.00  0.04     False
10016         Penghu         2.23  1.00  0.33  1.00          4  0.00  0.00  0.34     False
10002          Yilan         1.45  0.72  0.48  1.00         10  0.24  0.00  0.46     False

## Third candidates: share of each council group backing them, and the implied make-up of their vote
 code   county name  mayoral_share  districts  rate_G  rate_B  rate_U  halfwidth_max  from_G  from_B  from_U
10015  Hualien  魏嘉賢          24.51          4    0.34    0.27    0.15           0.06   26.64   52.57   20.51
10015  Hualien   張峻          37.45          4    0.63    0.20    0.47           0.07   31.78   26.11   40.74
10015  Hualien  游淑貞          37.66          4    0.02    0.53    0.38           0.06    1.15   67.62   32.78
10007 Changhua  邱建富          11.62          8    0.07    0.14    0.18           0.02   19.27   56.71   30.15
10007 Changhua  陳素月          46.24          8    0.76    0.31    0.32           0.05   54.98   31.21   13.68
10007 Changhua  魏平政          40.79          8    0.16    0.53    0.49           0.06   13.39   60.96   24.26
10016   Penghu  葉竹林          19.95          4    0.29    0.17    0.16           0.14   21.30   26.24   43.22
10016   Penghu  吳淑瑾          31.34          4    0.65    0.13    0.31           0.10   30.43   12.80   52.78
10016   Penghu  陳振中          42.24          4    0.00    0.62    0.48           0.10    0.00   45.75   60.97

## Sensitivity checks
  hualien_wei_blue: +9.4
  Hsinchu County_tpp_out: +23.8
  Miaoli_tpp_out: -6.8
  penghu_label: -10.4
  penghu_researched: +10.8

## Special municipalities
           county  shift26    m_G    c_G  G_to_G  B_to_G  U_to_G  B_to_B  shift22_tpp_in  change  comparable
code                                                                                                        
63000      Taipei     0.77  45.69  44.86    0.93    0.07    0.52    0.92            2.30   -1.54       False
64000   Kaohsiung    -2.06  52.90  51.18    0.86    0.13    0.38    0.86            5.34   -7.40        True
65000  New Taipei     1.50  48.25  44.99    0.88    0.13    0.42    0.87           -6.80    8.30        True
66000    Taichung     4.64  50.68  43.78    0.87    0.20    0.39    0.79           -4.93    9.57        True
67000      Tainan    -7.59  52.49  49.43    0.75    0.18    0.51    0.79           -9.79    2.19        True
68000     Taoyuan    -1.07  44.32  39.42    0.85    0.13    0.37    0.87           -3.04    1.97        True

## Templeman final ratings vs results
        county     rating winner winner_party  margin  votes_margin
        Yunlin  Leans KMT    劉建國        民主進步黨     0.0           173
       Hualien  Leans KMT    游淑貞        中國國民黨     0.2           357
      Taichung  Leans KMT    何欣純        民主進步黨     2.3         35079
    New Taipei    Toss-up    李四川        中國國民黨     3.0         64925
       Keelung    Toss-up    謝國樑        中國國民黨     3.7          7125
      Changhua Likely DPP    陳素月        民主進步黨     5.4         35443
     Kaohsiung Likely DPP    賴瑞隆        民主進步黨     7.1        104154
        Tainan   Safe DPP    陳亭妃        民主進步黨     7.8         77321
        Taipei  Leans KMT    蔣萬安        中國國民黨     8.0        116726
         Yilan  Leans DPP    林國漳        民主進步黨     9.4         23093
        Penghu    Toss-up    陳振中        中國國民黨    10.9          5634
   Chiayi City Likely DPP    王美惠        民主進步黨    11.0         14451
       Taoyuan Likely KMT    張善政        中國國民黨    11.4        132045
 Chiayi County   Safe DPP    蔡易餘        民主進步黨    11.7         31297
    Lienchiang   Safe KMT    王忠銘        中國國民黨    16.7          1283
Hsinchu County    Toss-up    鄭朝方        民主進步黨    17.0         51599
  Hsinchu City  Leans IND    高虹安            無    17.7         39898
      Pingtung  Leans DPP    周春米        民主進步黨    22.9        101066
        Miaoli   Safe KMT    鍾東錦        中國國民黨    24.4         69456
       Taitung  Leans KMT    吳秀華        中國國民黨    25.0         28013
        Nantou   Safe KMT    許淑華        中國國民黨    25.0         67947
        Kinmen   Safe KMT    陳玉珍        中國國民黨    34.2         15497

## Council camp swing toward pan-green, 2022 -> 2026 (party labels; two-camp share)
               county  cg22  cg26  swing
code                                    
10016          Penghu  33.6  53.0   19.4
10017         Keelung  37.4  43.7    6.3
63000          Taipei  40.7  46.2    5.5
10004  Hsinchu County  25.2  30.4    5.2
10010   Chiayi County  69.7  74.2    4.5
66000        Taichung  44.5  48.8    4.3
10015         Hualien  20.1  24.1    3.9
09020          Kinmen  10.9  14.4    3.5
65000      New Taipei  44.4  47.6    3.2
10009          Yunlin  56.8  59.9    3.1
10008          Nantou  37.7  40.3    2.6
10002           Yilan  52.7  54.2    1.5
64000       Kaohsiung  53.8  54.6    0.8
10018    Hsinchu City  45.4  45.8    0.4
10020     Chiayi City  51.3  51.5    0.2
68000         Taoyuan  46.5  46.6    0.0
67000          Tainan  62.6  62.1   -0.5
10007        Changhua  42.9  41.7   -1.1
10013        Pingtung  52.4  51.1   -1.3
10014         Taitung  16.3  14.3   -2.0
09007      Lienchiang   2.7   0.0   -2.7
10005          Miaoli  49.4  42.9   -6.5
  median 2.0; positive in 16 of 22

## Races by 2022 and 2026 winner
 code         county   winner22  margin22  dpp_minus_kmt22 winner26  margin26 camp26  dpp22  dpp26
09007     Lienchiang      中國國民黨      86.2            -86.2    中國國民黨      16.7      B  False  False
09020         Kinmen 無黨籍及未經政黨推薦      17.5            -41.0    中國國民黨      34.2      B  False  False
10002          Yilan      中國國民黨       9.6             -9.6    民主進步黨       9.4      G  False   True
10004 Hsinchu County      中國國民黨      31.0            -31.0    民主進步黨      17.0      G  False   True
10005         Miaoli 無黨籍及未經政黨推薦      13.1             20.3    中國國民黨      24.4      B  False  False
10007       Changhua      中國國民黨      14.8            -14.8    民主進步黨       5.4      G  False   True
10008         Nantou      中國國民黨      13.2            -13.2    中國國民黨      25.0      B  False  False
10009         Yunlin      中國國民黨      15.0            -15.0    民主進步黨       0.0      G  False   True
10010  Chiayi County      民主進步黨      25.7             25.7    民主進步黨      11.7      G   True   True
10013       Pingtung      民主進步黨       2.5              2.5    民主進步黨      22.9      G   True   True
10014        Taitung      中國國民黨      24.6            -24.6    中國國民黨      25.0      B  False  False
10015        Hualien      中國國民黨      32.7            -32.7    中國國民黨       0.2      B  False  False
10016         Penghu      民主進步黨       3.3              3.3    中國國民黨      10.9      B   True  False
10017        Keelung      中國國民黨      13.9            -13.9    中國國民黨       3.7      B  False  False
10018   Hsinchu City      台灣民眾黨       9.3             17.6        無      17.7      B  False  False
10020    Chiayi City      中國國民黨      28.9            -28.9    民主進步黨      11.0      G  False   True
63000         Taipei      中國國民黨      10.4            -10.4    中國國民黨       8.0      B  False  False
64000      Kaohsiung      民主進步黨      17.9             17.9    民主進步黨       7.1      G   True   True
65000     New Taipei      中國國民黨      24.8            -24.8    中國國民黨       3.0      B  False  False
66000       Taichung      中國國民黨      20.4            -20.4    民主進步黨       2.3      G  False   True
67000         Tainan      民主進步黨       5.2              5.2    民主進步黨       7.8      G   True   True
68000        Taoyuan      中國國民黨      12.0            -12.0    中國國民黨      11.4      B  False  False

## Council vote by group (municipalities and contrast counties)
 code     county  DPP  G_other    U  B_other  TPP  KMT  m_G  m_U  m_B  c_G  c_B
63000     Taipei 38.5      6.3  0.8      4.7  9.2 40.5 45.7  0.6 53.7 44.9 54.4
65000 New Taipei 44.4      0.6  4.3      1.4  8.1 41.3 48.2  0.5 51.2 45.0 50.7
66000   Taichung 42.4      1.4  5.9      5.3  5.0 40.0 50.7  0.9 48.4 43.8 50.3
67000     Tainan 46.3      3.1 19.7      1.5  2.5 26.8 52.5  2.8 44.7 49.4 30.8
64000  Kaohsiung 48.8      2.4  8.0      0.0  0.8 40.0 52.9  1.3 45.8 51.2 40.8
68000    Taoyuan 37.0      2.4 13.2      4.8  3.2 39.4 44.3  0.0 55.7 39.4 47.4
10009     Yunlin 28.3      2.5 46.7      2.7  4.3 15.4 49.2  1.6 49.2 30.9 22.4
10015    Hualien 14.7      4.2 32.8      0.0  2.4 45.8 37.5 24.9 37.7 19.0 48.2

## Loyalty: mean of pan-green->green and pan-blue->blue; crossover: mean of the two crossovers
 code         county  muni   c_U   GG   BB   BG   GB  loyal  cross
63000         Taipei  True  0.74 0.93 0.92 0.07 0.07   0.93   0.07
10020    Chiayi City False 29.29 0.89 0.87 0.09 0.06   0.88   0.08
65000     New Taipei  True  4.30 0.88 0.87 0.13 0.11   0.87   0.12
64000      Kaohsiung  True  8.04 0.86 0.86 0.13 0.12   0.86   0.12
68000        Taoyuan  True 13.17 0.85 0.87 0.13 0.15   0.86   0.14
66000       Taichung  True  5.90 0.87 0.79 0.20 0.12   0.83   0.16
10018   Hsinchu City False 15.07 0.75 0.85 0.10 0.23   0.80   0.17
10002          Yilan False 21.11 0.81 0.75 0.24 0.17   0.78   0.21
10008         Nantou False 43.71 0.67 0.87 0.13 0.33   0.77   0.23
10017        Keelung False 19.85 0.81 0.73 0.26 0.18   0.77   0.22
67000         Tainan  True 19.75 0.75 0.79 0.18 0.22   0.77   0.20
10014        Taitung False 30.00 0.79 0.69 0.28 0.19   0.74   0.23
10005         Miaoli False 44.72 0.63 0.79 0.21 0.37   0.71   0.29
10010  Chiayi County False 27.06 0.68 0.73 0.27 0.32   0.71   0.29
10013       Pingtung False 36.70 0.83 0.53 0.47 0.17   0.68   0.32
10007       Changhua False 20.00 0.76 0.53 0.31 0.16   0.65   0.24
10009         Yunlin False 46.68 0.62 0.64 0.34 0.36   0.63   0.35
10016         Penghu False 54.00 0.65 0.61 0.13 0.00   0.63   0.06
10004 Hsinchu County False 23.29 0.73 0.50 0.48 0.27   0.61   0.37
10015        Hualien False 32.80 0.63 0.53 0.20 0.02   0.58   0.11
  means: municipalities loyalty 0.855, crossover 0.136, unaligned 8.7; others 0.709, 0.227, 31.7; corr(unaligned, loyalty) -0.69

## Special municipalities vs other head-to-head races (simple means across races)
             c_G     c_U     c_B     m_G    m_U     m_B     GG     GB  G_other     BB     BG  B_other  loyal  cross   n                                                                                                              members
grp                                                                                                                                                                                                                                         
cities    45.611   8.650  45.739  49.055  1.029  49.916  0.858  0.132    0.010  0.851  0.139    0.009  0.855  0.136   6                                                             Taipei, Kaohsiung, New Taipei, Taichung, Tainan, Taoyuan
counties  31.641  30.679  37.679  48.172  1.504  50.324  0.745  0.242    0.013  0.722  0.261    0.016  0.734  0.252  11  Yilan, Hsinchu County, Miaoli, Nantou, Yunlin, Chiayi County, Pingtung, Taitung, Keelung, Hsinchu City, Chiayi City

expected output: OUT/allcounty/results.md

# Results: Taiwan 2026, mayoral vs council votes (all 22 counties)

Stations matched across ballots: 18,248 in 22 counties; general council districts: 161
Valid votes: mayor 12,556,956, council (all districts) 12,450,093; difference by county -1.1% to +1.9% of council
Nationwide council: pan-green 40.2, pan-blue 42.0 (TPP 4.9), unaligned 17.7
Nationwide mayoral: green standard-bearers 48.5, blue standard-bearers 49.3, others 2.2

## A. County table (percent of valid votes on each ballot; gaps in points)
        county  c_G  c_B  c_TPP  c_U  m_G  m_B  m_U  gap_G  gap_B  two_gap winner_camp  valid_diff_pct
        Taipei 44.0 51.3    9.2  4.8 45.7 53.7  0.6    1.7    2.5     -0.2           B             1.2
    New Taipei 45.0 49.6    8.1  5.4 48.2 51.2  0.5    3.3    1.6      0.9           B             1.1
     Kaohsiung 49.0 40.8    0.8 10.2 52.9 45.8  1.3    3.9    5.0     -1.0           G             0.6
      Taichung 43.2 45.3    5.0 11.5 50.7 48.4  0.9    7.5    3.1      2.4           G             1.2
       Taoyuan 37.4 42.9    3.2 19.7 44.3 55.7  0.0    6.9   12.8     -2.3           B             0.9
  Hsinchu City 36.2 42.9   12.9 20.9 39.7 57.4  2.9    3.5   14.5     -4.9           B             1.1
      Changhua 32.8 45.7    5.1 21.5 46.2 40.8 13.0   13.5   -5.0     11.4           G            -0.1
       Keelung 34.2 44.0    5.6 21.8 47.6 51.3  1.1   13.4    7.3      4.4           B             0.8
        Tainan 48.1 29.3    2.5 22.6 52.5 44.7  2.8    4.4   15.4     -8.1           G             0.6
Hsinchu County 23.3 53.4    9.8 23.3 57.4 40.4  2.3   34.0  -13.0     28.3           G             1.5
         Yilan 40.1 33.8    1.5 26.2 53.7 44.3  1.9   13.7   10.5      0.6           G             1.2
 Chiayi County 54.1 18.8    0.6 27.1 55.9 44.1  0.0    1.7   25.3    -18.3           G            -0.1
       Taitung 10.0 60.0    0.0 30.0 36.4 61.4  2.3   26.4    1.4     22.9           B             1.3
   Chiayi City 34.1 32.1    2.3 33.7 53.3 42.3  4.5   19.2   10.1      4.3           G             0.2
       Hualien 15.3 48.2    2.4 36.5 37.5 37.7 24.9   22.2  -10.6     25.8           B             1.9
      Pingtung 31.7 30.3    0.7 38.0 61.5 38.5  0.0   29.8    8.2     10.3           G            -0.0
        Miaoli 23.0 30.7    3.8 46.4 37.8 62.2  0.0   14.8   31.6     -5.1           B             0.7
        Nantou 21.6 32.0    0.9 46.4 37.5 62.5  0.0   15.9   30.5     -2.8           B             0.6
    Lienchiang  0.0 53.1    0.0 46.9  0.0 58.3 41.7    NaN    5.2      NaN           B            -1.1
        Yunlin 29.6 19.8    4.3 50.7 49.2 49.2  1.6   19.7   29.4     -9.9           G             0.3
        Kinmen  4.6 27.1    6.4 68.3  0.0 63.5 36.5    NaN   36.4      NaN           B            -0.9
        Penghu 14.6 13.0    2.2 72.4 31.3 42.2 26.4   16.7   29.3    -10.4           B             0.6

Two-standard-bearer races: 20; green gap mean +13.6 (range +1.7 to +34.0); blue gap mean +10.5 (range -13.0 to +31.6)
Two-camp gap: mean +2.4, median +0.2, range -18.3 to +28.3; positive (green ran ahead) in 10 of 20; |gap| < 2 in 4
Correlation of unaligned council share with (green gap + blue gap): 0.88; identity: gap_G + gap_B = c_U - m_U
Correlation of unaligned council share with two-camp gap: -0.16

## B. Loyalty (bounded ecological regression within general council districts, station-weighted)
  -> green standard-bearer: Yilan G 0.83 B 0.24 U 0.52; Hsinchu County G 0.73 B 0.48 U 0.50; Miaoli G 0.63 B 0.22 U 0.33; Changhua G 0.77 B 0.31 U 0.32; Nantou G 0.68 B 0.13 U 0.37; Yunlin G 0.64 B 0.34 U 0.47; Chiayi County G 0.68 B 0.27 U 0.48; Pingtung G 0.84 B 0.47 U 0.60; Taitung G 0.79 B 0.28 U 0.41; Hualien G 0.68 B 0.20 U 0.46; Penghu G 0.61 B 0.00 U 0.29; Keelung G 0.80 B 0.27 U 0.38; Hsinchu City G 0.77 B 0.07 U 0.39; Chiayi City G 0.91 B 0.09 U 0.57; Taipei G 0.94 B 0.06 U 0.39; Kaohsiung G 0.88 B 0.12 U 0.34; New Taipei G 0.89 B 0.10 U 0.43; Taichung G 0.87 B 0.19 U 0.40; Tainan G 0.75 B 0.19 U 0.54; Taoyuan G 0.87 B 0.09 U 0.40
  -> blue standard-bearer: Kinmen G 0.84 B 0.64 U 0.63; Yilan G 0.16 B 0.75 U 0.44; Hsinchu County G 0.27 B 0.50 U 0.48; Miaoli G 0.37 B 0.78 U 0.67; Changhua G 0.15 B 0.54 U 0.49; Nantou G 0.32 B 0.87 U 0.63; Yunlin G 0.35 B 0.65 U 0.51; Chiayi County G 0.32 B 0.73 U 0.52; Pingtung G 0.16 B 0.53 U 0.40; Taitung G 0.19 B 0.69 U 0.57; Hualien G 0.00 B 0.51 U 0.37; Penghu G 0.03 B 0.91 U 0.43; Keelung G 0.19 B 0.72 U 0.60; Hsinchu City G 0.21 B 0.89 U 0.59; Chiayi City G 0.05 B 0.87 U 0.39; Taipei G 0.06 B 0.94 U 0.58; Kaohsiung G 0.10 B 0.87 U 0.65; New Taipei G 0.10 B 0.89 U 0.55; Taichung G 0.12 B 0.80 U 0.58; Tainan G 0.23 B 0.79 U 0.42; Taoyuan G 0.13 B 0.91 U 0.60

## C. District gaps (general districts)
  G: 154 districts, mean +13.4, sd 15.0, within 3 points: 18%
  B: 161 districts, mean +10.3, sd 18.3, within 3 points: 20%

## D. Taipei by party label: pan-green 44.0, pan-blue 51.3, unaligned 4.8; Shen 45.7 (gap +1.7), Chiang 53.7 (gap +2.5)
   (published Taipei page, independents researched: pan-green 45.1, pan-blue 54.3; gaps +0.6, -0.6)

checks_mayor_council.py

robustness checks quoted in the appendices
"""Robustness checks on the mayor/council comparison (Taipei and Taiwan pages). Not part of any published page.

usage: python3 checks_mayor_council.py CLEAN_DIR TAIPEI_OUT ALLCOUNTY_RESEARCHED_OUT OUT_DIR
  CLEAN_DIR          _data/clean (cec2026 votes, candidates, turnout)
  TAIPEI_OUT         _data/output/taipei (stations_2026.csv, villages_22_26.csv from taipei_ballots.py)
  ALLCOUNTY_..._OUT  _data/output/allcounty_researched (loyalty.csv, counties.csv: the published figures)
Writes OUT_DIR/checks.md (every number reported) and the station/village tables the EI script reads
(ei_taipei_stations.csv, ei_taipei_villages.csv, ei_allcounty_stations.csv).

Checks
  1  weights: district estimates (bounded regression, ecoreg.py) aggregated by stations (published), registered electors, mayoral valid votes
  3  camp sensitivity: ambiguous independents as published / unaligned / a separate group dropped from the camps
  4  Taipei 2022->2026 village swing with party-label camps in both years
  5  village coattails with turnout change and district fixed effects
  6  effective number of council candidates as a control for the unaligned-share / loyalty correlation
Check 2 (bounded EI) is checks_mayor_council_ei.py, run in .venv-ei on the tables written here.
All estimates describe polling stations (or villages) in aggregate, not individual voters.
"""
import sys, os
import numpy as np
import pandas as pd

CLEAN, TPE_OUT, AC, OUT = sys.argv[1:5]
os.makedirs(OUT, exist_ok=True)
HERE = os.path.dirname(os.path.abspath(__file__))
JS = {}                                  # figures the page appendices quote (checks.json)
LOG = []
def say(s=''):
    print(s); LOG.append(s)

# ------------------------------------------------------------------ shared helpers (bounded regression, code/ecoreg.py)
sys.path.insert(0, HERE); import ecoreg
WEIGHTS = ('stations', 'electors', 'valid')
WCOL = {'stations': None, 'electors': 'electors', 'valid': 'm_valid'}
def within(z, groups, cols, min_n=0, weights=WEIGHTS):
    """Bounded regression within each council district; {weighting: {(group, outcome): estimate}} (no intervals)."""
    out = {}
    for k in weights:
        r = ecoreg.within(z, list(groups), list(cols), 'c_valid', 'm_valid', min_n=min_n, weight=WCOL[k], n_boot=0)
        out[k] = {(g, c): float(r['est'][i, j]) for i, g in enumerate(r['rows']) for j, c in enumerate(r['cols']) if r['districts']}
    return out

pct = lambda a, b: 100 * a / b
rule = lambda: say()

# ================================================================== Taipei stations (published) + candidate votes
V = pd.read_parquet(f'{CLEAN}/votes/source=cec2026'); C = pd.read_parquet(f'{CLEAN}/candidates/source=cec2026')
E = pd.read_parquet(f'{CLEAN}/elections/source=cec2026'); E['code'] = E.county.str[:5]
s26 = pd.read_csv(f'{TPE_OUT}/stations_2026.csv')
GREEN_IND = ['陳怡君', '朱政騏', '紀建漢']; BLUE_IND = ['陳怡潔', '陳重文', '應佳妤', '徐立信']; HSU = '徐立信'
tco = E[(E.code == '63000') & (E.office == 'council')].eid.iloc[0]
tv = V[V.eid == tco].merge(C[C.eid == tco][['race_id', 'no', 'name_zh']], on=['race_id', 'no'])
tv = tv[tv.name_zh.isin(GREEN_IND + BLUE_IND)].pivot_table(index='station', columns='name_zh', values='votes', aggfunc='sum')
s26 = s26.merge(tv.add_prefix('x_').reset_index(), on='station', how='left').fillna(0)
s26['c_G'] = s26.c_G_core + s26.c_G_other; s26['c_B'] = s26.c_B_core + s26.c_B_other
s26['c_GI'] = s26[['x_' + n for n in GREEN_IND]].sum(1); s26['c_BI'] = s26[['x_' + n for n in BLUE_IND]].sum(1)
assert abs(s26.c_HSU - s26['x_' + HSU]).max() == 0
s26['c_REST2'] = s26.c_valid - s26.c_DPP - s26.c_SDP - s26.c_KMT - s26.c_TPP
s26['m_OTH'] = s26.m_valid - s26.m_DPP - s26.m_KMT

say('# Robustness checks: mayoral vs council votes (Taipei and Taiwan pages)')
say('Estimates describe polling stations (villages for the 2022->2026 panel) in aggregate, not individual voters.')

# ================================================================== CHECK 1: weights
say('\n## Check 1. District weights: stations (published) vs registered electors vs mayoral valid votes')
say('\n### Taipei (six general districts; taipei_ballots.py specification)')
TC = ['m_DPP', 'm_KMT', 'm_OTH']
GR = ['c_DPP', 'c_KMT', 'c_TPP', 'c_REST2', 'c_SDP']
r1 = within(s26, ['c_G', 'c_B', 'c_U'], TC); r2 = within(s26, GR, TC)
tb = [('pan-green -> Shen', 0.930, r1, ('c_G', 'm_DPP')), ('pan-blue -> Chiang', 0.927, r1, ('c_B', 'm_KMT')),
      ('TPP -> Chiang', 0.91, r2, ('c_TPP', 'm_KMT')), ('TPP -> Shen', 0.08, r2, ('c_TPP', 'm_DPP'))]
JS['taipei_weights_maxdiff'] = max(100 * max(abs(r[k][g] - r['stations'][g]) for k in WEIGHTS) for _, _, r, g in tb)
say('| estimate | published (Goodman) | stations | electors | valid votes | max diff (pts) |'); say('|---|---|---|---|---|---|')
for lab, pub, r, g in tb:
    v = [r[k][g] for k in WEIGHTS]
    say(f'| {lab} | {pub:.3f} | {v[0]:.3f} | {v[1]:.3f} | {v[2]:.3f} | {100 * max(abs(x - v[0]) for x in v):.1f} |')

# ---- all-county station panel (rebuilt, so camps can vary; baseline must match the published loyalty.csv)
GREEN = {'民主進步黨', '社會民主黨', '時代力量', '台灣基進', '綠黨', '台灣綠黨', '小民參政歐巴桑聯盟', '台聯黨', '台灣團結聯盟'}
BLUE = {'中國國民黨', '新黨', '親民黨', '台灣民眾黨'}
lab_camp = lambda p: 'G' if p in GREEN else 'B' if p in BLUE else 'U'
ex = E[E.office == 'executive'][['eid', 'code']]; co = E[E.office == 'council'][['eid', 'code']]
ov = pd.read_csv(f'{HERE}/camps_executive.csv', dtype=str)
ov = ov[ov.year == '2026'].assign(code=lambda d: d.county.str[:5]).set_index(['code', 'name']).camp_race
OV = {'pan_green': 'G', 'pan_blue': 'B', 'unaligned': 'U', 'third_force': 'T'}
mc = C.merge(ex, on='eid')
mc['camp'] = [OV[ov[(c, n)]] if (c, n) in ov.index else lab_camp(p) for c, n, p in zip(mc.code, mc.name_zh, mc.party)]
cc = C.merge(co, on='eid'); cc['lab'] = cc.party.map(lab_camp); cc['tpp'] = cc.party == '台灣民眾黨'
R = pd.read_csv(f'{HERE}/camps_council_2026.csv', dtype=str); R = R[R.camp.isin(['pan_green', 'pan_blue'])]
rk = R.county.str[:5] + '-' + R.dist.str.zfill(2) + '|' + R.name
res_camp = dict(zip(rk, R.camp.map({'pan_green': 'G', 'pan_blue': 'B'}))); res_ev = dict(zip(rk, R.evidence_type))
k = cc.race_id + '|' + cc.name
cc['res'] = k.map(res_camp); cc['ev'] = k.map(res_ev)
TPE = {'陳怡君': 'G', '朱政騏': 'G', '紀建漢': 'G', '陳怡潔': 'B', '陳重文': 'B', '應佳妤': 'B', '徐立信': 'B'}
t = (cc.code == '63000') & cc.name_zh.isin(TPE) & (cc.lab == 'U')
cc.loc[t, 'res'] = cc.loc[t, 'name_zh'].map(TPE); cc.loc[t, 'ev'] = 'P'
cc['base'] = cc.res.fillna(cc.lab)
cc['amb'] = cc.res.notna() & cc.ev.isin(['B', 'C', 'U', 'P'])        # ambiguous: not evidence A (Taipei's 7 count as ambiguous)
cc['kind'] = np.where(cc.seat_type.fillna('general') == 'general', 'general', 'indigenous')
say(f'\nAll-county researched camps applied: {int(cc.res.notna().sum())} council candidates; of which ambiguous (evidence B, C, U, '
    f'or Taipei\'s seven independents): {int(cc.amb.sum())}; evidence A: {int((cc.res.notna() & ~cc.amb).sum())}')
cc['v_amb_U'] = np.where(cc.amb, 'U', cc.base); cc['v_amb_X'] = np.where(cc.amb, 'X' + cc.base, cc.base); cc['v_label'] = cc.lab

mv = V.merge(ex, on='eid').merge(mc[['eid', 'no', 'camp']], on=['eid', 'no'])
cv = V.merge(co, on='eid').merge(cc[['eid', 'race_id', 'no', 'tpp', 'kind', 'base', 'v_amb_U', 'v_amb_X', 'v_label']], on=['eid', 'race_id', 'no'])
key = ['code', 'station']
M = mv.pivot_table(index=key, columns='camp', values='votes', aggfunc='sum', fill_value=0).add_prefix('m_')
M['m_valid'] = M.sum(axis=1)
tu = pd.read_parquet(f'{CLEAN}/turnout/source=cec2026').merge(ex, on='eid')
M = M.join(tu.groupby(key)[['electors', 'cast']].sum())
gd = cv[cv.kind == 'general'].groupby(key).race_id.first().rename('dist')
def panel(col):
    K = cv.pivot_table(index=key, columns=col, values='votes', aggfunc='sum', fill_value=0).add_prefix('c_')
    K['c_valid'] = K.sum(axis=1); K['c_TPP'] = cv[cv.tpp].groupby(key).votes.sum().reindex(K.index, fill_value=0)
    S = M.join(K, how='outer').join(gd).fillna(0).reset_index()
    for c in ('m_G', 'm_B', 'm_U', 'c_G', 'c_B', 'c_U', 'c_XG', 'c_XB'):
        if c not in S: S[c] = 0
    S['c_X'] = S.c_XG + S.c_XB; S['m_O'] = S.m_valid - S.m_G - S.m_B
    return S
P = {v: panel(v) for v in ('base', 'v_amb_U', 'v_amb_X', 'v_label')}
S = P['base']
assert S.electors.gt(0).all()
T = pd.read_csv(f'{AC}/counties.csv', dtype={'code': str}).set_index('code')
LP = pd.read_csv(f'{AC}/loyalty.csv', dtype={'code': str})
MUNI = ('63000', '64000', '65000', '66000', '67000', '68000')
TWO = [c for c in T.index if T.loc[c, 'has_G'] and T.loc[c, 'has_B']]

def loyalty(S, groups=('c_G', 'c_B', 'c_U'), weights=WEIGHTS):
    """Per two-camp county: {weighting: dict(GG, BB, BG, GB, UG, UB, XGG.. )} (allcounty_mayor_council.py spec, bounded)."""
    out = {}
    for code in TWO:
        z = S[S.code == code]; r = within(z, groups, ('m_G', 'm_B', 'm_O'), min_n=8, weights=weights)
        out[code] = {k: {f'{g[2:]}{c[2:]}': v for (g, c), v in r[k].items()} for k in weights}
    return out
def summarize(lo, S, k):
    d = pd.DataFrame([dict(code=c, **lo[c][k]) for c in lo]).set_index('code')
    for c in ('GG', 'BB', 'BG', 'GB', 'UG', 'UB'):
        if c not in d: d[c] = np.nan
    cU = {c: pct(S[S.code == c].c_U.sum(), S[S.code == c].c_valid.sum()) for c in d.index}
    d['c_U'] = pd.Series(cU); d['loyal'] = (d.GG + d.BB) / 2; d['muni'] = d.index.isin(MUNI)
    h = d[T.loc[d.index, 'm_U'] < 10]
    return dict(cities=h[h.muni].loyal.mean(), counties=h[~h.muni].loyal.mean(), n_c=int(h.muni.sum()), n_o=int((~h.muni).sum()),
                r=np.corrcoef(d.c_U, d.loyal)[0, 1], table=d)

LO = loyalty(S)
chk = LP.set_index(['code', 'target'])
dev = max(max(abs(LO[c]['stations']['GG'] - chk.loc[(c, 'G'), 'c_G']), abs(LO[c]['stations']['BB'] - chk.loc[(c, 'B'), 'c_B'])) for c in TWO)
say(f'Rebuilt all-county panel: {len(S):,} stations; largest difference from published loyalty.csv (station weights): {dev:.2e}')
say('\n### Taiwan page (bounded regression within general council districts, researched camps; "published" = Goodman figures on the page)')
say('| estimate | published | stations | electors | valid votes | max diff (pts) |'); say('|---|---|---|---|---|---|')
sm = {k: summarize(LO, S, k) for k in WEIGHTS}
for lab, pub, f in (('Cities loyalty (6 head-to-head)', 0.862, lambda s: s['cities']),
                    ('Other head-to-head loyalty (11)', 0.750, lambda s: s['counties']),
                    ('Chiayi City unaligned -> DPP', 0.616, lambda s: s['table'].loc['10020', 'UG']),
                    ('Chiayi City unaligned -> KMT', 0.350, lambda s: s['table'].loc['10020', 'UB']),
                    ('Taipei loyalty (Taiwan-page spec)', 0.93, lambda s: s['table'].loc['63000', 'loyal']),
                    ('corr(unaligned share, loyalty), 20 races', -0.65, lambda s: s['r'])):
    v = [f(sm[k]) for k in WEIGHTS]
    say(f'| {lab} | {pub:.3f} | {v[0]:.3f} | {v[1]:.3f} | {v[2]:.3f} | {100 * max(abs(x - v[0]) for x in v):.1f} |')
JS['taiwan_weights'] = {k: dict(cities=sm[k]['cities'], counties=sm[k]['counties'], r=sm[k]['r']) for k in WEIGHTS}
d0, d1 = sm['stations']['table'], sm['electors']['table']
dd = (d1.loyal - d0.loyal).abs().sort_values(ascending=False)
say(f'Per-race loyalty, electors vs stations: largest moves ' + ', '.join(f"{T.loc[c, 'county']} {100 * (d1.loyal[c] - d0.loyal[c]):+.1f}" for c in dd.index[:4]) +
    f'; races moving 1 point or more: {(dd >= 0.01).sum()} of {len(dd)}')

# ================================================================== CHECK 3: camp sensitivity
say('\n## Check 3. Camp sensitivity')
say('Variants: (a) published classification; (b) ambiguous independents counted unaligned; (c) ambiguous independents a group of')
say('their own, left out of the camp shares (denominator = council valid votes minus their votes) and entered as a separate')
say('regressor in the bounded models (green-leaning and blue-leaning ambiguous candidates as two separate groups). Taipei ambiguous = GREEN_IND (陳怡君, 朱政騏, 紀建漢) and BLUE_IND (陳怡潔, 陳重文, 應佳妤, 徐立信).')
s = s26.copy()
s['c_G_lab'] = s.c_G - s.c_GI; s['c_B_lab'] = s.c_B - s.c_BI; s['c_U_lab'] = s.c_U + s.c_GI + s.c_BI; s['c_X'] = s.c_GI + s.c_BI
s['c_B_nohsu'] = s.c_B - s.c_HSU; s['c_U_hsu'] = s.c_U + s.c_HSU
VAR = {'(a) published': ('c_G', 'c_B', 'c_U', None), '(b) ambiguous -> unaligned': ('c_G_lab', 'c_B_lab', 'c_U_lab', None),
       '(c) ambiguous dropped': ('c_G_lab', 'c_B_lab', 'c_U', ['c_GI', 'c_BI']), '(b\') Hsu only -> unaligned': ('c_G', 'c_B_nohsu', 'c_U_hsu', None),
       '(c\') Hsu only dropped': ('c_G', 'c_B_nohsu', 'c_U', ['c_HSU'])}
say('\n### Taipei')
say('| variant | pan-green % | pan-blue % | Shen gap | Chiang gap | D5 Shen gap | D5 Chiang gap | green->Shen | blue->Chiang | ambiguous->Shen (green-leaning / blue-leaning) | ambiguous->Chiang (same) |')
say('|---|---|---|---|---|---|---|---|---|---|---|')
shen, chiang = pct(s.m_DPP.sum(), s.m_valid.sum()), pct(s.m_KMT.sum(), s.m_valid.sum())
z5 = s[s.dist == 5]; shen5, chiang5 = pct(z5.m_DPP.sum(), z5.m_valid.sum()), pct(z5.m_KMT.sum(), z5.m_valid.sum())
for lab, (g, b, u, x) in VAR.items():
    x = x or []; den = s.c_valid.sum() - s[x].sum().sum(); den5 = z5.c_valid.sum() - z5[x].sum().sum()
    G, B = pct(s[g].sum(), den), pct(s[b].sum(), den); G5, B5 = pct(z5[g].sum(), den5), pct(z5[b].sum(), den5)
    grp = [g, b, u] + x
    r = within(s, grp, TC, weights=('stations',))['stations']
    xs = ' / '.join(f"{r.get((c, 'm_DPP'), np.nan):.2f}" for c in x) or '–'; xc = ' / '.join(f"{r.get((c, 'm_KMT'), np.nan):.2f}" for c in x) or '–'
    say(f"| {lab} | {G:.1f} | {B:.1f} | {shen - G:+.1f} | {chiang - B:+.1f} | {shen5 - G5:+.1f} | {chiang5 - B5:+.1f} | {r[(g, 'm_DPP')]:.3f} | {r[(b, 'm_KMT')]:.3f} | {xs} | {xc} |")
    JS.setdefault('taipei_sens', {})[lab] = dict(G=G, B=B, gap_shen=shen - G, gap_chiang=chiang - B, d5_shen=shen5 - G5, d5_chiang=chiang5 - B5,
                                                 GG=r[(g, 'm_DPP')], BB=r[(b, 'm_KMT')])
say('Published (Goodman): pan-green 45.1, pan-blue 54.3, gaps +0.6 / -0.6; D5 gaps +5.6 / -5.6; loyalty 0.930 / 0.927; Hsu unassigned: Chiang gap +0.8.')

say('\n### Taiwan: 20 two-camp races (researched camps; ambiguous = evidence B, C, U and Taipei\'s seven)')
camb = cc[cc.amb]
say(f'Ambiguous candidates by county: ' + ', '.join(f'{n} {len(g)}' for n, g in camb.groupby(camb.code.map(T.county))))
rows = []
for v, lab in (('base', '(a) published'), ('v_amb_U', '(b) ambiguous -> unaligned'), ('v_amb_X', '(c) ambiguous dropped'), ('v_label', 'party labels only')):
    Sv = P[v]; grp = ('c_G', 'c_B', 'c_U', 'c_XG', 'c_XB') if v == 'v_amb_X' else ('c_G', 'c_B', 'c_U')
    lo = loyalty(Sv, grp); sv = summarize(lo, Sv, 'stations'); tb_ = sv['table']
    gaps = []
    for c in TWO:
        z = Sv[Sv.code == c]; den = z.c_valid.sum() - z.c_X.sum()
        cg, cb = pct(z.c_G.sum(), den), pct(z.c_B.sum(), den); mg, mb = pct(z.m_G.sum(), z.m_valid.sum()), pct(z.m_B.sum(), z.m_valid.sum())
        gaps.append(dict(code=c, gap_G=mg - cg, gap_B=mb - cb, two=100 * mg / (mg + mb) - 100 * cg / (cg + cb)))
    gp = pd.DataFrame(gaps).set_index('code')
    rows.append(dict(variant=lab, cities=sv['cities'], counties=sv['counties'], r=sv['r'], gapG=gp.gap_G.mean(), gapB=gp.gap_B.mean(),
                     two=gp.two.mean(), two_abs_lt2=int((gp.two.abs() < 2).sum()), chiayi_UG=tb_.loc['10020', 'UG'], chiayi_UB=tb_.loc['10020', 'UB'],
                     tbl=tb_, gp=gp))
JS['taiwan_sens'] = {r['variant']: {k: r[k] for k in ('cities', 'counties', 'r', 'two', 'chiayi_UG', 'chiayi_UB')} for r in rows}
JS['n_ambiguous'] = int(cc.amb.sum())
say('| variant | loyalty cities | loyalty other h2h | corr(unaligned, loyalty) | mean green gap | mean blue gap | mean two-camp gap | |two-camp gap|<2 | Chiayi City U->DPP / U->KMT |')
say('|---|---|---|---|---|---|---|---|---|')
for r in rows:
    say(f"| {r['variant']} | {r['cities']:.3f} | {r['counties']:.3f} | {r['r']:.2f} | {r['gapG']:+.1f} | {r['gapB']:+.1f} | {r['two']:+.1f} | {r['two_abs_lt2']} | {r['chiayi_UG']:.2f} / {r['chiayi_UB']:.2f} |")
b0, bb = rows[0]['tbl'], rows[1]['tbl']; d = (bb.loyal - b0.loyal).sort_values()
say('Per-race loyalty, (b) minus (a), points: ' + ', '.join(f"{T.loc[c, 'county']} {100 * d[c]:+.1f}" for c in d.index if abs(d[c]) >= 0.005))
bc = rows[2]['tbl']; d = (bc.loyal - b0.loyal).sort_values()
say('Per-race loyalty, (c) minus (a), points: ' + ', '.join(f"{T.loc[c, 'county']} {100 * d[c]:+.1f}" for c in d.index if abs(d[c]) >= 0.005))

# ================================================================== CHECK 4: harmonized camps, village swing
say('\n## Check 4. Taipei 2022->2026 village swing with party-label camps in both years')
pv = pd.read_csv(f'{TPE_OUT}/villages_22_26.csv')
s26['town_'] = s26.town; s26['vil_'] = s26.village.str.replace('台', '臺')
g = s26.groupby(['town_', 'vil_'])[['c_GI', 'c_BI', 'c_valid', 'c_G', 'c_DPP', 'c_SDP']].sum()
g.index = g.index.set_names(['town', 'village'])
pv = pv.merge(g.add_suffix('_x').reset_index(), on=['town', 'village'], how='left')
assert pv.c_valid_x.notna().all() and (pv.c_valid_x == pv.c_valid26).all() and (pv.c_G_x == pv.c_G).all()
if 'dg_res' in pv:              # taipei_ballots.py after the 1 December 2026 revision: dg = labels both years, dg_res = first version
    pv['dg_lab'] = pv.dg; pv['dg'] = pv.dg_res; pv['g26'] = pv.c_G / pv.c_valid26
pv['g26_lab'] = (pv.c_G - pv.c_GI_x) / pv.c_valid26; assert np.allclose(pv.dg_lab, pv.g26_lab - pv.g22); pv['dg_lab'] = pv.g26_lab - pv.g22
dm = lambda c: pv[c] - pv.groupby('dist26')[c].transform('mean')
def wcorr(a, b): return np.corrcoef(dm(a), dm(b))[0, 1]
say('| measure | first version (2026 researched) | labels both years (revised) | difference |'); say('|---|---|---|---|')
for lab, f in (('mean green council gain (pts, village mean)', lambda c: 100 * pv[c].mean()),
               ('citywide green council gain (pts, vote-weighted)', lambda c: 100 * ((pv.g26 if c == 'dg' else pv.g26_lab) * pv.c_valid26).sum() / pv.c_valid26.sum() - 100 * pv.c_GREEN.sum() / pv.c_valid22.sum()),
               ('sd of green council gain (pts)', lambda c: 100 * pv[c].std()),
               ('sd ratio council/Shen', lambda c: pv[c].std() / pv.dS.std()),
               ('within-district r (green gain, Shen gain)', lambda c: wcorr(c, 'dS')),
               ('within-district slope, Shen gain on green gain', lambda c: np.polyfit(dm(c), dm('dS'), 1)[0])):
    a, b_ = f('dg'), f('dg_lab'); say(f'| {lab} | {a:.2f} | {b_:.2f} | {b_ - a:+.2f} |')
say('Green council gain by district (pts, village means), published -> harmonized: ' +
    '; '.join(f'D{int(d)} {100 * z.dg.mean():.1f} -> {100 * z.dg_lab.mean():.1f}' for d, z in pv.groupby('dist26')))
say(f'Share of the 2026 council vote cast for the three green-leaning independents: {pct(pv.c_GI_x.sum(), pv.c_valid26.sum()):.2f}% citywide; '
    f'villages where it exceeds 5%: {(pv.c_GI_x / pv.c_valid26 > 0.05).sum()} of {len(pv)}')

# ================================================================== CHECK 5: coattails with turnout control
say('\n## Check 5. Village coattails with turnout change and district fixed effects (456 villages; HC1 SEs)')
def ols(y, X, names):
    X = np.column_stack([np.asarray(x, float) for x in X]); yv = np.asarray(y, float)
    b, *_ = np.linalg.lstsq(X, yv, rcond=None); e = yv - X @ b; n, k = X.shape
    Xi = np.linalg.inv(X.T @ X); Vc = Xi @ (X.T * e ** 2) @ X @ Xi * n / (n - k)
    return {nm: (b[i], np.sqrt(Vc[i, i])) for i, nm in enumerate(names)}, 1 - (e ** 2).sum() / ((yv - yv.mean()) ** 2).sum()
FE = pd.get_dummies(pv.dist26, prefix='d').astype(float)
fe = [FE[c].values for c in FE]
say('| outcome | regressor | camp definition | no controls (pooled) | district FE | district FE + turnout change | turnout change coefficient |')
say('|---|---|---|---|---|---|---|')
for gcol, cd in (('dg', 'published'), ('dg_lab', 'harmonized')):
    for y, x, lab in (('dS', gcol, 'Shen gain on green council gain'), (gcol, 'dS', 'green council gain on Shen gain')):
        r0, _ = ols(pv[y], [np.ones(len(pv)), pv[x]], ['c', 'x'])
        r1, _ = ols(pv[y], fe + [pv[x]], list(FE) + ['x'])
        r2, _ = ols(pv[y], fe + [pv[x], pv.dt], list(FE) + ['x', 'dt'])
        f = lambda t: f'{t[0]:.2f} ({t[1]:.2f})'
        say(f"| {y} | {x} | {cd} | {f(r0['x'])} | {f(r1['x'])} | {f(r2['x'])} | {f(r2['dt'])} |")
        JS.setdefault('coattail', {})[f'{y}~{x}'] = dict(fe=r1['x'][0], fe_turnout=r2['x'][0], fe_turnout_se=r2['x'][1], turnout=r2['dt'][0], turnout_se=r2['dt'][1])
say(f'Turnout change, villages: mean {100 * pv.dt.mean():.1f} pts, sd {100 * pv.dt.std():.1f}; within-district r with Shen gain {wcorr("dt", "dS"):.2f}, '
    f'with green gain {wcorr("dt", "dg"):.2f} (published), {wcorr("dt", "dg_lab"):.2f} (harmonized)')
# partial correlations after district FE and turnout
def resid(c):
    r, _ = ols(pv[c], fe + [pv.dt], list(FE) + ['dt']); X = np.column_stack(fe + [pv.dt.values]); b = np.array([r[n][0] for n in list(FE) + ['dt']])
    return pv[c].values - X @ b
for gcol, cd in (('dg', 'published'), ('dg_lab', 'harmonized')):
    say(f'Partial r (green gain, Shen gain | district FE, turnout change), {cd}: {np.corrcoef(resid(gcol), resid("dS"))[0, 1]:.2f}')
    JS.setdefault('partial_r', {})[cd] = float(np.corrcoef(resid(gcol), resid('dS'))[0, 1])

# ================================================================== CHECK 6: effective number of council candidates
say('\n## Check 6. Effective number of council candidates (ENC) as a control, 20 two-camp races')
cand = cv[cv.kind == 'general'].groupby(['code', 'race_id', 'no']).votes.sum().reset_index()
seats = C.merge(co, on='eid').groupby('race_id').seats.first()
enc = []
for (code, rid), z in cand.groupby(['code', 'race_id']):
    p = z.votes / z.votes.sum(); enc.append(dict(code=code, race_id=rid, enc=1 / (p ** 2).sum(), seats=seats.get(rid, np.nan), valid=z.votes.sum()))
enc = pd.DataFrame(enc); enc['enc_seat'] = enc.enc / enc.seats
ce = enc.groupby('code').apply(lambda z: pd.Series({'enc': np.average(z.enc, weights=z.valid), 'enc_seat': np.average(z.enc_seat, weights=z.valid)}))
d = sm['stations']['table'].join(ce)
say(f"ENC per district (valid-vote weighted county mean): {d.enc.min():.1f}-{d.enc.max():.1f}; per seat {d.enc_seat.min():.2f}-{d.enc_seat.max():.2f}")
say(f"corr(unaligned, loyalty) {np.corrcoef(d.c_U, d.loyal)[0, 1]:.2f}; corr(ENC, loyalty) {np.corrcoef(d.enc, d.loyal)[0, 1]:.2f}; "
    f"corr(ENC per seat, loyalty) {np.corrcoef(d.enc_seat, d.loyal)[0, 1]:.2f}; corr(unaligned, ENC) {np.corrcoef(d.c_U, d.enc)[0, 1]:.2f}; corr(unaligned, ENC per seat) {np.corrcoef(d.c_U, d.enc_seat)[0, 1]:.2f}")
def pcorr(a, b, c):
    ra = d[a] - np.polyval(np.polyfit(d[c], d[a], 1), d[c]); rb = d[b] - np.polyval(np.polyfit(d[c], d[b], 1), d[c]); return np.corrcoef(ra, rb)[0, 1]
for c in ('enc', 'enc_seat'):
    r, r2 = ols(d.loyal, [np.ones(len(d)), d.c_U / 100, d[c]], ['c', 'U', c])
    say(f"loyalty ~ unaligned share + {c}: unaligned coef {r['U'][0]:.2f} (SE {r['U'][1]:.2f}) per unit share, {c} coef {r[c][0]:.3f} (SE {r[c][1]:.3f}); R2 {r2:.2f}; "
        f"partial r(unaligned, loyalty | {c}) {pcorr('c_U', 'loyal', c):.2f}")
r, r2 = ols(d.loyal, [np.ones(len(d)), d.c_U / 100], ['c', 'U']); say(f"loyalty ~ unaligned share alone: coef {r['U'][0]:.2f} (SE {r['U'][1]:.2f}); R2 {r2:.2f}")
say(f"Same, excluding the six municipalities (14 races): corr(unaligned, loyalty) {np.corrcoef(d[~d.muni].c_U, d[~d.muni].loyal)[0, 1]:.2f}")
JS['corr_all'] = float(np.corrcoef(d.c_U, d.loyal)[0, 1]); JS['corr_nonmuni'] = float(np.corrcoef(d[~d.muni].c_U, d[~d.muni].loyal)[0, 1])
JS['n_nonmuni'] = int((~d.muni).sum()); JS['pcorr_enc'] = float(pcorr('c_U', 'loyal', 'enc')); JS['pcorr_enc_seat'] = float(pcorr('c_U', 'loyal', 'enc_seat'))
JS['corr_muni_only'] = float(np.corrcoef(d[d.muni].c_U, d[d.muni].loyal)[0, 1])

# ================================================================== tables for the EI script
s26.to_csv(f'{OUT}/ei_taipei_stations.csv', index=False)
pv.to_csv(f'{OUT}/ei_taipei_villages.csv', index=False)
S.to_csv(f'{OUT}/ei_allcounty_stations.csv', index=False)
sm['stations']['table'].assign(county=lambda d: d.index.map(T.county)).to_csv(f'{OUT}/ei_goodman_loyalty.csv')
import json
json.dump(JS, open(f'{OUT}/checks.json', 'w'), indent=1, default=float)
open(f'{OUT}/checks.md', 'w').write('\n'.join(LOG) + '\n')
print(f'wrote {OUT}/checks.md')

expected output: OUT/checks/checks.md

# Robustness checks: mayoral vs council votes (Taipei and Taiwan pages)
Estimates describe polling stations (villages for the 2022->2026 panel) in aggregate, not individual voters.

## Check 1. District weights: stations (published) vs registered electors vs mayoral valid votes

### Taipei (six general districts; taipei_ballots.py specification)
| estimate | published (Goodman) | stations | electors | valid votes | max diff (pts) |
|---|---|---|---|---|---|
| pan-green -> Shen | 0.930 | 0.927 | 0.926 | 0.926 | 0.1 |
| pan-blue -> Chiang | 0.927 | 0.924 | 0.925 | 0.925 | 0.1 |
| TPP -> Chiang | 0.910 | 0.897 | 0.899 | 0.899 | 0.2 |
| TPP -> Shen | 0.080 | 0.091 | 0.089 | 0.089 | 0.2 |

All-county researched camps applied: 54 council candidates; of which ambiguous (evidence B, C, U, or Taipei's seven independents): 33; evidence A: 21
Rebuilt all-county panel: 18,248 stations; largest difference from published loyalty.csv (station weights): 1.11e-16

### Taiwan page (bounded regression within general council districts, researched camps; "published" = Goodman figures on the page)
| estimate | published | stations | electors | valid votes | max diff (pts) |
|---|---|---|---|---|---|
| Cities loyalty (6 head-to-head) | 0.862 | 0.855 | 0.857 | 0.857 | 0.2 |
| Other head-to-head loyalty (11) | 0.750 | 0.734 | 0.736 | 0.736 | 0.2 |
| Chiayi City unaligned -> DPP | 0.616 | 0.616 | 0.616 | 0.616 | 0.0 |
| Chiayi City unaligned -> KMT | 0.350 | 0.350 | 0.350 | 0.350 | 0.0 |
| Taipei loyalty (Taiwan-page spec) | 0.930 | 0.927 | 0.927 | 0.927 | 0.0 |
| corr(unaligned share, loyalty), 20 races | -0.650 | -0.686 | -0.668 | -0.672 | 1.8 |
Per-race loyalty, electors vs stations: largest moves Penghu +2.3, Taitung +1.6, Yilan -1.0, Hsinchu County +0.8; races moving 1 point or more: 2 of 20

## Check 3. Camp sensitivity
Variants: (a) published classification; (b) ambiguous independents counted unaligned; (c) ambiguous independents a group of
their own, left out of the camp shares (denominator = council valid votes minus their votes) and entered as a separate
regressor in the bounded models (green-leaning and blue-leaning ambiguous candidates as two separate groups). Taipei ambiguous = GREEN_IND (陳怡君, 朱政騏, 紀建漢) and BLUE_IND (陳怡潔, 陳重文, 應佳妤, 徐立信).

### Taipei
| variant | pan-green % | pan-blue % | Shen gap | Chiang gap | D5 Shen gap | D5 Chiang gap | green->Shen | blue->Chiang | ambiguous->Shen (green-leaning / blue-leaning) | ambiguous->Chiang (same) |
|---|---|---|---|---|---|---|---|---|---|---|
| (a) published | 45.1 | 54.3 | +0.6 | -0.6 | +5.6 | -5.6 | 0.927 | 0.924 | – | – |
| (b) ambiguous -> unaligned | 44.2 | 51.2 | +1.5 | +2.5 | +5.6 | +7.5 | 0.937 | 0.935 | – | – |
| (c) ambiguous dropped | 46.0 | 53.3 | -0.3 | +0.4 | -0.5 | +0.5 | 0.938 | 0.937 | 0.57 / 0.22 | 0.43 / 0.76 |
| (b') Hsu only -> unaligned | 45.1 | 52.9 | +0.6 | +0.8 | +5.6 | +5.4 | 0.927 | 0.928 | – | – |
| (c') Hsu only dropped | 45.7 | 53.6 | +0.0 | +0.1 | +0.6 | -0.6 | 0.927 | 0.928 | 0.20 | 0.77 |
Published (Goodman): pan-green 45.1, pan-blue 54.3, gaps +0.6 / -0.6; D5 gaps +5.6 / -5.6; loyalty 0.930 / 0.927; Hsu unassigned: Chiang gap +0.8.

### Taiwan: 20 two-camp races (researched camps; ambiguous = evidence B, C, U and Taipei's seven)
Ambiguous candidates by county: Changhua 2, Hsinchu City 3, Hualien 2, Kaohsiung 1, Keelung 2, Miaoli 1, Nantou 1, Taichung 5, Tainan 1, Taipei 8, Taoyuan 3, Yilan 1, Yunlin 3
| variant | loyalty cities | loyalty other h2h | corr(unaligned, loyalty) | mean green gap | mean blue gap | mean two-camp gap | |two-camp gap|<2 | Chiayi City U->DPP / U->KMT |
|---|---|---|---|---|---|---|---|---|
| (a) published | 0.855 | 0.734 | -0.69 | +12.5 | +7.9 | +3.8 | 5 | 0.62 / 0.35 |
| (b) ambiguous -> unaligned | 0.861 | 0.738 | -0.69 | +13.3 | +8.8 | +3.8 | 5 | 0.62 / 0.35 |
| (c) ambiguous dropped | 0.861 | 0.738 | -0.71 | +12.7 | +8.1 | +3.8 | 5 | 0.62 / 0.35 |
| party labels only | 0.867 | 0.739 | -0.49 | +13.6 | +10.5 | +2.4 | 4 | 0.57 / 0.39 |
Per-race loyalty, (b) minus (a), points: Keelung -0.8, Miaoli -0.5, Changhua +0.5, Taichung +0.6, Taoyuan +0.8, Yunlin +0.9, Yilan +1.0, Taipei +1.0, Kaohsiung +1.5, Hualien +1.7, Hsinchu City +3.2
Per-race loyalty, (c) minus (a), points: Miaoli -0.6, Taichung +0.5, Taoyuan +0.5, Yilan +1.0, Taipei +1.2, Kaohsiung +1.4, Hualien +2.5, Hsinchu City +3.2

## Check 4. Taipei 2022->2026 village swing with party-label camps in both years
| measure | first version (2026 researched) | labels both years (revised) | difference |
|---|---|---|---|
| mean green council gain (pts, village mean) | 8.74 | 7.78 | -0.96 |
| citywide green council gain (pts, vote-weighted) | 9.01 | 8.11 | -0.90 |
| sd of green council gain (pts) | 4.22 | 4.93 | +0.71 |
| sd ratio council/Shen | 2.61 | 3.05 | +0.44 |
| within-district r (green gain, Shen gain) | 0.46 | 0.39 | -0.07 |
| within-district slope, Shen gain on green gain | 0.28 | 0.21 | -0.07 |
Green council gain by district (pts, village means), published -> harmonized: D1 13.5 -> 12.0; D2 11.4 -> 11.4; D3 8.8 -> 8.8; D4 4.3 -> -0.1; D5 4.0 -> 4.0; D6 8.9 -> 8.9
Share of the 2026 council vote cast for the three green-leaning independents: 0.90% citywide; villages where it exceeds 5%: 19 of 456

## Check 5. Village coattails with turnout change and district fixed effects (456 villages; HC1 SEs)
| outcome | regressor | camp definition | no controls (pooled) | district FE | district FE + turnout change | turnout change coefficient |
|---|---|---|---|---|---|---|
| dS | dg | published | 0.10 (0.02) | 0.28 (0.05) | 0.28 (0.05) | 0.08 (0.03) |
| dg | dS | published | 0.70 (0.11) | 0.76 (0.07) | 0.78 (0.07) | -0.08 (0.06) |
| dS | dg_lab | harmonized | 0.07 (0.02) | 0.21 (0.05) | 0.22 (0.05) | 0.08 (0.04) |
| dg_lab | dS | harmonized | 0.67 (0.14) | 0.71 (0.08) | 0.72 (0.08) | -0.12 (0.07) |
Turnout change, villages: mean 4.3 pts, sd 2.3; within-district r with Shen gain 0.10, with green gain -0.03 (published), -0.06 (harmonized)
Partial r (green gain, Shen gain | district FE, turnout change), published: 0.47
Partial r (green gain, Shen gain | district FE, turnout change), harmonized: 0.40

## Check 6. Effective number of council candidates (ENC) as a control, 20 two-camp races
ENC per district (valid-vote weighted county mean): 5.2-13.2; per seat 1.08-1.63
corr(unaligned, loyalty) -0.69; corr(ENC, loyalty) -0.02; corr(ENC per seat, loyalty) -0.56; corr(unaligned, ENC) 0.39; corr(unaligned, ENC per seat) 0.54
loyalty ~ unaligned share + enc: unaligned coef -0.54 (SE 0.08) per unit share, enc coef 0.015 (SE 0.008); R2 0.54; partial r(unaligned, loyalty | enc) -0.74
loyalty ~ unaligned share + enc_seat: unaligned coef -0.36 (SE 0.12) per unit share, enc_seat coef -0.228 (SE 0.182); R2 0.52; partial r(unaligned, loyalty | enc_seat) -0.55
loyalty ~ unaligned share alone: coef -0.46 (SE 0.08); R2 0.47
Same, excluding the six municipalities (14 races): corr(unaligned, loyalty) -0.33

The research files behind camps_council_2026.csv and the page builders are not included; the CSV carries each candidate’s evidence type, source, date and quotation.

Turnout and party mobilization

For Turnout and Party Mobilization: Taiwan, 2026. Runs on the cleaned tables above. turnout_counties.py totals each county’s electors, ballots and party votes for every mayoral and magistrate election from 2014 and every presidential election from 2016; village_panel.py builds a village-by-election table for one city or county; turnout_analysis.py produces every other number on the page. areas.py, taipei_ballots.py (both listed above) and camps_executive.csv must sit next to the scripts. The voter flows from 2022 to 2026 in Taipei are those of the Taipei analysis (results.md, section H). Run from scratch in an empty folder, the cleaning and these steps reproduce the expected outputs below byte for byte.

Run

python3 turnout_counties.py CLEAN OUT/turnout
for c in 63000 65000 66000 67000 64000 68000 10004 10017; do     # Taipei, New Taipei, Taichung, Tainan, Kaohsiung,
  python3 village_panel.py CLEAN OUT/panel $c                      # Taoyuan, Hsinchu County, Keelung
done
python3 turnout_analysis.py CLEAN OUT/turnout OUT/panel

Outputs

FileContentsArticle section
turnout/turnout_counties.mdturnout by county, local elections 2014–2026 and presidential elections 2016–2024appendix table
turnout/turnout_analysis.mdlong-run turnout by cycle, Taiwan and Taipei, with legislative elections; county changes and the rebound; village tests in eight cities and counties; robustness checks; each party’s mobilization rate by cycleall three questions
turnout/*.csv, turnout/extras.jsonthe same figures as tables
panel/villages_<code>.csv, panel/panel_<code>.mdone row per village and election: electors, ballots, votes by camp, age structureTaipei; within-city tests

Method

Files

turnout_counties.py

"""Turnout and 催票率 by city/county: local (mayor/magistrate) elections 2014-2026 and presidential elections 2012-2024.

usage: python3 turnout_counties.py CLEAN_DIR OUT_DIR
Writes OUT_DIR/turnout_counties.csv (one row per county and election) and OUT_DIR/turnout_counties.md.

turnout = ballots cast / electors.  催票率 (mobilization rate) = a party's votes / electors.
share = a party's votes / valid votes. DPP and KMT are by ballot label: a county where the party had no nominee
(e.g. it backed an independent) has no value for that party, so changes there are left out rather than guessed.
"""
import sys, os
import pandas as pd

CLEAN, OUT = sys.argv[1], sys.argv[2]
os.makedirs(OUT, exist_ok=True)
LOCAL = {2014: [70, 74], 2018: [88, 93], 2022: [105, 104]}
PRES = {2016: 83, 2020: 103, 2024: 122}           # 2012 files use pre-2014 county codes
cand = pd.read_parquet(f'{CLEAN}/candidates')
areas = pd.read_parquet(f'{CLEAN}/areas')
NAME = {}
for r in areas[(areas.town == '000') & (areas.vil == '0000')].itertuples():
    NAME[r.prv + r.city] = str(r.name).replace('台', '臺')
LOG = []
say = lambda s='': (LOG.append(s), print(s))
PARTY = {'民主進步黨': 'DPP', '中國國民黨': 'KMT', '台灣民眾黨': 'TPP', '親民黨': 'PFP'}

rows = []
for year, eids in LOCAL.items():
    for eid in eids:
        t = pd.read_parquet(f'{CLEAN}/turnout/source=cecdb', filters=[('eid', '==', eid)])
        v = pd.read_parquet(f'{CLEAN}/votes/source=cecdb', filters=[('eid', '==', eid)])
        c = cand[cand.eid == eid][['prv', 'city', 'no', 'party_std']].copy()
        c['lab'] = c.party_std.map(PARTY).fillna('other')
        c = c.drop(columns='party_std')
        v = v.merge(c, on=['prv', 'city', 'no'], how='left'); assert v.lab.notna().all()
        t = t.assign(county=t.prv + t.city); v = v.assign(county=v.prv + v.city)
        x = t.groupby('county')[['electors', 'cast', 'valid']].sum().join(v.pivot_table(index='county', columns='lab', values='votes', aggfunc='sum'))
        rows.append(x.reset_index().assign(year=year, kind='local'))

# Chiayi City's 2022 mayoral race was re-held on 18 December 2022 (嘉義市長重行選舉) and sits in the by-election files
Eb = pd.read_parquet(f'{CLEAN}/elections/source=cec_byelection')
eb = Eb[(Eb.year == 2022) & (Eb.office == 'executive') & (Eb.county == '嘉義市')].eid.tolist(); assert len(eb) == 1
t = pd.read_parquet(f'{CLEAN}/turnout/source=cec_byelection', filters=[('eid', '==', eb[0])])
v = pd.read_parquet(f'{CLEAN}/votes/source=cec_byelection', filters=[('eid', '==', eb[0])])
c = cand[cand.eid == eb[0]][['no', 'party_std']].drop_duplicates('no'); c['lab'] = c.party_std.map(PARTY).fillna('other')
v = v.merge(c[['no', 'lab']], on='no', how='left'); assert v.lab.notna().all()
x = pd.DataFrame([t[['electors', 'cast', 'valid']].sum()]).assign(county='10020').set_index('county').join(
    v.assign(county='10020').pivot_table(index='county', columns='lab', values='votes', aggfunc='sum'))
rows.append(x.reset_index().assign(year=2022, kind='local'))

E26 = pd.read_parquet(f'{CLEAN}/elections/source=cec2026')
for r in E26[E26.office == 'executive'].itertuples():
    t = pd.read_parquet(f'{CLEAN}/turnout/source=cec2026', filters=[('eid', '==', r.eid)])
    v = pd.read_parquet(f'{CLEAN}/votes/source=cec2026', filters=[('eid', '==', r.eid)])
    c = cand[cand.eid == r.eid][['no', 'party_std']].drop_duplicates('no')
    c['lab'] = c.party_std.map(PARTY).fillna('other')
    v = v.merge(c[['no', 'lab']], on='no', how='left'); assert v.lab.notna().all()
    cc = r.county[:5]; NAME.setdefault(cc, r.county[5:])
    x = pd.DataFrame([t[['electors', 'cast', 'valid']].sum()]).assign(county=cc).set_index('county').join(
        v.assign(county=cc).pivot_table(index='county', columns='lab', values='votes', aggfunc='sum'))
    rows.append(x.reset_index().assign(year=2026, kind='local'))

for year, eid in PRES.items():
    t = pd.read_parquet(f'{CLEAN}/turnout/source=cecdb', filters=[('eid', '==', eid)])
    v = pd.read_parquet(f'{CLEAN}/votes/source=cecdb', filters=[('eid', '==', eid)])
    c = cand[cand.eid == eid][['no', 'party_std']].drop_duplicates('no')
    c['lab'] = c.party_std.map(PARTY).fillna('other')
    v = v.merge(c[['no', 'lab']], on='no', how='left'); assert v.lab.notna().all()
    t = t.assign(county=t.prv + t.city); v = v.assign(county=v.prv + v.city)
    x = t.groupby('county')[['electors', 'cast', 'valid']].sum().join(v.pivot_table(index='county', columns='lab', values='votes', aggfunc='sum'))
    rows.append(x.reset_index().assign(year=year, kind='president'))

D = pd.concat(rows, ignore_index=True)
D['name'] = D.county.map(NAME)
# counties renamed or upgraded within the window: keep only the 22 current ones (2014 onward codes match 2026)
cur = set(D[D.year == 2026].county)
gone = D[~D.county.isin(cur)][['year', 'county', 'name']].drop_duplicates()
if len(gone): say('Rows whose county code is not a 2026 county (left out): ' + ', '.join(f'{r.year} {r.county} {r.name}' for r in gone.itertuples()))
D = D[D.county.isin(cur)].copy()
D['name'] = D.county.map({r.county: r.name for r in D[D.year == 2026].itertuples()})
D['turnout'] = D.cast / D.electors
for p in ('DPP', 'KMT', 'TPP'):
    D[f'mob_{p}'] = D[p] / D.electors
    D[f'share_{p}'] = D[p] / D.valid
D = D.sort_values(['kind', 'year', 'county'])
D.to_csv(f'{OUT}/turnout_counties.csv', index=False)

say('# Turnout by county (ballots cast / electors, %)')
tab = D.pivot_table(index='name', columns=['kind', 'year'], values='turnout') * 100
nat = D.groupby(['kind', 'year']).apply(lambda g: 100 * g.cast.sum() / g.electors.sum(), include_groups=False)
tab.loc['Taiwan'] = nat
say(tab.round(1).to_string())
say('\n# Electors and valid votes, all counties: ' + '; '.join(f'{k[0]} {k[1]}: {int(g.electors.sum()):,} electors, {int(g.valid.sum()):,} valid'
                                                               for k, g in D.groupby(['kind', 'year'])))
open(f'{OUT}/turnout_counties.md', 'w', encoding='utf-8').write('\n'.join(LOG) + '\n')

village_panel.py

"""Village panel for one city or county: turnout, mayoral and council votes by camp, presidential votes, and age structure.

usage: python3 village_panel.py CLEAN_DIR OUT_DIR [COUNTY]     (COUNTY = MOI code, default 63000 = Taipei)
Reads the cleaned tables (votes, turnout, candidates, areas, demog_age.parquet). Writes OUT_DIR/villages_<COUNTY>.csv,
one row per village (里) and election, and OUT_DIR/panel_<COUNTY>.md with match rates and totals.

Key: (district name, village name). Older CEC files use CEC area codes and 2026 files and the population data use MOI
codes, so names are the only key common to all. Stations listed under one village are counted in that village; for
2026 stations covering several villages (vil_list) the votes stay with the village the station is filed under.

Camps, by ballot label (the default rule in CLAUDE.md):
  green = DPP, SDP, NPP, TSP, Green Party, Obasan, TSU;  blue = KMT, New Party, PFP;  TPP kept separate in every year.
In 2026 Taipei, the researched classification of the published Taipei page (taipei_ballots.camp) is added as
c_G_res / c_B_res / c_U_res, so the two definitions can be compared (critique: harmonize 2022 and 2026).
"""
import sys, os
import pandas as pd

CLEAN, OUT = sys.argv[1], sys.argv[2]
COUNTY = sys.argv[3] if len(sys.argv) > 3 else '63000'
os.makedirs(OUT, exist_ok=True)
GREEN = {'民主進步黨', '社會民主黨', '時代力量', '台灣基進', '台灣綠黨', '綠黨', '小民參政歐巴桑聯盟', '台灣團結聯盟'}
BLUE = {'中國國民黨', '新黨', '親民黨'}
TPP = '台灣民眾黨'
# CEC database election ids (cecdb) and 2026 ids by office; see _data/clean/elections
LOCAL = {2014: dict(mayor=70, council=66), 2018: dict(mayor=88, council=84), 2022: dict(mayor=105, council=112)}   # special municipalities
LOCAL_COUNTY = {2014: dict(mayor=74, council=72), 2018: dict(mayor=93, council=91), 2022: dict(mayor=104, council=111)}   # other cities and counties
PRES = {2020: 103, 2024: 122}
AGE_MONTH = {2018: 10710, 2022: 11110, 2026: 11510}            # October before each local election
LOG = []
say = lambda s='': (LOG.append(s), print(s))

areas = pd.read_parquet(f'{CLEAN}/areas')
cand = pd.read_parquet(f'{CLEAN}/candidates')
E26 = pd.read_parquet(f'{CLEAN}/elections/source=cec2026')
e26 = E26[E26.county.astype(str).str.startswith(COUNTY)].set_index('office').eid.to_dict()
CNAME = E26[E26.county.astype(str).str.startswith(COUNTY)].county.iloc[0][5:]
prv, city = (COUNTY[:2], '000') if COUNTY.endswith('000') else (COUNTY[:2], COUNTY[2:])
say(f'# Village panel: {CNAME} ({COUNTY})')
if not COUNTY.endswith('000'): LOCAL = LOCAL_COUNTY

import re
src = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'areas.py'), encoding='utf-8').read()
RARE = eval(re.search(r'RARE = (\{.*?\})', src, re.S).group(1))        # rare characters encoded differently by each source (areas.py)
def norm(s):
    if s is None or s != s: return None
    s = str(s).replace('台', '臺').strip()
    for k, v in RARE.items(): s = s.replace(k, v)
    return s

def cecdb(table, eid):
    d = pd.read_parquet(f'{CLEAN}/{table}/source=cecdb', filters=[('eid', '==', eid), ('prv', '==', prv)])
    d = d[d.city == city] if 'city' in d else d
    a = areas[(areas.eid == eid) & (areas.prv == prv)]
    # vote rows carry the electoral district in `dist`, the area list does not: match on city, town and village codes
    tn = a[a.vil == '0000'].drop_duplicates(['city', 'town']).set_index(['city', 'town']).name
    vn = a[a.vil != '0000'].drop_duplicates(['city', 'town', 'vil']).set_index(['city', 'town', 'vil']).name
    d['town_name'] = [tn.get((c, t)) for c, t in zip(d.city, d.town)]
    d['village_name'] = [vn.get((c, t, v)) for c, t, v in zip(d.city, d.town, d.vil)]
    return d

def c2026(table, eid):
    return pd.read_parquet(f'{CLEAN}/{table}/source=cec2026', filters=[('eid', '==', eid)])

def camp_of(party, year):
    return 'G' if party in GREEN else 'B' if party in BLUE else 'TPP' if party == TPP else 'U'

def key(d):
    d = d.copy(); d['town_name'] = d.town_name.map(norm); d['village_name'] = d.village_name.map(norm); return d

rows = []
def add(year, kind, turn, votes, cands, by='no'):
    """turn: station turnout rows; votes: station x ballot-number votes; cands: ballot no (and race) -> label column."""
    turn, votes = key(turn).fillna({'town_name': '?', 'village_name': '?'}), key(votes).fillna({'town_name': '?', 'village_name': '?'})
    t = turn.groupby(['town_name', 'village_name'])[['electors', 'cast', 'valid']].sum().add_prefix(f'{kind}_')
    v = votes.merge(cands, on=by, how='left')
    assert v.lab.notna().all(), (year, kind, v[v.lab.isna()][by].unique()[:5])
    w = v.pivot_table(index=['town_name', 'village_name'], columns='lab', values='votes', aggfunc='sum', fill_value=0).add_prefix(f'{kind}_')
    x = t.join(w, how='outer').reset_index().assign(year=year)
    bad = (x.village_name == '?') | (x.town_name == '?')
    say(f'  {year} {kind}: {len(x) - bad.sum()} villages; ' + (f'{x[bad][f"{kind}_valid"].sum():,.0f} valid votes without a village name dropped' if bad.any() else 'all stations named'))
    rows.append(x[~bad])

# ---------------------------------------------------------------- local elections 2014-2022 (CEC database)
for year, ids in LOCAL.items():
    cm = cand[(cand.eid == ids['mayor']) & (cand.prv == prv) & (cand.city == city)][['no', 'name', 'party_std']].copy()
    vm = cecdb('votes', ids['mayor'])
    tot = vm.groupby('no').votes.sum()
    cm['lab'] = [camp_of(p, year) for p in cm.party_std]
    rest = tot.drop(cm[cm.lab.isin(['G', 'B'])].no, errors='ignore')
    if len(rest): cm.loc[cm.no == rest.idxmax(), 'lab'] = 'third'      # largest other candidate, e.g. Ko 2014/2018, Huang 2022
    cm.loc[~cm.lab.isin(['G', 'B', 'third']), 'lab'] = 'other'
    say(f'  {year} mayor: ' + ', '.join(f'{r.name} ({r.party_std}) = {r.lab}' for r in cm[cm.lab != 'other'].itertuples()))
    add(year, 'm', cecdb('turnout', ids['mayor']), vm, cm[['no', 'lab']])
    cc = cand[(cand.eid == ids['council']) & (cand.prv == prv) & (cand.city == city)][['race_id', 'no', 'party_std']].copy()
    cc['lab'] = [camp_of(p, year) for p in cc.party_std]
    add(year, 'c', cecdb('turnout', ids['council']), cecdb('votes', ids['council']), cc[['race_id', 'no', 'lab']], by=['race_id', 'no'])

# ---------------------------------------------------------------- 2026 (CEC tables, cleaned)
c6 = cand[cand.eid == e26['executive']][['no', 'name_zh', 'party_std', 'total']].copy()
c6['lab'] = [camp_of(p, 2026) for p in c6.party_std]
c6.loc[~c6.lab.isin(['G', 'B']), 'lab'] = 'other'
say('  2026 mayor: ' + ', '.join(f'{r.name_zh} ({r.party_std}) = {r.lab}' for r in c6[c6.lab != 'other'].itertuples()))
add(2026, 'm', c2026('turnout', e26['executive']), c2026('votes', e26['executive']), c6[['no', 'lab']])
k6 = cand[cand.eid == e26['council']][['race_id', 'no', 'name_zh', 'party_std', 'seat_type']].copy()
gen = k6.seat_type.isna() | (k6.seat_type == 'general')
k6['lab'] = [camp_of(p, 2026) for p in k6.party_std]
if COUNTY == '63000':                                            # researched camps of the published Taipei page
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    src = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'taipei_ballots.py'), encoding='utf-8').read()
    ns = {}; exec(src[src.index('GREEN_PARTIES'):src.index('def load2026')], ns)
    k6['res'] = [{'G': 'G_res', 'B': 'B_res'}.get(ns['camp'](n, p)[0], 'U_res') for n, p in zip(k6.name_zh, k6.party_std)]
vc = c2026('votes', e26['council']).merge(k6[gen][['race_id', 'no']], on=['race_id', 'no'])
tc = c2026('turnout', e26['council']); tc = tc[tc.race_id.isin(k6[gen].race_id)]
add(2026, 'c', tc, vc, k6[gen][['race_id', 'no', 'lab']], by=['race_id', 'no'])
if 'res' in k6:
    r = key(vc).merge(k6[['race_id', 'no', 'res']], on=['race_id', 'no']).pivot_table(index=['town_name', 'village_name'], columns='res', values='votes', aggfunc='sum', fill_value=0).add_prefix('c_').reset_index()
    rows[-1] = rows[-1].merge(r, on=['town_name', 'village_name'], how='left')

# ---------------------------------------------------------------- presidential 2020, 2024
for year, eid in PRES.items():
    cp = cand[cand.eid == eid][['no', 'party_std']].drop_duplicates('no').copy()
    cp['lab'] = [{'民主進步黨': 'DPP', '中國國民黨': 'KMT', '台灣民眾黨': 'TPP', '親民黨': 'PFP'}.get(p, 'other') for p in cp.party_std]
    add(year, 'p', cecdb('turnout', eid), cecdb('votes', eid), cp[['no', 'lab']])

P = pd.concat(rows, ignore_index=True)
P = P.groupby(['year', 'town_name', 'village_name'], as_index=False).sum(min_count=1)

# ---------------------------------------------------------------- age structure (MOI, October before each local election)
D = pd.read_parquet(f'{CLEAN}/demog_age.parquet')
D = D[D.county == COUNTY].assign(town_name=lambda d: d.county_town.str[3:].map(norm), village_name=lambda d: d.village.map(norm))
bands = {'a20_29': (20, 29), 'a30_39': (30, 39), 'a40_64': (40, 64), 'a65p': (65, 200)}
ages = []
for year, mo in AGE_MONTH.items():
    d = D[D.month == mo]
    g = d.groupby(['town_name', 'village_name'])
    a = pd.DataFrame({'pop': g.population.sum(), 'pop20p': d[d.age >= 20].groupby(['town_name', 'village_name']).population.sum()})
    for b, (lo, hi) in bands.items():
        a[b] = d[(d.age >= lo) & (d.age <= hi)].groupby(['town_name', 'village_name']).population.sum() / a.pop20p
    s = d[d.age >= 20].sort_values('age')                                       # median age of adults 20+
    a['med20p'] = s.groupby(['town_name', 'village_name'])[['age', 'population']].apply(lambda x: x.age.values[(x.population.cumsum() >= x.population.sum() / 2).values.argmax()])
    ages.append(a.reset_index().assign(year=year))
A = pd.concat(ages, ignore_index=True)
P = P.merge(A, on=['year', 'town_name', 'village_name'], how='left')

# ---------------------------------------------------------------- report
say('\n## Coverage')
for year, g in P.groupby('year'):
    tot = g.filter(like='_valid').sum()
    agem = g.pop20p.notna().mean() if year in AGE_MONTH else float('nan')
    say(f'  {year}: {len(g)} villages; ' + '; '.join(f'{k} {int(v):,}' for k, v in tot.items()) +
        (f'; age matched {100*agem:.1f}% of villages' if year in AGE_MONTH else ''))
say('\n## Citywide turnout (cast / electors) and camp 催票率 (votes / electors), local elections')
for year, g in P[P.year.isin(list(LOCAL) + [2026])].groupby('year'):
    e = g.m_electors.sum()
    say(f'  {year}: turnout {100*g.m_cast.sum()/e:.1f}%; mayor G {100*g.get("m_G", 0).sum()/e:.1f}%, B {100*g.get("m_B", 0).sum()/e:.1f}%, '
        f'third {100*g.get("m_third", pd.Series([0])).sum()/e:.1f}%; council G {100*g.get("c_G", 0).sum()/e:.1f}%, B {100*g.get("c_B", 0).sum()/e:.1f}%, '
        f'TPP {100*g.get("c_TPP", pd.Series([0])).sum()/e:.1f}%')
for year, g in P[P.year.isin(PRES)].groupby('year'):
    e = g.p_electors.sum()
    say(f'  {year} president: turnout {100*g.p_cast.sum()/e:.1f}%; DPP {100*g.p_DPP.sum()/e:.1f}%, KMT {100*g.p_KMT.sum()/e:.1f}%' +
        (f', TPP {100*g.p_TPP.sum()/e:.1f}%' if 'p_TPP' in g and g.p_TPP.sum() else ''))
P.to_csv(f'{OUT}/villages_{COUNTY}.csv', index=False)
open(f'{OUT}/panel_{COUNTY}.md', 'w', encoding='utf-8').write('\n'.join(LOG) + '\n')
say(f'\nwrote {OUT}/villages_{COUNTY}.csv ({len(P)} rows)')

turnout_analysis.py

"""Turnout page analyses: long-run turnout, county changes, and village tests of who gained from higher turnout.

usage: python3 turnout_analysis.py CLEAN_DIR TURNOUT_DIR PANEL_DIR
Needs TURNOUT_DIR/turnout_counties.csv (turnout_counties.py) and PANEL_DIR/villages_<code>.csv (village_panel.py).
Writes TURNOUT_DIR/longrun.csv, county_changes.csv, village_slopes.csv and turnout_analysis.md.

Measures: turnout = ballots cast / electors; 催票率 (mobilization rate) = votes / electors; share = votes / valid votes.
Camps at the county level are the DPP and KMT ballot labels (a county without a nominee has no value).
In the village panels, camps are by ballot label (village_panel.py): G = pan-green, B = pan-blue, third = largest other.
"""
import sys, os
import numpy as np
import pandas as pd

CLEAN, TDIR, PDIR = sys.argv[1:4]
import json
EX = {}   # numbers the page builder needs
LOG = []
say = lambda s='': (LOG.append(s), print(s))

# ---------------------------------------------------------------- 1. long-run turnout
# executive races by cycle: county magistrates/mayors and the special municipalities voted in different years until 2014
CYCLES = {'1997/98': [12, 15], '2001/02': [21, 24], '2005/06': [37, 41], '2009/10': [51, 55]}
PRES = {1996: 132, 2000: 20, 2004: 29, 2008: 42, 2012: 64}
TPE_LOCAL = {1994: 8, 1998: 15, 2002: 24, 2006: 41, 2010: 55}
LEG = {1995: 123, 1998: 126, 2001: 129, 2004: 30, 2008: 45}   # legislative elections held on their own day (from 2012 they coincide with the presidential)
areas = pd.read_parquet(f'{CLEAN}/areas')

def by_county(eid):
    t = pd.read_parquet(f'{CLEAN}/turnout/source=cecdb', filters=[('eid', '==', eid)])
    t = t.assign(county=t.prv + t.city)
    g = t.groupby('county')[['electors', 'cast']].sum()
    a = areas[(areas.eid == eid) & (areas.town == '000') & (areas.vil == '0000')]
    g['name'] = g.index.map(dict(zip(a.prv + a.city, a.name.str.replace('台', '臺'))))
    g.loc[g.index.isin(['01000', '63000']), 'name'] = '臺北市'   # legislative area lists name districts, not the city
    return g

C = pd.read_csv(f'{TDIR}/turnout_counties.csv', dtype={'county': str})
rows = []
for cyc, eids in CYCLES.items():
    g = pd.concat([by_county(e) for e in eids])
    rows.append(dict(kind='local', cycle=cyc, electors=g.electors.sum(), cast=g.cast.sum(),
                     taipei=float((g[g.name == '臺北市'].cast / g[g.name == '臺北市'].electors).iloc[0])))
for y in (2014, 2018, 2022, 2026):
    g = C[(C.kind == 'local') & (C.year == y)]
    rows.append(dict(kind='local', cycle=str(y), electors=g.electors.sum(), cast=g.cast.sum(),
                     taipei=float(g[g.name == '臺北市'].turnout.iloc[0])))
for y, e in PRES.items():
    g = by_county(e)
    rows.append(dict(kind='president', cycle=str(y), electors=g.electors.sum(), cast=g.cast.sum(),
                     taipei=float((g[g.name == '臺北市'].cast / g[g.name == '臺北市'].electors).iloc[0])))
for y, e in LEG.items():
    g = by_county(e)
    rows.append(dict(kind='legislative', cycle=str(y), electors=g.electors.sum(), cast=g.cast.sum(),
                     taipei=float((g[g.name == '臺北市'].cast / g[g.name == '臺北市'].electors).iloc[0])))
for y in (2016, 2020, 2024):
    g = C[(C.kind == 'president') & (C.year == y)]
    rows.append(dict(kind='president', cycle=str(y), electors=g.electors.sum(), cast=g.cast.sum(),
                     taipei=float(g[g.name == '臺北市'].turnout.iloc[0])))
L = pd.DataFrame(rows)
L['taiwan'] = L.cast / L.electors
tpe = []
for y, e in TPE_LOCAL.items():
    g = by_county(e); g = g[g.name == '臺北市']
    tpe.append(dict(year=y, taipei_mayor=float(g.cast.iloc[0] / g.electors.iloc[0])))
for y in (2014, 2018, 2022, 2026):
    tpe.append(dict(year=y, taipei_mayor=float(C[(C.kind == 'local') & (C.year == y) & (C.name == '臺北市')].turnout.iloc[0])))
T = pd.DataFrame(tpe)
EX['tpe_mayor'] = [[int(r.year), round(100 * r.taipei_mayor, 2)] for r in T.itertuples()]
L.to_csv(f'{TDIR}/longrun.csv', index=False)
say('# 1. Long-run turnout (%)')
say('Taiwan, by cycle (all executive races of the cycle pooled; electors in millions):')
for r in L.itertuples():
    say(f'  {r.kind:9s} {r.cycle:8s} Taiwan {100*r.taiwan:5.1f}  ({r.electors/1e6:5.2f}M electors)   Taipei {100*r.taipei:5.1f}')
say('Taipei mayoral elections: ' + ', '.join(f'{r.year} {100*r.taipei_mayor:.1f}' for r in T.itertuples()))

# ---------------------------------------------------------------- 2. county changes
say('\n# 2. County changes between local elections (percentage points)')
say('Left out: Kinmen and Lienchiang (registered electors largely living elsewhere; 38.6% and tiny electorates),')
say('Chiayi City in changes to or from 2022 (the 18 Dec 2022 re-run, turnout 44.0%).')
loc = C[(C.kind == 'local') & ~C.name.isin(['金門縣', '連江縣'])].copy()
W = loc.pivot_table(index='name', columns='year', values=['turnout', 'mob_DPP', 'mob_KMT', 'share_DPP', 'share_KMT'])
out = []
for a, b in ((2014, 2018), (2018, 2022), (2022, 2026)):
    d = pd.DataFrame({'d_turn': W['turnout'][b] - W['turnout'][a], 'd_dpp': W['mob_DPP'][b] - W['mob_DPP'][a],
                      'd_kmt': W['mob_KMT'][b] - W['mob_KMT'][a], 'd_sdpp': W['share_DPP'][b] - W['share_DPP'][a],
                      'turn_a': W['turnout'][a]}) * 100
    if 2022 in (a, b): d = d.drop(index='嘉義市')
    d['period'] = f'{a}-{b}'
    out.append(d.reset_index())
    msg = []
    for col, lab in (('d_dpp', 'DPP 催票率'), ('d_kmt', 'KMT 催票率'), ('d_sdpp', 'DPP share')):
        x = d[['d_turn', col]].dropna()
        slope = np.polyfit(x.d_turn, x[col], 1)[0]
        msg.append(f'{lab}: r = {x.corr().iloc[0, 1]:.2f}, slope {slope:.2f} (n = {len(x)})')
        EX[f'r_{col}_{a}_{b}'] = [x.corr().iloc[0, 1], slope, len(x)]
    say(f'  {a}->{b}: ' + '; '.join(msg))
D = pd.concat(out, ignore_index=True)
D.to_csv(f'{TDIR}/county_changes.csv', index=False)
d = D[D.period == '2022-2026'].set_index('name').sort_values('d_turn', ascending=False)
say('\n2022->2026 by county (turnout change; DPP and KMT 催票率 change; 2022 turnout):')
for n, r in d.iterrows():
    say(f'  {n}  {r.d_turn:+5.1f}   DPP {r.d_dpp:+5.1f}   KMT {r.d_kmt:+5.1f}   (2022: {r.turn_a:.1f})')
# rebound: did turnout rise most where it had fallen most in 2022?
p = D.pivot_table(index='name', columns='period', values='d_turn').dropna()
EX['rebound_r'] = p.corr().loc['2018-2022', '2022-2026']; EX['rebound_n'] = len(p); EX['level_r'] = d[['turn_a', 'd_turn']].corr().iloc[0, 1]
say(f'\nRebound check: r(turnout change 2018-22, change 2022-26) = {p.corr().loc["2018-2022", "2022-2026"]:.2f} (n = {len(p)}); '
    f'r(2022 turnout, change 2022-26) = {d[["turn_a", "d_turn"]].corr().iloc[0, 1]:.2f}')
p['net_18_26'] = p['2018-2022'] + p['2022-2026']
say('Net change 2018->2026: ' + ', '.join(f'{n} {v:+.1f}' for n, v in p.net_18_26.sort_values(ascending=False).items()))

# ---------------------------------------------------------------- 3. village tests, 2022 -> 2026
say('\n# 3. Villages, 2022 -> 2026: within districts, where turnout rose more, whose 催票率 rose more?')
say('OLS of the change in each camp\'s mayoral 催票率 on the change in turnout, district fixed effects,')
say('control: 2022 third-candidate 催票率 (its votes had to go somewhere); villages weighted equally; HC1 standard errors.')
NAMES = {'63000': 'Taipei', '65000': 'New Taipei', '66000': 'Taichung', '67000': 'Tainan', '64000': 'Kaohsiung',
         '68000': 'Taoyuan', '10004': 'Hsinchu County', '10017': 'Keelung'}

def ols(y, X):
    X = np.column_stack(X); b, *_ = np.linalg.lstsq(X, y, rcond=None)
    e = y - X @ b; n, k = X.shape
    XtXi = np.linalg.pinv(X.T @ X)
    V = XtXi @ (X.T * e**2) @ X @ XtXi * n / (n - k)
    return b, np.sqrt(np.diag(V))

res = []
for code, nm in NAMES.items():
    P = pd.read_csv(f'{PDIR}/villages_{code}.csv')
    w = {}
    for y in (2018, 2022, 2026):
        g = P[P.year == y].set_index(['town_name', 'village_name'])
        e = g.m_electors
        w[y] = pd.DataFrame({'turn': g.m_cast / e, 'G': g.get('m_G', 0) / e, 'B': g.get('m_B', 0) / e,
                             'third': g.get('m_third', 0) / e, 'el': e}).fillna({'G': 0, 'B': 0, 'third': 0})
    X = w[2022].join(w[2026], lsuffix='22', rsuffix='26', how='inner').join(w[2018][['turn']].rename(columns={'turn': 'turn18'}), how='left')
    X = X[(X.el22 >= 100) & (X.el26 >= 100)]
    X['dt'] = (X.turn26 - X.turn22) * 100
    X['dG'] = (X.G26 - X.G22) * 100
    X['dB'] = (X.B26 - X.B22) * 100
    X['th22'] = X.third22 * 100
    dist = pd.get_dummies(X.index.get_level_values(0), drop_first=False).values.astype(float)
    r = dict(county=nm, n=len(X), turn22=100 * (X.turn22 * X.el22).sum() / X.el22.sum(), turn26=100 * (X.turn26 * X.el26).sum() / X.el26.sum(),
             sd_dt=X.dt.std())
    for cmp in ('G', 'B'):
        b, se = ols(X[f'd{cmp}'].values, [X.dt.values, X.th22.values, dist])
        r[f'slope_{cmp}'], r[f'se_{cmp}'] = b[0], se[0]
    b, se = ols((X.dG - X.dB).values, [X.dt.values, X.th22.values, dist])
    r['slope_margin'], r['se_margin'] = b[0], se[0]
    m = X.dropna(subset=['turn18'])
    r['rebound_r'] = np.corrcoef((m.turn22 - m.turn18), m.dt / 100)[0, 1]
    r['third22'] = 100 * (X.third22 * X.el22).sum() / X.el22.sum()
    res.append(r)
R = pd.DataFrame(res)
R.to_csv(f'{TDIR}/village_slopes.csv', index=False)
for r in R.itertuples():
    say(f'  {r.county:15s} n={r.n:4d}  turnout {r.turn22:.1f}->{r.turn26:.1f}  (village sd of change {r.sd_dt:.1f}); '
        f'per point of turnout: G {r.slope_G:+.2f} ({r.se_G:.2f}), B {r.slope_B:+.2f} ({r.se_B:.2f}), '
        f'G-B margin {r.slope_margin:+.2f} ({r.se_margin:.2f}); 2022 third 催票率 {r.third22:.1f}; '
        f'rebound r(change 18-22, change 22-26) = {r.rebound_r:.2f}')
open(f'{TDIR}/turnout_analysis.md', 'w', encoding='utf-8').write('\n'.join(LOG) + '\n')

# ---------------------------------------------------------------- 4. robustness (lessons from the mayor/council critique checks)
say('\n# 4. Robustness')
# (a) 2026 camps by the standard-bearer rule (code/camps_executive.csv) instead of ballot labels
cx = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'camps_executive.csv'))
cx = cx[(cx.year == 2026) & cx.camp_race.isin(['pan_green', 'pan_blue'])]
cand = pd.read_parquet(f'{CLEAN}/candidates')
E26 = pd.read_parquet(f'{CLEAN}/elections/source=cec2026')
sb = W.copy()
for r in cx.itertuples():
    eid = E26[(E26.office == 'executive') & (E26.county == r.county)].eid.iloc[0]
    v = cand[(cand.eid == eid) & (cand.name_zh == r.name)].total.iloc[0]
    nm = r.county[5:].replace('台', '臺'); el = C[(C.kind == 'local') & (C.year == 2026) & (C.name == nm)].electors.iloc[0]
    col = 'mob_DPP' if r.camp_race == 'pan_green' else 'mob_KMT'
    if nm in sb.index: sb.loc[nm, (col, 2026)] = v / el
    say(f'  standard-bearer 2026: {nm} {r.name} -> {col[4:]} 催票率 {100*v/el:.1f}')
d2 = pd.DataFrame({'d_turn': sb['turnout'][2026] - sb['turnout'][2022], 'd_dpp': sb['mob_DPP'][2026] - sb['mob_DPP'][2022],
                   'd_kmt': sb['mob_KMT'][2026] - sb['mob_KMT'][2022]}).drop(index='嘉義市') * 100
for col in ('d_dpp', 'd_kmt'):
    x = d2[['d_turn', col]].dropna()
    EX[f'sb_{col}'] = [x.corr().iloc[0, 1], np.polyfit(x.d_turn, x[col], 1)[0], len(x)]
    say(f'  2022->2026 with standard-bearers: {col} r = {x.corr().iloc[0, 1]:.2f}, slope {np.polyfit(x.d_turn, x[col], 1)[0]:.2f} (n = {len(x)})')
# (b) bootstrap interval for the county correlations, and the municipalities/other split
rng = np.random.default_rng(2026)
MUNI = ['臺北市', '新北市', '桃園市', '臺中市', '臺南市', '高雄市']
for per in ('2014-2018', '2018-2022', '2022-2026'):
    x = D[D.period == per].dropna(subset=['d_dpp'])
    bs = [np.corrcoef(*x.iloc[rng.integers(0, len(x), len(x))][['d_turn', 'd_dpp']].values.T)[0, 1] for _ in range(2000)]
    m, o = x[x.name.isin(MUNI)], x[~x.name.isin(MUNI)]
    EX[f'boot_{per}'] = [np.nanpercentile(bs, 2.5), np.nanpercentile(bs, 97.5), m[['d_turn', 'd_dpp']].corr().iloc[0, 1], o[['d_turn', 'd_dpp']].corr().iloc[0, 1], len(m), len(o)]
    v = [x.drop(i)[['d_turn', 'd_dpp']].corr().iloc[0, 1] for i in x.index]
    EX[f'loo_{per}'] = [min(v), max(v), x.name.iloc[int(np.argmin(v))], x.name.iloc[int(np.argmax(v))]]
    say(f'  {per}: r(turnout, DPP 催票率) = {x[["d_turn", "d_dpp"]].corr().iloc[0, 1]:.2f}, 95% bootstrap [{np.nanpercentile(bs, 2.5):.2f}, {np.nanpercentile(bs, 97.5):.2f}]; '
        f'municipalities r = {m[["d_turn", "d_dpp"]].corr().iloc[0, 1]:.2f} (n = {len(m)}), others r = {o[["d_turn", "d_dpp"]].corr().iloc[0, 1]:.2f} (n = {len(o)})')
# (c) village slopes weighted by 2026 electors
say('  Village slopes weighted by 2026 electors (margin G-B per point of turnout; equal-weight value in brackets):')
for code, nm in NAMES.items():
    P = pd.read_csv(f'{PDIR}/villages_{code}.csv')
    g = {y: P[P.year == y].set_index(['town_name', 'village_name']) for y in (2022, 2026)}
    X = pd.DataFrame({f'{k}{y}': g[y].get(f'm_{k}', 0) / g[y].m_electors for y in (2022, 2026) for k in ('cast', 'G', 'B', 'third')}).fillna(0)
    X['el22'], X['el26'] = g[2022].m_electors, g[2026].m_electors
    X = X.dropna(); X = X[(X.el22 >= 100) & (X.el26 >= 100)]
    s = np.sqrt(X.el26.values)
    dist = pd.get_dummies(X.index.get_level_values(0)).values.astype(float)
    y = ((X.G2026 - X.G2022) - (X.B2026 - X.B2022)).values * 100
    b, se = ols(y * s, [((X.cast2026 - X.cast2022) * 100).values * s, (X.third2022 * 100).values * s, dist * s[:, None]])
    EX.setdefault('wslope', {})[nm] = [b[0], se[0]]
    say(f'    {nm:15s} {b[0]:+.2f} ({se[0]:.2f})  [{R.set_index("county").slope_margin[nm]:+.2f}]')
open(f'{TDIR}/turnout_analysis.md', 'w', encoding='utf-8').write('\n'.join(LOG) + '\n')
json.dump(EX, open(f'{TDIR}/extras.json', 'w'), ensure_ascii=False, indent=1, default=float)

# ---------------------------------------------------------------- 5. party mobilization rates by cycle (an identity, no estimation)
# turnout = DPP rate + KMT rate + TPP rate + others' rate + invalid ballots / electors, all over the same electors
say('\n# 5. Mobilization rates (votes / registered electors, %) by party label, local elections')
PARTY = {'民主進步黨': 'DPP', '中國國民黨': 'KMT', '台灣民眾黨': 'TPP'}
cand = pd.read_parquet(f'{CLEAN}/candidates')
def cyc_votes(eids):
    out = []
    for eid in eids:
        t = pd.read_parquet(f'{CLEAN}/turnout/source=cecdb', filters=[('eid', '==', eid)])
        v = pd.read_parquet(f'{CLEAN}/votes/source=cecdb', filters=[('eid', '==', eid)])
        c = cand[cand.eid == eid][['prv', 'city', 'no', 'party_std']].drop_duplicates(['prv', 'city', 'no'])
        v = v.merge(c, on=['prv', 'city', 'no'], how='left'); assert v.party_std.notna().all(), eid
        v['lab'] = v.party_std.map(PARTY).fillna('other')
        a = areas[(areas.eid == eid) & (areas.town == '000') & (areas.vil == '0000')]
        nm = dict(zip(a.prv + a.city, a.name.str.replace('台', '臺')))
        for d in (t, v):
            d['name'] = (d.prv + d.city).map(nm); d.loc[(d.prv + d.city).isin(['01000', '63000']), 'name'] = '臺北市'
        x = t.groupby('name')[['electors', 'cast', 'valid']].sum().join(v.pivot_table(index='name', columns='lab', values='votes', aggfunc='sum'))
        out.append(x)
    return pd.concat(out)
mob = []
for cy_, eids in CYCLES.items():
    mob.append(cyc_votes(eids).reset_index().assign(cycle=cy_))
for y in (2014, 2018, 2022, 2026):
    g = C[(C.kind == 'local') & (C.year == y)].copy()
    g['other'] = g[['other', 'PFP']].sum(axis=1, min_count=1) if 'PFP' in g else g.other
    mob.append(g[['name', 'electors', 'cast', 'valid', 'DPP', 'KMT', 'TPP', 'other']].assign(cycle=str(y)))
MB = pd.concat(mob, ignore_index=True).fillna({'DPP': 0, 'KMT': 0, 'TPP': 0, 'other': 0})
MB['invalid'] = MB.cast - MB.valid
rowsm = []
for scope, g0 in (('Taiwan', MB), ('Taipei', MB[MB.name == '臺北市'])):
    for cy_, g in g0.groupby('cycle', sort=False):
        e = g.electors.sum()
        rowsm.append(dict(scope=scope, cycle=cy_, turnout=100 * g.cast.sum() / e, **{k: 100 * g[k].sum() / e for k in ('DPP', 'KMT', 'TPP', 'other', 'invalid')}))
MR = pd.DataFrame(rowsm)
MR.to_csv(f'{TDIR}/mobilization.csv', index=False)
for r in MR.itertuples():
    say(f'  {r.scope:7s} {r.cycle:8s} turnout {r.turnout:5.1f} = DPP {r.DPP:5.1f} + KMT {r.KMT:5.1f} + TPP {r.TPP:4.1f} + other {r.other:5.1f} + invalid {r.invalid:4.1f}')
say('Changes between local elections (points):')
for scope in ('Taiwan', 'Taipei'):
    m = MR[MR.scope == scope].set_index('cycle').drop(columns='scope')
    for a_, b_ in zip(m.index[:-1], m.index[1:]):
        d_ = m.loc[b_] - m.loc[a_]
        say(f'  {scope:7s} {a_}->{b_}: turnout {d_.turnout:+5.1f}; DPP {d_.DPP:+5.1f}, KMT {d_.KMT:+5.1f}, TPP {d_.TPP:+4.1f}, other {d_.other:+5.1f}, invalid {d_.invalid:+4.1f}')
# counties: in how many did each party's rate rise, 2022 -> 2026 (nominee in both years)
d = D[D.period == '2022-2026']
for p_ in ('dpp', 'kmt'):
    x = d[f'd_{p_}'].dropna(); EX[f'n_up_{p_}'] = [int((x > 0).sum()), len(x)]
    say(f'  2022->2026 counties where the {p_.upper()} rate rose: {(x > 0).sum()} of {len(x)}')
# like with like: counties where both parties had a nominee in both elections
for a_, b_ in (('2014', '2018'), ('2018', '2022'), ('2022', '2026')):
    w = MB[MB.cycle.isin([a_, b_]) & ~MB.name.isin(['金門縣', '連江縣'])]
    ok = w.groupby('name').apply(lambda g: (g.DPP > 0).all() and (g.KMT > 0).all() and len(g) == 2)
    if '2022' in (a_, b_): ok = ok.drop(index='嘉義市', errors='ignore')
    k = ok[ok].index; w = w[w.name.isin(k)]
    r_ = {c: w.groupby('cycle').apply(lambda g: 100 * g[c].sum() / g.electors.sum()) for c in ('cast', 'DPP', 'KMT')}
    dd = {c: r_[c][b_] - r_[c][a_] for c in r_}
    EX[f'mob_both_{a_}_{b_}'] = dict(n=len(k), **dd)
    say(f'  both parties nominated in both years ({len(k)} counties), {a_}->{b_}: turnout {dd["cast"]:+.1f}, DPP {dd["DPP"]:+.1f}, KMT {dd["KMT"]:+.1f}')
EX['mob'] = MR.to_dict(orient='records')
json.dump(EX, open(f'{TDIR}/extras.json', 'w'), ensure_ascii=False, indent=1, default=float)
open(f'{TDIR}/turnout_analysis.md', 'w', encoding='utf-8').write('\n'.join(LOG) + '\n')

expected output: OUT/turnout/turnout_counties.md

# Turnout by county (ballots cast / electors, %)
kind   local                   president            
year    2014  2018  2022  2026      2016  2020  2024
name                                                
南投縣     73.1  72.7  69.1  69.1      63.6  73.2  71.1
嘉義市     71.0  67.9  44.0  61.4      66.6  76.0  72.9
嘉義縣     74.2  70.7  67.3  66.6      65.9  72.6  69.7
基隆市     63.9  62.5  60.2  63.4      64.0  73.3  70.6
宜蘭縣     70.5  69.1  64.3  65.7      64.1  73.9  71.0
屏東縣     73.5  71.1  67.2  67.4      66.0  74.9  70.3
彰化縣     72.9  70.9  64.9  65.9      66.6  74.7  72.4
新北市     61.7  64.0  56.6  64.3      67.2  75.1  72.8
新竹市     62.9  65.4  62.9  62.5      68.3  76.6  74.6
新竹縣     68.8  68.0  59.0  64.7      65.9  75.1  73.5
桃園市     62.7  60.6  59.5  60.4      66.7  74.4  72.2
澎湖縣     66.3  62.9  58.5  57.1      51.4  58.3  53.7
臺中市     71.9  67.5  60.0  65.1      68.4  76.4  73.9
臺北市     70.5  65.9  67.7  72.1      68.0  76.3  74.3
臺南市     65.9  64.0  58.7  64.2      65.8  75.8  72.0
臺東縣     67.8  68.3  64.8  65.1      55.1  65.0  62.0
花蓮縣     61.8  64.9  57.6  64.3      58.7  69.5  65.7
苗栗縣     72.8  70.7  67.2  65.0      64.8  73.8  71.7
連江縣     67.1  71.3  73.0  67.9      44.5  57.3  51.3
金門縣     45.2  42.8  39.3  38.6      33.6  40.1  36.4
雲林縣     74.1  71.6  67.3  67.3      61.8  71.6  68.5
高雄市     66.4  73.5  58.6  64.3      67.6  77.4  71.2
Taiwan  67.6  67.0  61.0  65.0      66.3  74.9  71.9

# Electors and valid votes, all counties: local 2014: 18,511,356 electors, 12,261,784 valid; local 2018: 19,102,502 electors, 12,506,833 valid; local 2022: 19,181,901 electors, 11,490,975 valid; local 2026: 19,576,028 electors, 12,556,956 valid; president 2016: 18,782,991 electors, 12,284,970 valid; president 2020: 19,311,105 electors, 14,300,940 valid; president 2024: 19,548,531 electors, 13,947,506 valid

expected output: OUT/turnout/turnout_analysis.md

# 1. Long-run turnout (%)
Taiwan, by cycle (all executive races of the cycle pooled; electors in millions):
  local     1997/98  Taiwan  68.8  (14.68M electors)   Taipei  80.9
  local     2001/02  Taiwan  67.3  (15.88M electors)   Taipei  70.6
  local     2005/06  Taiwan  66.1  (16.79M electors)   Taipei  64.5
  local     2009/10  Taiwan  68.4  (17.71M electors)   Taipei  70.6
  local     2014     Taiwan  67.6  (18.51M electors)   Taipei  70.5
  local     2018     Taiwan  67.0  (19.10M electors)   Taipei  65.9
  local     2022     Taiwan  61.0  (19.18M electors)   Taipei  67.7
  local     2026     Taiwan  65.0  (19.58M electors)   Taipei  72.1
  president 1996     Taiwan  76.0  (14.31M electors)   Taipei  76.3
  president 2000     Taiwan  82.7  (15.46M electors)   Taipei  83.5
  president 2004     Taiwan  80.3  (16.51M electors)   Taipei  81.7
  president 2008     Taiwan  76.3  (17.32M electors)   Taipei  79.2
  president 2012     Taiwan  74.4  (18.09M electors)   Taipei  76.8
  legislative 1995     Taiwan  67.8  (13.92M electors)   Taipei  66.0
  legislative 1998     Taiwan  68.3  (14.71M electors)   Taipei  80.9
  legislative 2001     Taiwan  66.3  (15.55M electors)   Taipei  64.4
  legislative 2004     Taiwan  59.4  (16.26M electors)   Taipei  61.3
  legislative 2008     Taiwan  58.7  (16.86M electors)   Taipei  62.2
  president 2016     Taiwan  66.3  (18.78M electors)   Taipei  68.0
  president 2020     Taiwan  74.9  (19.31M electors)   Taipei  76.3
  president 2024     Taiwan  71.9  (19.55M electors)   Taipei  74.3
Taipei mayoral elections: 1994 78.5, 1998 80.9, 2002 70.6, 2006 64.5, 2010 70.6, 2014 70.5, 2018 65.9, 2022 67.7, 2026 72.1

# 2. County changes between local elections (percentage points)
Left out: Kinmen and Lienchiang (registered electors largely living elsewhere; 38.6% and tiny electorates),
Chiayi City in changes to or from 2022 (the 18 Dec 2022 re-run, turnout 44.0%).
  2014->2018: DPP 催票率: r = 0.29, slope 0.77 (n = 16); KMT 催票率: r = 0.53, slope 1.67 (n = 20); DPP share: r = 0.10, slope 0.40 (n = 16)
  2018->2022: DPP 催票率: r = 0.02, slope 0.02 (n = 18); KMT 催票率: r = 0.21, slope 0.57 (n = 19); DPP share: r = -0.27, slope -0.71 (n = 18)
  2022->2026: DPP 催票率: r = 0.61, slope 1.19 (n = 18); KMT 催票率: r = -0.41, slope -1.36 (n = 17); DPP share: r = 0.44, slope 1.23 (n = 18)

2022->2026 by county (turnout change; DPP and KMT 催票率 change; 2022 turnout):
  新北市   +7.7   DPP  +9.8   KMT  -2.1   (2022: 56.6)
  花蓮縣   +6.7   DPP  +nan   KMT -12.5   (2022: 57.6)
  高雄市   +5.7   DPP  +0.0   KMT  +5.9   (2022: 58.6)
  新竹縣   +5.7   DPP +17.9   KMT -10.6   (2022: 59.0)
  臺南市   +5.5   DPP  +5.2   KMT  +3.3   (2022: 58.7)
  臺中市   +5.0   DPP  +9.6   KMT  -3.9   (2022: 60.0)
  臺北市   +4.4   DPP +11.3   KMT +10.1   (2022: 67.7)
  基隆市   +3.2   DPP  +6.7   KMT  +0.7   (2022: 60.2)
  宜蘭縣   +1.4   DPP  +8.8   KMT  -3.3   (2022: 64.3)
  彰化縣   +1.0   DPP  +3.2   KMT  -9.7   (2022: 64.9)
  桃園市   +1.0   DPP  +3.0   KMT  +2.8   (2022: 59.5)
  臺東縣   +0.3   DPP  +0.0   KMT  +0.4   (2022: 64.8)
  屏東縣   +0.3   DPP  +8.4   KMT  -5.0   (2022: 67.2)
  南投縣   +0.1   DPP  -3.6   KMT  +4.5   (2022: 69.1)
  雲林縣   -0.0   DPP  +5.0   KMT  -4.8   (2022: 67.3)
  新竹市   -0.4   DPP  +2.4   KMT  +nan   (2022: 62.9)
  嘉義縣   -0.7   DPP  -4.6   KMT  +nan   (2022: 67.3)
  澎湖縣   -1.4   DPP  -3.2   KMT  +4.7   (2022: 58.5)
  苗栗縣   -2.2   DPP  +3.5   KMT +32.4   (2022: 67.2)

Rebound check: r(turnout change 2018-22, change 2022-26) = -0.50 (n = 19); r(2022 turnout, change 2022-26) = -0.66
Net change 2018->2026: 臺北市 +6.2, 基隆市 +0.9, 新北市 +0.3, 臺南市 +0.2, 桃園市 -0.2, 花蓮縣 -0.6, 臺中市 -2.4, 新竹市 -2.9, 新竹縣 -3.3, 臺東縣 -3.3, 宜蘭縣 -3.4, 南投縣 -3.6, 屏東縣 -3.6, 嘉義縣 -4.2, 雲林縣 -4.3, 彰化縣 -5.0, 苗栗縣 -5.7, 澎湖縣 -5.8, 高雄市 -9.2

# 3. Villages, 2022 -> 2026: within districts, where turnout rose more, whose 催票率 rose more?
OLS of the change in each camp's mayoral 催票率 on the change in turnout, district fixed effects,
control: 2022 third-candidate 催票率 (its votes had to go somewhere); villages weighted equally; HC1 standard errors.
  Taipei          n= 456  turnout 67.7->72.1  (village sd of change 2.3); per point of turnout: G +0.47 (0.03), B +0.50 (0.03), G-B margin -0.03 (0.06); 2022 third 催票率 16.9; rebound r(change 18-22, change 22-26) = -0.25
  New Taipei      n=1032  turnout 56.6->64.4  (village sd of change 5.1); per point of turnout: G +0.37 (0.02), B +0.59 (0.02), G-B margin -0.22 (0.03); 2022 third 催票率 0.0; rebound r(change 18-22, change 22-26) = -0.49
  Taichung        n= 624  turnout 60.0->65.0  (village sd of change 4.3); per point of turnout: G +0.46 (0.02), B +0.51 (0.02), G-B margin -0.05 (0.04); 2022 third 催票率 1.0; rebound r(change 18-22, change 22-26) = -0.48
  Tainan          n= 648  turnout 58.7->64.2  (village sd of change 6.8); per point of turnout: G +0.52 (0.02), B +0.38 (0.02), G-B margin +0.15 (0.03); 2022 third 催票率 2.5; rebound r(change 18-22, change 22-26) = -0.48
  Kaohsiung       n= 879  turnout 58.7->64.5  (village sd of change 5.3); per point of turnout: G +0.57 (0.01), B +0.37 (0.01), G-B margin +0.19 (0.03); 2022 third 催票率 0.6; rebound r(change 18-22, change 22-26) = -0.66
  Taoyuan         n= 516  turnout 59.5->60.5  (village sd of change 4.0); per point of turnout: G +0.46 (0.02), B +0.46 (0.02), G-B margin -0.00 (0.05); 2022 third 催票率 3.0; rebound r(change 18-22, change 22-26) = -0.30
  Hsinchu County  n= 192  turnout 59.0->64.7  (village sd of change 6.2); per point of turnout: G +0.35 (0.04), B +0.57 (0.04), G-B margin -0.22 (0.08); 2022 third 催票率 1.1; rebound r(change 18-22, change 22-26) = -0.49
  Keelung         n= 157  turnout 60.2->63.4  (village sd of change 3.8); per point of turnout: G +0.49 (0.03), B +0.45 (0.04), G-B margin +0.04 (0.07); 2022 third 催票率 0.7; rebound r(change 18-22, change 22-26) = -0.29

# 4. Robustness
  standard-bearer 2026: 新竹市 高虹安 -> KMT 催票率 35.5
  standard-bearer 2026: 嘉義縣 吳品叡 -> KMT 催票率 28.5
  standard-bearer 2026: 花蓮縣 張峻 -> DPP 催票率 23.7
  standard-bearer 2026: 嘉義市 張啓楷 -> KMT 催票率 25.5
  2022->2026 with standard-bearers: d_dpp r = 0.58, slope 1.07 (n = 19)
  2022->2026 with standard-bearers: d_kmt r = -0.46, slope -1.66 (n = 19)
  2014-2018: r(turnout, DPP 催票率) = 0.29, 95% bootstrap [-0.10, 0.76]; municipalities r = 0.10 (n = 5), others r = 0.69 (n = 11)
  2018-2022: r(turnout, DPP 催票率) = 0.02, 95% bootstrap [-0.55, 0.57]; municipalities r = 0.24 (n = 6), others r = -0.36 (n = 12)
  2022-2026: r(turnout, DPP 催票率) = 0.61, 95% bootstrap [0.28, 0.84]; municipalities r = 0.31 (n = 6), others r = 0.77 (n = 12)
  Village slopes weighted by 2026 electors (margin G-B per point of turnout; equal-weight value in brackets):
    Taipei          -0.07 (0.05)  [-0.03]
    New Taipei      -0.15 (0.02)  [-0.22]
    Taichung        -0.03 (0.04)  [-0.05]
    Tainan          +0.12 (0.02)  [+0.15]
    Kaohsiung       +0.21 (0.02)  [+0.19]
    Taoyuan         -0.01 (0.04)  [-0.00]
    Hsinchu County  -0.26 (0.10)  [-0.22]
    Keelung         +0.02 (0.06)  [+0.04]

# 5. Mobilization rates (votes / registered electors, %) by party label, local elections
  Taiwan  1997/98  turnout  68.8 = DPP  30.0 + KMT  29.8 + TPP  0.0 + other   8.1 + invalid  1.0
  Taiwan  2001/02  turnout  67.3 = DPP  29.4 + KMT  26.4 + TPP  0.0 + other  10.5 + invalid  1.0
  Taiwan  2005/06  turnout  66.1 = DPP  27.6 + KMT  33.3 + TPP  0.0 + other   4.2 + invalid  1.0
  Taiwan  2009/10  turnout  68.4 = DPP  32.5 + KMT  30.8 + TPP  0.0 + other   4.1 + invalid  1.0
  Taiwan  2014     turnout  67.6 = DPP  31.5 + KMT  27.0 + TPP  0.0 + other   7.8 + invalid  1.4
  Taiwan  2018     turnout  67.0 = DPP  25.6 + KMT  31.9 + TPP  0.0 + other   7.9 + invalid  1.5
  Taiwan  2022     turnout  61.0 = DPP  24.9 + KMT  30.0 + TPP  0.9 + other   4.1 + invalid  1.1
  Taiwan  2026     turnout  65.0 = DPP  30.8 + KMT  30.1 + TPP  0.3 + other   3.0 + invalid  0.9
  Taipei  1997/98  turnout  80.9 = DPP  36.8 + KMT  41.0 + TPP  0.0 + other   2.4 + invalid  0.7
  Taipei  2001/02  turnout  70.6 = DPP  25.1 + KMT  44.8 + TPP  0.0 + other   0.0 + invalid  0.7
  Taipei  2005/06  turnout  64.5 = DPP  26.2 + KMT  34.5 + TPP  0.0 + other   3.4 + invalid  0.5
  Taipei  2009/10  turnout  70.6 = DPP  30.7 + KMT  39.0 + TPP  0.0 + other   0.4 + invalid  0.6
  Taipei  2014     turnout  70.5 = DPP   0.0 + KMT  28.4 + TPP  0.0 + other  41.2 + invalid  0.9
  Taipei  2018     turnout  65.9 = DPP  11.3 + KMT  26.7 + TPP  0.0 + other  27.4 + invalid  0.6
  Taipei  2022     turnout  67.7 = DPP  21.4 + KMT  28.4 + TPP  0.0 + other  17.3 + invalid  0.6
  Taipei  2026     turnout  72.1 = DPP  32.7 + KMT  38.5 + TPP  0.0 + other   0.4 + invalid  0.5
Changes between local elections (points):
  Taiwan  1997/98->2001/02: turnout  -1.5; DPP  -0.5, KMT  -3.5, TPP +0.0, other  +2.4, invalid +0.0
  Taiwan  2001/02->2005/06: turnout  -1.2; DPP  -1.9, KMT  +7.0, TPP +0.0, other  -6.3, invalid +0.1
  Taiwan  2005/06->2009/10: turnout  +2.3; DPP  +4.9, KMT  -2.5, TPP +0.0, other  -0.1, invalid -0.1
  Taiwan  2009/10->2014: turnout  -0.8; DPP  -1.0, KMT  -3.9, TPP +0.0, other  +3.7, invalid +0.4
  Taiwan  2014->2018: turnout  -0.6; DPP  -5.9, KMT  +5.0, TPP +0.0, other  +0.1, invalid +0.1
  Taiwan  2018->2022: turnout  -6.0; DPP  -0.7, KMT  -1.9, TPP +0.9, other  -3.8, invalid -0.4
  Taiwan  2022->2026: turnout  +4.1; DPP  +5.9, KMT  +0.0, TPP -0.6, other  -1.1, invalid -0.2
  Taipei  1997/98->2001/02: turnout -10.3; DPP -11.7, KMT  +3.8, TPP +0.0, other  -2.4, invalid -0.0
  Taipei  2001/02->2005/06: turnout  -6.1; DPP  +1.1, KMT -10.4, TPP +0.0, other  +3.4, invalid -0.2
  Taipei  2005/06->2009/10: turnout  +6.1; DPP  +4.5, KMT  +4.5, TPP +0.0, other  -3.0, invalid +0.1
  Taipei  2009/10->2014: turnout  -0.2; DPP -30.7, KMT -10.6, TPP +0.0, other +40.8, invalid +0.3
  Taipei  2014->2018: turnout  -4.5; DPP +11.3, KMT  -1.7, TPP +0.0, other -13.8, invalid -0.3
  Taipei  2018->2022: turnout  +1.8; DPP +10.2, KMT  +1.7, TPP +0.0, other -10.1, invalid -0.1
  Taipei  2022->2026: turnout  +4.4; DPP +11.3, KMT +10.1, TPP +0.0, other -16.9, invalid -0.0
  2022->2026 counties where the DPP rate rose: 15 of 18
  2022->2026 counties where the KMT rate rose: 9 of 17
  both parties nominated in both years (16 counties), 2014->2018: turnout -0.1, DPP -9.0, KMT +5.8
  both parties nominated in both years (18 counties), 2018->2022: turnout -5.9, DPP -1.1, KMT -1.2
  both parties nominated in both years (16 counties), 2022->2026: turnout +4.1, DPP +6.5, KMT +1.3

Age and the vote

For Age and the Vote: Taipei, 2026. Runs on the cleaned tables above and the village panels built in the turnout section (village_panel.py for 63000, 65000, 10017 and 68000). age_analysis.py produces every number on the page; the CEC’s turnout by age, which is printed only in figures, is read from cec_turnout_age_2022.csv next to the script. Run from scratch in an empty folder, the cleaning, the village panels and this step reproduce the expected output below byte for byte.

Run

python3 age_analysis.py CLEAN OUT/panel OUT/age SOURCE/fia_income

Outputs

FileContentsArticle section
age/age_report.mdage structure by county; village comparisons of age with each candidate’s share and with turnout, Taipei, New Taipei, Keelung and Taoyuan, 2018–2026, with and without district fixed effects and income; the CEC’s turnout by ageall three questions
age/county_age.csv, age/age_coefs.csv, age/age.jsonthe same figures as tables

Method

Files

age_analysis.py

"""Age and voting in Taipei, New Taipei, Keelung and Taoyuan: village-level checks for the age page.

usage: python3 age_analysis.py CLEAN_DIR PANEL_DIR OUT_DIR INCOME_DIR
INCOME_DIR holds the Fiscal Information Agency's village income-tax tables (data.gov.tw dataset 103066), named
<ROC year>_165-9.csv: 107 (2018 income, matched to the 2018 election), 111 (2022), 112 (2023, latest, matched to 2026).
Reads PANEL_DIR/villages_<county>.csv (village_panel.py) and CLEAN_DIR/demog_age.parquet. Writes OUT_DIR/age_report.md
and OUT_DIR/age_coefs.csv. Every number is a village comparison (ecological), not a statement about individual voters.

Outcomes are shares of valid votes (mayor: m_*/m_valid; council: c_*/c_valid; president: p_*/p_valid), and turnout
(cast / electors), in percentage points. Age: shares of adults 20+ (the electorate's age floor) aged 20-39 and 65+,
40-64 the base. Models: OLS across villages, without and with district (區) fixed effects; coefficients are points of
outcome per +10 points of age share; HC1 standard errors (12-29 districts, so district-clustered errors are not used).
"""
import sys, os, json
import numpy as np
import pandas as pd

CLEAN, PANEL, OUT, INC = sys.argv[1:5]
INCOME_FILE = {2018: '107', 2022: '111', 2026: '112'}
os.makedirs(OUT, exist_ok=True)
COUNTIES = {'63000': 'Taipei', '65000': 'New Taipei', '10017': 'Keelung', '68000': 'Taoyuan'}
ZH = {'63000': '臺北市', '65000': '新北市', '10017': '基隆市', '68000': '桃園市'}
LOG = []
say = lambda s='': (LOG.append(s), print(s))


def ols(y, X, fe=None):
    """OLS with optional fixed effects (dummies); returns coefficients and HC1 SEs for the columns of X."""
    Z = X.copy()
    if fe is not None:
        Z = pd.concat([Z, pd.get_dummies(fe, drop_first=True, dtype=float)], axis=1)
    Z.insert(0, 'const', 1.0)
    ok = y.notna() & Z.notna().all(axis=1)
    yv, Zv = y[ok].values, Z[ok].values.astype(float)
    b, *_ = np.linalg.lstsq(Zv, yv, rcond=None)
    e = yv - Zv @ b
    n, k = Zv.shape
    inv = np.linalg.pinv(Zv.T @ Zv)
    V = inv @ (Zv.T * e**2) @ Zv @ inv * n / (n - k)
    se = np.sqrt(np.diag(V))
    cols = list(Z.columns)
    return {c: (b[cols.index(c)], se[cols.index(c)]) for c in X.columns}, ok.sum()


src = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'areas.py'), encoding='utf-8').read()
import re
RARE = eval(re.search(r'RARE = (\{.*?\})', src, re.S).group(1))


def norm(s):
    s = str(s).replace('台', '臺').strip()
    for k, v in RARE.items():
        s = s.replace(k, v)
    return s


def income(cname_zh, yr):
    """Median and mean income per tax unit (thousand NT$) by village; rows '合計' and '其他' dropped."""
    d = pd.read_csv(f'{INC}/{INCOME_FILE[yr]}_165-9.csv', encoding='utf-8-sig', dtype=str)
    d.columns = ['county_town', 'village', 'units', 'total', 'mean', 'median', 'q1', 'q3', 'sd', 'cv']
    d = d[d.county_town.map(norm).str.startswith(cname_zh) & ~d.village.isin(['合計', '其他'])]
    return pd.DataFrame({'town_name': d.county_town.map(norm).str[3:], 'village_name': d.village.map(norm),
                         'inc_med': d['median'].astype(float), 'inc_mean': d['mean'].astype(float),
                         'units': d.units.astype(float)}).groupby(['town_name', 'village_name'], as_index=False).first()


def ols_w(y, X, fe, w):
    """Weighted least squares with fixed effects (point estimates only)."""
    Z = pd.concat([X, pd.get_dummies(fe, drop_first=True, dtype=float)], axis=1)
    Z.insert(0, 'const', 1.0)
    ok = y.notna() & Z.notna().all(axis=1) & w.notna()
    sw = np.sqrt(w[ok].values)
    b, *_ = np.linalg.lstsq(Z[ok].values.astype(float) * sw[:, None], y[ok].values * sw, rcond=None)
    return {c: b[list(Z.columns).index(c)] for c in X.columns}


def demean(s, g):
    return s - s.groupby(g).transform('mean')


# ---------------------------------------------------------------- 1. age structure, all 22 counties
D = pd.read_parquet(f'{CLEAN}/demog_age.parquet')
say('# Age and voting: village checks\n')
say('## 1. Share of adults 20+ aged 65+ and 20-39, October 2018 / 2022 / 2026 (MOI household registration)')
rows = []
for mo, yr in [(10710, 2018), (11110, 2022), (11510, 2026)]:
    d = D[(D.month == mo) & (D.age >= 20)]
    for (cty, name), g in d.groupby(['county', d.county_town.str[:3]]):
        rows.append(dict(year=yr, county=cty, name=name, p20=g.population.sum(),
                         s65=g[g.age >= 65].population.sum(), s2039=g[g.age <= 39].population.sum()))
    rows.append(dict(year=yr, county='all', name='Taiwan', p20=d.population.sum(),
                     s65=d[d.age >= 65].population.sum(), s2039=d[d.age <= 39].population.sum()))
C = pd.DataFrame(rows)
C = C.groupby(['year', 'county'], as_index=False).agg(name=('name', 'first'), p20=('p20', 'sum'), s65=('s65', 'sum'), s2039=('s2039', 'sum'))
C['pct65'] = 100 * C.s65 / C.p20
C['pct2039'] = 100 * C.s2039 / C.p20
W = C[C.county != 'all'].pivot(index=['county', 'name'], columns='year', values=['pct65', 'pct2039'])
W['rank65_2026'] = W[('pct65', 2026)].rank(ascending=False).astype(int)
W = pd.concat([W, C[C.county == 'all'].pivot(index=['county', 'name'], columns='year', values=['pct65', 'pct2039'])])
W = W.sort_values(('pct65', 2026), ascending=False).round(1)
# 2026 executive race by ballot label (DPP / KMT nominee share of valid votes), across counties
E = pd.read_parquet(f'{CLEAN}/elections/source=cec2026'); E = E[E.office == 'executive']
K = pd.read_parquet(f'{CLEAN}/candidates'); K = K[K.eid.isin(E.eid)].merge(E[['eid', 'county']], on='eid')
K['county'] = K.county.str[:5]
T = K.groupby('county').total.sum().to_frame('valid')
for lab, party in [('dpp', '民主進步黨'), ('kmt', '中國國民黨')]:
    T[f'{lab}_pct'] = 100 * K[K.party_std == party].groupby('county').total.sum() / T.valid
for lab in ('dpp_pct', 'kmt_pct'):
    W[lab] = [round(T[lab].get(c, np.nan), 1) for c in W.index.get_level_values('county')]
say(W.to_string())
A26 = C[(C.year == 2026) & (C.county != 'all')].set_index('county').join(T)
for lab in ('dpp_pct', 'kmt_pct'):
    ok = A26[lab].notna()
    say(f'across counties with a {lab[:3].upper()} nominee (n={ok.sum()}): r(65+ share, {lab}) {np.corrcoef(A26.pct65[ok], A26[lab][ok])[0, 1]:+.2f}, '
        f'r(20-39 share, {lab}) {np.corrcoef(A26.pct2039[ok], A26[lab][ok])[0, 1]:+.2f}')
C.to_csv(f'{OUT}/county_age.csv', index=False)

# ---------------------------------------------------------------- 2. village models
coefs = []
for cty, cname in COUNTIES.items():
    P = pd.read_csv(f'{PANEL}/villages_{cty}.csv')
    say(f'\n## 2. {cname} ({cty})')
    for yr in (2018, 2022, 2026):
        v = P[P.year == yr].copy()
        v['s2039'] = v.a20_29 + v.a30_39
        v['s65'] = v.a65p
        say(f'\n### {yr}: {len(v)} villages; adults 20+ {v.pop20p.sum():,.0f}; village 65+ share mean {100*v.s65.mean():.1f}, sd {100*v.s65.std():.1f} '
            f'(within district sd {100*demean(v.s65, v.town_name).std():.1f}); 20-39 mean {100*v.s2039.mean():.1f}, sd {100*v.s2039.std():.1f} '
            f'(within {100*demean(v.s2039, v.town_name).std():.1f}); electors/adults20+ {v.m_electors.sum()/v.pop20p.sum():.3f}')
        out = {'turnout_m': 100 * v.m_cast / v.m_electors}
        for c in ['m_B', 'm_G', 'm_third']:
            if c in v and v[c].notna().any() and v[c].sum() > 0:
                out[c] = 100 * v[c].fillna(0) / v.m_valid
        for c in ['c_B', 'c_G', 'c_TPP', 'c_U']:
            if c in v and v[c].notna().any() and v[c].sum() > 0:
                out[c] = 100 * v[c].fillna(0) / v.c_valid
        pres = {2018: 2020, 2022: 2024}.get(yr)          # presidential results matched to the nearest age snapshot
        if pres:
            p = P[P.year == pres].set_index(['town_name', 'village_name'])
            vv = v.set_index(['town_name', 'village_name'])
            for c in ['p_KMT', 'p_DPP', 'p_TPP']:
                if c in p and p[c].sum() > 0:
                    out[f'{c}{pres}'] = (100 * p[c] / p.p_valid).reindex(vv.index).values
            out[f'turnout_p{pres}'] = (100 * p.p_cast / p.p_electors).reindex(vv.index).values
        X = v[['s2039', 's65']] * 100 / 10
        inc = income(ZH[cty], yr)
        v = v.merge(inc, on=['town_name', 'village_name'], how='left')
        v.index = X.index
        v['log_inc'] = np.log(v.inc_med)
        say(f'income ({INCOME_FILE[yr]}): matched {v.inc_med.notna().sum()} of {len(v)} villages; '
            f'r(log median income, 65+) {v.log_inc.corr(v.s65):+.2f}, within {demean(v.log_inc, v.town_name).corr(demean(v.s65, v.town_name)):+.2f}; '
            f'r(log median income, 20-39) {v.log_inc.corr(v.s2039):+.2f}, within {demean(v.log_inc, v.town_name).corr(demean(v.s2039, v.town_name)):+.2f}')                     # +1 in X = +10 points of age share
        say(f'{"outcome":<14} {"mean":>6} | {"r(65+)":>7} {"r(20-39)":>8} | {"r_within(65+)":>13} {"r_within(20-39)":>15} | '
            f'{"b20-39":>7} {"b65+":>7} (no FE) | {"b20-39":>7} {"(se)":>6} {"b65+":>7} {"(se)":>6} (district FE)')
        for name, y in out.items():
            y = pd.Series(np.asarray(y, dtype=float), index=v.index)
            ok = y.notna()
            r65 = np.corrcoef(y[ok], v.s65[ok])[0, 1]
            r2039 = np.corrcoef(y[ok], v.s2039[ok])[0, 1]
            yw, a65, a2039 = demean(y[ok], v.town_name[ok]), demean(v.s65[ok], v.town_name[ok]), demean(v.s2039[ok], v.town_name[ok])
            rw65, rw2039 = np.corrcoef(yw, a65)[0, 1], np.corrcoef(yw, a2039)[0, 1]
            b0, _ = ols(y, X)
            b1, n = ols(y, X, v.town_name)
            b2, n2 = ols(y, X.assign(log_inc=v.log_inc), v.town_name)
            b3 = ols_w(y, X, v.town_name, v.m_electors)
            one = {}
            for m in ('s65', 's2039'):
                o1, _ = ols(y, X[[m]], v.town_name)
                o2, _ = ols(y, X[[m]].assign(log_inc=v.log_inc), v.town_name)
                o3 = ols_w(y, X[[m]], v.town_name, v.m_electors)
                o0, _ = ols(y, X[[m]])                                  # citywide, no district comparison
                one.update({f'{m}_pool': o0[m][0], f'{m}_pool_se': o0[m][1]})
                one.update({f'{m}_only': o1[m][0], f'{m}_only_se': o1[m][1], f'{m}_only_inc': o2[m][0],
                            f'{m}_only_inc_se': o2[m][1], f'{m}_only_w': o3[m]})
            say(f'{name:<14} {y.mean():6.1f} | {r65:+7.2f} {r2039:+8.2f} | {rw65:+13.2f} {rw2039:+15.2f} | '
                f'{b0["s2039"][0]:+7.1f} {b0["s65"][0]:+7.1f}        | {b1["s2039"][0]:+7.1f} {b1["s2039"][1]:6.1f} {b1["s65"][0]:+7.1f} {b1["s65"][1]:6.1f}')
            coefs.append(dict(county=cname, year=yr, outcome=name, mean=y.mean(), n=n, r65=r65, r2039=r2039, rw65=rw65, rw2039=rw2039,
                              b2039=b0['s2039'][0], b65=b0['s65'][0], b2039_fe=b1['s2039'][0], se2039_fe=b1['s2039'][1],
                              b65_fe=b1['s65'][0], se65_fe=b1['s65'][1],
                              b2039_inc=b2['s2039'][0], se2039_inc=b2['s2039'][1], b65_inc=b2['s65'][0], se65_inc=b2['s65'][1],
                              binc=b2['log_inc'][0] * np.log(2), seinc=b2['log_inc'][1] * np.log(2), n_inc=n2,
                              b2039_w=b3['s2039'], b65_w=b3['s65'], **one))
        if cty == '63000' and yr == 2026:
            SCAT = [[round(100 * a, 2), round(100 * b, 2), t] for a, b, t in zip(v.s65, v.m_B / v.m_valid, v.town_name)]
            SD65 = dict(sd=100 * v.s65.std(), sd_within=100 * demean(v.s65, v.town_name).std(),
                        lo=100 * v.s65.min(), hi=100 * v.s65.max(),
                        turnout=100 * v.m_cast.sum() / v.m_electors.sum())
# ---------------------------------------------------------------- 2b. robustness: income control and elector weights
say('\n## 2b. Within-district age coefficients (points per +10 points of age share): district FE | + log median income | FE, weighted by electors')
say('   income coefficient = points per doubling of village median income per tax unit')
K = pd.DataFrame(coefs)
for (cn, yr), g in K.groupby(['county', 'year'], sort=False):
    say(f'\n{cn} {yr}')
    for r in g.itertuples():
        say(f'  {r.outcome:<14} 20-39 {r.b2039_fe:+6.1f} ({r.se2039_fe:.1f}) | {r.b2039_inc:+6.1f} ({r.se2039_inc:.1f}) | {r.b2039_w:+6.1f}   '
            f'65+ {r.b65_fe:+6.1f} ({r.se65_fe:.1f}) | {r.b65_inc:+6.1f} ({r.se65_inc:.1f}) | {r.b65_w:+6.1f}   income {r.binc:+5.1f} ({r.seinc:.1f}) n={r.n_inc}')

CHG = []
# ---------------------------------------------------------------- 3. changes 2022 -> 2026 and mayor-council gaps, 2026 age shares
say('\n## 3. 2022->2026 changes and 2026 mayor-council gaps against 2026 age shares (r across villages / within districts)')
for cty, cname in COUNTIES.items():
    P = pd.read_csv(f'{PANEL}/villages_{cty}.csv')
    a = P[P.year == 2026].set_index(['town_name', 'village_name']); b = P[P.year == 2022].set_index(['town_name', 'village_name']).reindex(a.index)
    s65, s2039 = a.a65p, a.a20_29 + a.a30_39
    dm = lambda s: s - s.groupby(level=0).transform('mean')
    d = {'turnout change': 100 * (a.m_cast / a.m_electors - b.m_cast / b.m_electors),
         'KMT mayoral share change': 100 * (a.m_B / a.m_valid - b.m_B / b.m_valid),
         'KMT mayor - KMT council': 100 * (a.m_B / a.m_valid - a.c_B / a.c_valid),
         'KMT mayor - (KMT+TPP council)': 100 * (a.m_B / a.m_valid - (a.c_B + a.c_TPP.fillna(0)) / a.c_valid),
         'DPP mayor - DPP council': 100 * (a.m_G / a.m_valid - a.c_G / a.c_valid)}
    say(f'\n{cname}')
    for k, y in d.items():
        okk = y.notna()
        CHG.append(dict(county=cname, measure=k, mean=y.mean(), r65=np.corrcoef(y[okk], s65[okk])[0, 1], r2039=np.corrcoef(y[okk], s2039[okk])[0, 1],
                        rw65=np.corrcoef(dm(y[okk]), dm(s65[okk]))[0, 1], rw2039=np.corrcoef(dm(y[okk]), dm(s2039[okk]))[0, 1]))
        ok = y.notna()
        say(f'  {k:<30} mean {y.mean():+6.1f} | r65 {np.corrcoef(y[ok], s65[ok])[0, 1]:+.2f} r20-39 {np.corrcoef(y[ok], s2039[ok])[0, 1]:+.2f} | '
            f'within r65 {np.corrcoef(dm(y[ok]), dm(s65[ok]))[0, 1]:+.2f} r20-39 {np.corrcoef(dm(y[ok]), dm(s2039[ok]))[0, 1]:+.2f}')

# ---------------------------------------------------------------- 4. age-group vote estimates (bounded ecological regression): tried, not used
# Electorate model: each village's electors split into KMT, DPP, other and not voting, regressed on adult age shares
# (20-39, 40-64, 65+) within districts (ecoreg.within; bounded, bootstrap intervals). Reported to show why the page does
# not use them: the 2022 estimates contradict the CEC's sampled turnout by age.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import ecoreg
say('\n## 4. Bounded ecological estimates by age group (share of electors), within districts; 95% bootstrap intervals')
EI = []
for cty, cname in COUNTIES.items():
    P = pd.read_csv(f'{PANEL}/villages_{cty}.csv')
    for yr in (2022, 2026):
        v = P[P.year == yr].copy()
        v['g1'], v['g2'], v['g3'], v['one'] = v.a20_29 + v.a30_39, v.a40_64, v.a65p, 1.0
        v['oth'] = v.m_valid - v.m_B.fillna(0) - v.m_G.fillna(0); v['nv'] = v.m_electors - v.m_valid
        v['m_B'], v['m_G'] = v.m_B.fillna(0), v.m_G.fillna(0)
        v = v.dropna(subset=['g1'])
        r = ecoreg.within(v, ['g1', 'g2', 'g3'], ['m_B', 'm_G', 'oth', 'nv'], 'one', 'm_electors', dist='town_name')
        for gi, gn in enumerate(['20-39', '40-64', '65+']):
            e, lo, hi = 100 * r['est'][gi], 100 * r['lo'][gi], 100 * r['hi'][gi]
            EI.append(dict(county=cname, year=yr, group=gn, kmt=e[0], kmt_lo=lo[0], kmt_hi=hi[0], dpp=e[1], dpp_lo=lo[1], dpp_hi=hi[1],
                           turnout=100 - e[3], turnout_lo=100 - hi[3], turnout_hi=100 - lo[3]))
            say(f'  {cname:<10} {yr} {gn:<6} KMT {e[0]:4.0f} [{lo[0]:3.0f},{hi[0]:3.0f}]  DPP {e[1]:4.0f} [{lo[1]:3.0f},{hi[1]:3.0f}]  '
                f'turnout {100 - e[3]:4.0f} [{100 - hi[3]:3.0f},{100 - lo[3]:3.0f}]')

pd.DataFrame(coefs).to_csv(f'{OUT}/age_coefs.csv', index=False)
TA = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cec_turnout_age_2022.csv'), comment='#')
json.dump(dict(county=C.to_dict('records'), exec2026=T.reset_index().to_dict('records'),
               r_county={lab: float(np.corrcoef(A26.pct65[A26[lab].notna()], A26[lab][A26[lab].notna()])[0, 1]) for lab in ('dpp_pct', 'kmt_pct')},
               coefs=coefs, scatter=SCAT, sd65=SD65, change=CHG, ei=EI, cec_turnout=TA.to_dict('records')),
          open(f'{OUT}/age.json', 'w'), ensure_ascii=False, default=float, indent=0)
open(f'{OUT}/age_report.md', 'w', encoding='utf-8').write('\n'.join(LOG) + '\n')

cec_turnout_age_2022.csv

read by age_analysis.py
# CEC turnout by age and sex, 2022 mayoral and magistrate elections, read from the bar labels of the figures (printed page numbers) in the Central Election Commission's 111年地方公職人員選舉及憲法修正案公民複決投票統計分析 期末報告 (published 2024-12-24); M = 男性, F = 女性; checked against the rendered figures; rows with sex and age "all" are the official turnout from table 4-9 (p. 86)
county,sex,age,turnout,figure,page
Taiwan,M,20-35,44.9,4-13,111
Taiwan,F,20-35,47.8,4-13,111
Taiwan,M,36-50,56.7,4-13,111
Taiwan,F,36-50,58.7,4-13,111
Taiwan,M,51-65,69.5,4-13,111
Taiwan,F,51-65,71.2,4-13,111
Taiwan,M,66+,74.4,4-13,111
Taiwan,F,66+,70.4,4-13,111
Taipei,M,20-35,54.6,4-14,112
Taipei,F,20-35,60.5,4-14,112
Taipei,M,36-50,64.8,4-14,112
Taipei,F,36-50,67.8,4-14,112
Taipei,M,51-65,75.5,4-14,112
Taipei,F,51-65,75.2,4-14,112
Taipei,M,66+,74.6,4-14,112
Taipei,F,66+,72.2,4-14,112
New Taipei,M,20-35,39.2,4-15,113
New Taipei,F,20-35,45.4,4-15,113
New Taipei,M,36-50,52.3,4-15,113
New Taipei,F,36-50,54.1,4-15,113
New Taipei,M,51-65,62.7,4-15,113
New Taipei,F,51-65,65.9,4-15,113
New Taipei,M,66+,69.3,4-15,113
New Taipei,F,66+,65.9,4-15,113
Taoyuan,M,20-35,44.8,4-16,113
Taoyuan,F,20-35,44.7,4-16,113
Taoyuan,M,36-50,54.1,4-16,113
Taoyuan,F,36-50,61.4,4-16,113
Taoyuan,M,51-65,70.8,4-16,113
Taoyuan,F,51-65,67.8,4-16,113
Taoyuan,M,66+,76.4,4-16,113
Taoyuan,F,66+,69.0,4-16,113
Keelung,M,20-35,41.0,4-33,125
Keelung,F,20-35,45.8,4-33,125
Keelung,M,36-50,47.9,4-33,125
Keelung,F,36-50,56.5,4-33,125
Keelung,M,51-65,66.1,4-33,125
Keelung,F,51-65,69.4,4-33,125
Keelung,M,66+,73.1,4-33,125
Keelung,F,66+,71.6,4-33,125
Taiwan,all,all,60.97,table 4-9,86
Taipei,all,all,67.70,table 4-9,86

expected output: OUT/age/age_report.md

# Age and voting: village checks

## 1. Share of adults 20+ aged 65+ and 20-39, October 2018 / 2022 / 2026 (MOI household registration)
              pct65             pct2039             rank65_2026 dpp_pct kmt_pct
year           2018  2022  2026    2018  2022  2026                            
county name                                                                    
63000  臺北市     20.9  24.8  29.5    32.8  28.5  25.3         1.0    45.7    53.7
10010  嘉義縣     22.3  24.8  28.2    32.1  29.8  27.6         2.0    55.9     NaN
10008  南投縣     20.4  23.5  27.3    34.0  31.1  28.5         3.0    37.5    62.5
10017  基隆市     18.5  22.3  26.6    33.2  30.4  27.9         4.0    47.6    51.3
10009  雲林縣     21.7  23.7  26.1    33.3  30.6  28.6         5.0    49.2    49.2
10015  花蓮縣     19.2  22.5  26.1    34.0  31.2  28.8         6.0     NaN    37.7
10013  屏東縣     19.5  22.6  26.1    34.0  31.1  28.6         7.0    61.5    38.5
10014  臺東縣     19.4  22.1  25.3    33.3  30.9  29.1         8.0    36.4    61.4
10016  澎湖縣     19.0  21.3  25.2    36.9  34.6  31.1         9.0    31.3    42.2
10002  宜蘭縣     19.2  22.0  25.2    34.8  32.0  29.6        10.0    53.7    44.3
64000  高雄市     18.0  21.6  25.2    34.6  31.1  28.3        11.0    52.9    45.8
67000  臺南市     18.1  21.3  25.0    35.2  31.4  28.3        12.0    52.5    44.7
10007  彰化縣     18.8  21.5  24.9    37.1  33.6  30.2        13.0    46.2    40.8
10005  苗栗縣     19.4  21.8  24.7    35.7  32.4  29.9        14.0    37.8    62.2
10020  嘉義市     18.4  21.4  24.6    35.2  32.3  30.0        15.0    53.3     NaN
all    Taiwan  17.7  20.9  24.6    35.6  32.1  29.2         NaN     NaN     NaN
65000  新北市     16.2  20.1  24.3    35.6  31.8  28.5        16.0    48.2    51.2
09020  金門縣     14.8  18.5  23.1    36.7  35.0  31.4        17.0     NaN    63.5
66000  臺中市     15.1  18.3  21.8    38.5  34.8  31.7        18.0    50.7    48.4
68000  桃園市     14.3  17.5  21.1    39.3  35.4  32.1        19.0    44.3    55.7
10018  新竹市     15.5  17.9  20.9    37.4  33.5  30.6        20.0    39.7     NaN
09007  連江縣     13.4  16.1  20.6    37.6  37.5  34.8        21.0     NaN    58.3
10004  新竹縣     15.8  17.2  19.3    37.6  34.7  32.6        22.0    57.4    40.4
across counties with a DPP nominee (n=19): r(65+ share, dpp_pct) -0.03, r(20-39 share, dpp_pct) -0.11
across counties with a KMT nominee (n=19): r(65+ share, kmt_pct) -0.02, r(20-39 share, kmt_pct) +0.09

## 2. Taipei (63000)

### 2018: 456 villages; adults 20+ 2,179,572; village 65+ share mean 21.2, sd 3.4 (within district sd 2.4); 20-39 mean 32.6, sd 3.0 (within 2.2); electors/adults20+ 0.993
income (107): matched 453 of 456 villages; r(log median income, 65+) +0.04, within -0.07; r(log median income, 20-39) -0.34, within -0.27
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        66.2 |   -0.09    +0.24 |         -0.02           +0.20 |    +5.4    +2.9        |    +5.2    1.4    +3.0    0.9
m_B              40.6 |   +0.22    -0.41 |         +0.31           -0.47 |   -15.1    -6.3        |   -11.5    1.5    -0.4    1.2
m_G              17.6 |   +0.08    +0.15 |         -0.00           +0.23 |    +9.8    +8.2        |    +6.8    0.9    +4.4    0.8
m_third          40.9 |   -0.55    +0.60 |         -0.57           +0.58 |    +5.3    -1.9        |    +4.7    0.8    -4.0    0.6
c_B              49.5 |   +0.01    -0.21 |         +0.18           -0.36 |   -22.4   -15.8        |   -13.4    2.0    -3.4    1.6
c_G              37.2 |   -0.17    +0.34 |         -0.14           +0.35 |   +14.4    +6.6        |   +12.4    1.7    +4.6    1.4
c_U              13.4 |   +0.11    -0.01 |         -0.14           +0.13 |    +8.0    +9.2        |    +1.0    0.9    -1.2    0.6
p_KMT2020        41.8 |   +0.21    -0.41 |         +0.28           -0.45 |   -16.0    -7.0        |   -12.0    1.5    -1.4    1.3
p_DPP2020        53.9 |   -0.19    +0.39 |         -0.26           +0.44 |   +16.1    +7.6        |   +12.1    1.5    +1.8    1.3
turnout_p2020    76.2 |   -0.28    +0.39 |         -0.17           +0.36 |    +4.4    +0.9        |    +5.5    1.3    +1.6    0.8

### 2022: 456 villages; adults 20+ 2,053,719; village 65+ share mean 25.1, sd 3.3 (within district sd 2.6); 20-39 mean 28.4, sd 2.4 (within 1.7); electors/adults20+ 0.987
income (111): matched 456 of 456 villages; r(log median income, 65+) +0.05, within -0.05; r(log median income, 20-39) -0.31, within -0.24
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        67.8 |   -0.01    +0.16 |         -0.00           +0.22 |    +4.5    +2.2        |    +5.8    1.7    +2.2    0.7
m_B              42.2 |   +0.22    -0.33 |         +0.27           -0.34 |    -9.8    -1.0        |    -7.8    1.8    +2.3    1.0
m_G              32.3 |   +0.14    +0.02 |         -0.00           +0.14 |    +6.3    +5.7        |    +5.5    1.6    +2.1    0.9
m_third          24.9 |   -0.76    +0.68 |         -0.70           +0.53 |    +3.2    -4.8        |    +2.0    0.5    -4.5    0.3
c_B              42.6 |   -0.07    -0.03 |         +0.21           -0.29 |    -8.2    -6.5        |    -9.1    2.3    +1.5    1.2
c_G              36.4 |   +0.05    +0.04 |         -0.09           +0.24 |    +5.3    +3.8        |    +8.4    2.0    +1.3    1.1
c_TPP             9.1 |   -0.30    +0.36 |         -0.21           +0.11 |    +5.2    -0.9        |    -0.1    0.5    -1.3    0.3
c_U              12.0 |   +0.21    -0.18 |         -0.14           +0.11 |    -2.2    +3.6        |    +0.8    1.2    -1.5    0.6
p_KMT2024        37.9 |   +0.22    -0.32 |         +0.32           -0.39 |    -9.2    -0.8        |    -8.3    1.6    +2.7    0.9
p_DPP2024        38.5 |   +0.10    +0.04 |         -0.04           +0.16 |    +6.0    +4.8        |    +5.3    1.7    +1.4    0.9
p_TPP2024        23.6 |   -0.77    +0.71 |         -0.72           +0.59 |    +3.2    -4.0        |    +2.9    0.5    -4.1    0.3
turnout_p2024    74.2 |   -0.25    +0.35 |         -0.15           +0.30 |    +4.5    +0.2        |    +5.3    1.5    +0.4    0.6

### 2026: 456 villages; adults 20+ 2,041,978; village 65+ share mean 29.8, sd 3.4 (within district sd 2.8); 20-39 mean 25.1, sd 2.0 (within 1.5); electors/adults20+ 0.995
income (112): matched 456 of 456 villages; r(log median income, 65+) +0.05, within -0.06; r(log median income, 20-39) -0.30, within -0.20
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        72.1 |   -0.28    +0.36 |         -0.19           +0.28 |    +5.2    -0.5        |    +5.4    1.7    -0.3    0.6
m_B              53.4 |   +0.05    -0.03 |         +0.20           -0.14 |    +0.3    +1.0        |    -1.2    1.9    +2.9    1.0
m_G              46.0 |   -0.05    +0.03 |         -0.20           +0.14 |    -0.3    -1.0        |    +1.1    1.9    -2.9    1.0
c_B              41.7 |   +0.16    -0.15 |         +0.34           -0.25 |    -2.7    +2.7        |    -2.9    2.0    +5.5    1.1
c_G              44.1 |   -0.15    +0.14 |         -0.21           +0.16 |    +1.5    -1.8        |    +1.7    2.0    -3.2    1.1
c_TPP             9.1 |   -0.34    +0.31 |         -0.22           +0.13 |    +1.5    -1.7        |    +0.0    0.5    -1.0    0.3
c_U               5.0 |   +0.05    -0.04 |         -0.18           +0.15 |    -0.3    +0.7        |    +1.2    0.8    -1.3    0.5

## 2. New Taipei (65000)

### 2018: 1032 villages; adults 20+ 3,285,108; village 65+ share mean 18.1, sd 5.0 (within district sd 3.5); 20-39 mean 34.1, sd 5.1 (within 3.2); electors/adults20+ 0.994
income (107): matched 1028 of 1032 villages; r(log median income, 65+) -0.22, within -0.21; r(log median income, 20-39) +0.05, within -0.11
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        65.7 |   +0.38    -0.26 |         +0.28           -0.13 |    +3.0    +6.9        |    +2.6    1.2    +5.8    0.9
m_B              56.1 |   +0.10    -0.24 |         -0.13           -0.06 |    -9.3    -6.4        |    -6.0    0.9    -6.2    0.9
m_G              43.9 |   -0.10    +0.24 |         +0.13           +0.06 |    +9.3    +6.4        |    +6.0    0.9    +6.2    0.9
c_B              44.8 |   -0.02    -0.06 |         +0.01           -0.14 |    -6.8    -6.3        |    -6.5    1.1    -4.2    1.0
c_G              40.8 |   +0.26    -0.25 |         -0.08           +0.19 |    -1.9    +4.0        |    +5.6    1.0    +2.4    0.9
c_U              14.4 |   -0.25    +0.33 |         +0.09           -0.04 |    +8.7    +2.3        |    +0.9    0.6    +1.8    0.6
p_KMT2020        38.7 |   +0.32    -0.43 |         +0.11           -0.28 |    -9.5    -3.2        |    -6.9    0.8    -3.0    0.7
p_DPP2020        56.9 |   -0.28    +0.40 |         -0.09           +0.26 |    +9.5    +3.7        |    +7.0    0.8    +3.4    0.8
turnout_p2020    74.8 |   -0.21    +0.31 |         +0.02           +0.10 |    +4.0    +1.8        |    +2.4    1.0    +1.8    0.7

### 2022: 1032 villages; adults 20+ 3,347,090; village 65+ share mean 22.1, sd 5.1 (within district sd 3.6); 20-39 mean 30.4, sd 4.5 (within 2.9); electors/adults20+ 0.991
income (111): matched 1032 of 1032 villages; r(log median income, 65+) -0.20, within -0.21; r(log median income, 20-39) +0.08, within -0.06
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        58.6 |   +0.44    -0.32 |         +0.35           -0.20 |    +3.1    +8.0        |    +2.1    1.4    +6.9    0.9
m_B              61.7 |   +0.07    -0.16 |         -0.24           +0.09 |    -5.8    -3.4        |    -2.8    0.8    -4.8    0.6
m_G              38.3 |   -0.07    +0.16 |         +0.24           -0.09 |    +5.8    +3.4        |    +2.8    0.8    +4.8    0.6
c_B              44.1 |   -0.04    -0.03 |         -0.12           +0.01 |    -6.0    -5.4        |    -3.4    1.0    -3.9    0.8
c_G              42.9 |   +0.22    -0.22 |         +0.06           +0.05 |    -2.6    +3.2        |    +3.8    1.0    +3.2    0.8
c_TPP             4.0 |   -0.14    +0.15 |         -0.15           +0.04 |    +0.9    -0.2        |    -0.8    0.2    -1.2    0.2
c_U               9.0 |   -0.18    +0.25 |         +0.18           -0.11 |    +7.7    +2.4        |    +0.4    0.6    +2.0    0.4
p_KMT2024        35.3 |   +0.37    -0.44 |         +0.12           -0.24 |    -7.1    -0.2        |    -5.1    0.8    -1.5    0.6
p_DPP2024        39.8 |   +0.07    -0.00 |         +0.28           -0.15 |    +3.1    +3.3        |    +1.9    0.8    +4.7    0.6
p_TPP2024        24.9 |   -0.83    +0.84 |         -0.72           +0.70 |    +4.0    -3.1        |    +3.2    0.3    -3.2    0.2
turnout_p2024    72.4 |   -0.17    +0.28 |         +0.02           +0.11 |    +4.9    +2.3        |    +3.1    1.1    +2.0    0.6

### 2026: 1039 villages; adults 20+ 3,448,987; village 65+ share mean 26.5, sd 5.4 (within district sd 4.0); 20-39 mean 27.3, sd 4.0 (within 2.8); electors/adults20+ 0.996
income (112): matched 1032 of 1039 villages; r(log median income, 65+) -0.24, within -0.27; r(log median income, 20-39) +0.11, within +0.05
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        65.0 |   +0.21    -0.08 |         +0.21           -0.07 |    +3.9    +4.3        |    +3.3    1.2    +4.1    0.6
m_B              50.6 |   +0.16    -0.21 |         -0.11           +0.03 |    -4.4    -0.6        |    -2.1    0.9    -2.4    0.6
m_G              48.8 |   -0.17    +0.21 |         +0.10           -0.03 |    +4.3    +0.5        |    +2.0    0.9    +2.3    0.6
c_B              38.9 |   -0.13    +0.15 |         +0.06           -0.12 |    +6.0    +0.2        |    -3.0    0.8    -0.9    0.6
c_G              49.2 |   +0.33    -0.36 |         +0.10           -0.02 |   -10.7    +2.8        |    +2.0    0.8    +2.3    0.6
c_TPP             7.0 |   -0.28    +0.26 |         -0.39           +0.30 |    +1.0    -3.0        |    +0.2    0.3    -1.2    0.2
c_U               5.0 |   -0.18    +0.21 |         -0.11           +0.13 |    +3.8    +0.0        |    +0.8    0.4    -0.1    0.2

## 2. Keelung (10017)

### 2018: 157 villages; adults 20+ 311,004; village 65+ share mean 21.2, sd 5.0 (within district sd 4.5); 20-39 mean 31.3, sd 3.6 (within 3.2); electors/adults20+ 0.995
income (107): matched 157 of 157 villages; r(log median income, 65+) -0.32, within -0.33; r(log median income, 20-39) +0.24, within +0.23
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        64.6 |   +0.39    -0.37 |         +0.48           -0.44 |    -2.3    +3.5        |    -1.9    3.6    +5.3    2.2
m_B              44.9 |   -0.12    +0.10 |         -0.16           +0.10 |    +0.2    -1.2        |    -2.1    2.2    -3.1    1.7
m_G              55.1 |   +0.12    -0.10 |         +0.16           -0.10 |    -0.2    +1.2        |    +2.1    2.2    +3.1    1.7
c_B              48.2 |   +0.03    +0.03 |         -0.05           +0.04 |    +8.5    +6.0        |    -0.7    3.6    -1.4    2.5
c_G              27.5 |   +0.08    -0.05 |         +0.14           -0.12 |    +2.1    +2.6        |    -0.3    2.7    +1.6    2.0
c_U              24.3 |   -0.07    +0.00 |         -0.06           +0.06 |   -10.5    -8.6        |    +1.0    2.9    -0.3    2.0
p_KMT2020        43.0 |   -0.15    +0.10 |         -0.13           +0.03 |    -1.8    -2.6        |    -4.3    2.1    -4.0    1.5
p_DPP2020        51.9 |   +0.19    -0.14 |         +0.17           -0.07 |    +1.4    +2.8        |    +3.9    2.3    +4.2    1.6
turnout_p2020    73.4 |   +0.12    -0.02 |         +0.19           -0.06 |    +3.5    +3.0        |    +3.6    2.6    +3.5    1.7

### 2022: 157 villages; adults 20+ 310,490; village 65+ share mean 25.2, sd 5.3 (within district sd 4.8); 20-39 mean 28.4, sd 3.5 (within 3.1); electors/adults20+ 0.992
income (111): matched 157 of 157 villages; r(log median income, 65+) -0.17, within -0.22; r(log median income, 20-39) +0.09, within +0.10
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        62.3 |   +0.40    -0.40 |         +0.46           -0.44 |    -3.6    +2.4        |    -3.3    3.2    +3.7    1.7
m_B              51.8 |   -0.16    +0.15 |         -0.21           +0.12 |    +0.9    -1.0        |    -2.7    2.4    -3.6    1.4
m_G              46.6 |   +0.14    -0.14 |         +0.20           -0.11 |    -0.9    +0.9        |    +2.7    2.4    +3.4    1.4
m_third           1.2 |   +0.15    -0.12 |         +0.11           -0.07 |    -0.0    +0.1        |    +0.1    0.2    +0.2    0.1
c_B              50.7 |   +0.21    -0.17 |         -0.02           -0.06 |    +1.0    +4.8        |    -5.0    3.4    -2.9    2.2
c_G              33.5 |   +0.25    -0.22 |         -0.06           +0.16 |    -1.7    +5.1        |    +7.1    3.1    +3.0    2.0
c_TPP             3.2 |   +0.25    -0.26 |         -0.10           +0.10 |    -1.2    +0.5        |    +0.3    0.6    -0.1    0.4
c_U              12.6 |   -0.33    +0.29 |         +0.16           -0.19 |    +1.9   -10.4        |    -2.4    1.7    -0.0    1.1
p_KMT2024        37.9 |   -0.00    -0.01 |         -0.02           -0.08 |    -0.5    -0.3        |    -4.3    2.1    -2.5    1.2
p_DPP2024        37.1 |   +0.44    -0.42 |         +0.46           -0.36 |    -3.1    +3.0        |    +0.8    2.4    +5.5    1.4
p_TPP2024        25.0 |   -0.76    +0.75 |         -0.75           +0.73 |    +3.6    -2.7        |    +3.5    1.1    -3.0    0.7
turnout_p2024    70.5 |   +0.14    -0.01 |         +0.19           -0.05 |    +3.6    +3.0        |    +3.8    2.3    +3.4    1.4

### 2026: 157 villages; adults 20+ 312,067; village 65+ share mean 29.9, sd 5.5 (within district sd 5.1); 20-39 mean 25.9, sd 3.3 (within 3.0); electors/adults20+ 0.996
income (112): matched 157 of 157 villages; r(log median income, 65+) -0.21, within -0.24; r(log median income, 20-39) +0.11, within +0.11
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        64.8 |   +0.31    -0.29 |         +0.34           -0.32 |    -1.4    +2.1        |    -1.6    3.2    +2.4    1.7
m_B              50.0 |   -0.21    +0.19 |         -0.22           +0.12 |    +0.7    -1.5        |    -3.1    2.2    -3.5    1.3
m_G              48.9 |   +0.21    -0.18 |         +0.22           -0.12 |    -0.2    +1.7        |    +3.5    2.2    +3.6    1.2
c_B              38.6 |   +0.06    +0.01 |         +0.18           -0.26 |    +5.5    +3.8        |    -8.2    3.3    -1.8    1.8
c_G              35.5 |   +0.11    +0.02 |         -0.02           +0.17 |    +8.8    +5.9        |   +10.3    2.8    +4.9    1.6
c_TPP             4.7 |   -0.08    +0.22 |         -0.38           +0.34 |    +7.5    +3.1        |    +0.4    0.7    -1.1    0.5
c_U              21.3 |   -0.07    -0.08 |         -0.07           +0.02 |   -21.9   -12.8        |    -2.5    2.7    -2.0    1.4

## 2. Taoyuan (68000)

### 2018: 504 villages; adults 20+ 1,744,712; village 65+ share mean 15.5, sd 4.6 (within district sd 4.2); 20-39 mean 38.6, sd 3.8 (within 3.4); electors/adults20+ 0.993
income (107): matched 504 of 504 villages; r(log median income, 65+) -0.50, within -0.49; r(log median income, 20-39) +0.19, within +0.20
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        62.5 |   +0.49    -0.33 |         +0.50           -0.34 |    +2.9    +9.2        |    +2.0    1.2    +7.5    0.9
m_B              38.8 |   -0.16    +0.03 |         -0.12           -0.08 |    -6.3    -7.4        |   -10.2    1.6    -8.8    1.0
m_G              54.2 |   +0.19    -0.02 |         +0.14           +0.07 |    +8.1    +9.0        |   +10.3    1.6    +9.2    1.0
m_third           4.9 |   -0.04    -0.09 |         -0.06           +0.06 |    -1.5    -1.1        |    +0.1    0.2    -0.1    0.2
c_B              41.9 |   -0.26    +0.10 |         -0.19           +0.00 |   -12.1   -17.3        |    -9.7    1.8   -10.2    1.3
c_G              35.8 |   +0.14    -0.04 |         +0.12           +0.06 |    +4.9    +6.2        |    +9.3    1.8    +8.3    1.2
c_U              22.3 |   +0.19    -0.08 |         +0.10           -0.07 |    +7.2   +11.0        |    +0.4    1.4    +1.9    1.2
p_KMT2020        40.4 |   -0.12    +0.01 |         -0.07           -0.10 |    -5.3    -5.9        |    -8.2    1.5    -6.4    0.9
p_DPP2020        54.9 |   +0.15    -0.04 |         +0.11           +0.07 |    +5.4    +6.6        |    +8.3    1.5    +7.2    0.9
turnout_p2020    74.6 |   +0.23    -0.12 |         +0.21           -0.09 |    +1.4    +2.5        |    +1.6    1.0    +2.4    0.8

### 2022: 516 villages; adults 20+ 1,840,728; village 65+ share mean 18.7, sd 4.8 (within district sd 4.5); 20-39 mean 34.7, sd 3.5 (within 3.3); electors/adults20+ 0.992
income (111): matched 516 of 516 villages; r(log median income, 65+) -0.43, within -0.44; r(log median income, 20-39) +0.19, within +0.26
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        61.0 |   +0.47    -0.31 |         +0.51           -0.37 |    +1.9    +7.0        |    +0.8    1.2    +6.4    0.8
m_B              51.7 |   -0.23    +0.04 |         -0.23           -0.04 |    -8.3    -8.9        |   -11.5    1.5   -10.2    0.9
m_G              40.5 |   +0.28    -0.08 |         +0.28           -0.01 |    +7.1    +8.8        |   +10.0    1.5   +10.0    0.8
m_third           5.0 |   -0.48    +0.46 |         -0.48           +0.50 |    +0.6    -0.6        |    +0.9    0.2    -0.5    0.1
c_B              40.5 |   -0.17    +0.05 |         -0.16           -0.03 |    -7.5    -9.5        |    -8.0    1.6    -7.1    1.0
c_G              39.6 |   +0.13    -0.00 |         +0.19           +0.07 |    +6.7    +6.5        |   +12.0    1.8   +10.1    1.1
c_TPP             3.0 |   -0.16    +0.09 |         -0.27           +0.16 |    -0.8    -1.6        |    -0.6    0.5    -1.5    0.5
c_U              16.9 |   +0.14    -0.09 |         +0.03           -0.10 |    +1.6    +4.6        |    -3.4    1.4    -1.5    0.9
p_KMT2024        34.3 |   -0.02    -0.15 |         +0.02           -0.27 |    -7.5    -4.4        |   -10.1    1.2    -5.5    0.7
p_DPP2024        36.0 |   +0.38    -0.22 |         +0.41           -0.17 |    +3.4    +7.9        |    +6.2    1.3    +9.1    0.7
p_TPP2024        29.7 |   -0.80    +0.79 |         -0.84           +0.81 |    +4.1    -3.5        |    +3.9    0.4    -3.7    0.3
turnout_p2024    72.2 |   +0.13    -0.07 |         +0.13           +0.00 |    +0.9    +1.5        |    +2.3    1.1    +2.2    0.7

### 2026: 529 villages; adults 20+ 1,952,252; village 65+ share mean 22.4, sd 5.3 (within district sd 4.9); 20-39 mean 31.5, sd 3.7 (within 3.5); electors/adults20+ 0.996
income (112): matched 516 of 529 villages; r(log median income, 65+) -0.41, within -0.43; r(log median income, 20-39) +0.13, within +0.25
outcome          mean |  r(65+) r(20-39) | r_within(65+) r_within(20-39) |  b20-39    b65+ (no FE) |  b20-39   (se)    b65+   (se) (district FE)
turnout_m        61.4 |   +0.37    -0.21 |         +0.37           -0.24 |    +3.0    +5.2        |    +2.1    1.1    +4.6    0.8
m_B              55.6 |   -0.19    +0.05 |         -0.19           -0.01 |    -5.3    -5.7        |    -8.0    1.3    -6.8    0.9
m_G              44.4 |   +0.19    -0.05 |         +0.19           +0.01 |    +5.3    +5.7        |    +8.0    1.3    +6.8    0.9
c_B              39.5 |   -0.09    -0.01 |         -0.05           -0.16 |    -8.9    -7.5        |   -10.7    1.5    -6.7    1.0
c_G              37.7 |   -0.01    +0.09 |         +0.01           +0.14 |    +5.3    +2.8        |    +7.3    1.4    +4.2    0.9
c_TPP             2.8 |   -0.13    -0.01 |         -0.39           +0.36 |    -2.8    -2.4        |    +0.3    0.3    -0.6    0.1
c_U              19.9 |   +0.15    -0.05 |         +0.11           -0.02 |    +6.4    +7.2        |    +3.1    1.2    +3.1    0.9

## 2b. Within-district age coefficients (points per +10 points of age share): district FE | + log median income | FE, weighted by electors
   income coefficient = points per doubling of village median income per tax unit

Taipei 2018
  turnout_m      20-39   +5.2 (1.4) |   +6.1 (1.7) |   +5.3   65+   +3.0 (0.9) |   +3.7 (1.1) |   +2.7   income  +1.9 (1.3) n=453
  m_B            20-39  -11.5 (1.5) |   -8.7 (1.7) |  -10.7   65+   -0.4 (1.2) |   +1.8 (1.4) |   +0.5   income  +6.2 (1.7) n=453
  m_G            20-39   +6.8 (0.9) |   +3.1 (1.1) |   +6.5   65+   +4.4 (0.8) |   +1.5 (1.0) |   +3.8   income  -8.1 (1.3) n=453
  m_third        20-39   +4.7 (0.8) |   +5.7 (0.9) |   +4.2   65+   -4.0 (0.6) |   -3.2 (0.7) |   -4.3   income  +2.1 (0.9) n=453
  c_B            20-39  -13.4 (2.0) |   -8.4 (2.2) |  -12.4   65+   -3.4 (1.6) |   +0.5 (1.9) |   -1.7   income +11.1 (2.3) n=453
  c_G            20-39  +12.4 (1.7) |  +10.1 (2.0) |  +11.4   65+   +4.6 (1.4) |   +2.8 (1.7) |   +3.3   income  -5.1 (1.8) n=453
  c_U            20-39   +1.0 (0.9) |   -1.7 (1.0) |   +1.0   65+   -1.2 (0.6) |   -3.3 (0.8) |   -1.7   income  -6.0 (1.2) n=453
  p_KMT2020      20-39  -12.0 (1.5) |   -8.9 (1.7) |  -11.2   65+   -1.4 (1.3) |   +1.0 (1.5) |   -0.2   income  +6.9 (1.6) n=453
  p_DPP2020      20-39  +12.1 (1.5) |   +8.8 (1.8) |  +11.2   65+   +1.8 (1.3) |   -0.7 (1.5) |   +0.7   income  -7.3 (1.7) n=453
  turnout_p2020  20-39   +5.5 (1.3) |   +8.1 (1.5) |   +5.7   65+   +1.6 (0.8) |   +3.6 (0.9) |   +1.7   income  +5.7 (1.0) n=453

Taipei 2022
  turnout_m      20-39   +5.8 (1.7) |   +7.4 (1.7) |   +5.9   65+   +2.2 (0.7) |   +3.0 (0.7) |   +2.2   income  +2.9 (0.8) n=456
  m_B            20-39   -7.8 (1.8) |   -6.2 (1.9) |   -6.7   65+   +2.3 (1.0) |   +3.0 (1.0) |   +2.7   income  +3.0 (1.1) n=456
  m_G            20-39   +5.5 (1.6) |   +3.6 (1.7) |   +4.5   65+   +2.1 (0.9) |   +1.2 (1.0) |   +1.6   income  -3.4 (1.0) n=456
  m_third        20-39   +2.0 (0.5) |   +2.5 (0.5) |   +1.8   65+   -4.5 (0.3) |   -4.3 (0.3) |   -4.3   income  +0.8 (0.4) n=456
  c_B            20-39   -9.1 (2.3) |   -6.4 (2.5) |   -8.0   65+   +1.5 (1.2) |   +2.7 (1.3) |   +2.2   income  +5.0 (1.3) n=456
  c_G            20-39   +8.4 (2.0) |   +6.4 (2.1) |   +7.8   65+   +1.3 (1.1) |   +0.4 (1.1) |   +0.8   income  -3.7 (1.1) n=456
  c_TPP          20-39   -0.1 (0.5) |   +0.2 (0.6) |   -0.5   65+   -1.3 (0.3) |   -1.2 (0.4) |   -1.2   income  +0.5 (0.4) n=456
  c_U            20-39   +0.8 (1.2) |   -0.2 (1.2) |   +0.7   65+   -1.5 (0.6) |   -2.0 (0.7) |   -1.8   income  -1.8 (0.8) n=456
  p_KMT2024      20-39   -8.3 (1.6) |   -6.0 (1.8) |   -7.4   65+   +2.7 (0.9) |   +3.7 (1.0) |   +2.9   income  +4.1 (1.0) n=456
  p_DPP2024      20-39   +5.3 (1.7) |   +4.0 (1.8) |   +4.4   65+   +1.4 (0.9) |   +0.8 (1.0) |   +0.9   income  -2.4 (1.1) n=456
  p_TPP2024      20-39   +2.9 (0.5) |   +2.0 (0.5) |   +3.1   65+   -4.1 (0.3) |   -4.5 (0.3) |   -3.8   income  -1.8 (0.3) n=456
  turnout_p2024  20-39   +5.3 (1.5) |   +7.4 (1.6) |   +5.6   65+   +0.4 (0.6) |   +1.4 (0.6) |   +0.6   income  +3.8 (0.6) n=456

Taipei 2026
  turnout_m      20-39   +5.4 (1.7) |   +5.9 (1.8) |   +5.6   65+   -0.3 (0.6) |   -0.1 (0.6) |   +0.0   income  +1.0 (0.7) n=456
  m_B            20-39   -1.2 (1.9) |   +0.2 (2.0) |   +0.2   65+   +2.9 (1.0) |   +3.5 (1.0) |   +3.1   income  +2.5 (1.0) n=456
  m_G            20-39   +1.1 (1.9) |   -0.2 (2.0) |   -0.4   65+   -2.9 (1.0) |   -3.5 (1.0) |   -3.1   income  -2.4 (1.0) n=456
  c_B            20-39   -2.9 (2.0) |   +0.3 (2.1) |   -2.2   65+   +5.5 (1.1) |   +6.8 (1.1) |   +5.5   income  +5.7 (1.0) n=456
  c_G            20-39   +1.7 (2.0) |   +0.5 (2.1) |   +0.8   65+   -3.2 (1.1) |   -3.7 (1.1) |   -3.3   income  -2.1 (1.0) n=456
  c_TPP          20-39   +0.0 (0.5) |   +0.2 (0.5) |   -0.1   65+   -1.0 (0.3) |   -0.9 (0.3) |   -0.8   income  +0.3 (0.3) n=456
  c_U            20-39   +1.2 (0.8) |   -1.0 (0.9) |   +1.5   65+   -1.3 (0.5) |   -2.2 (0.5) |   -1.4   income  -3.9 (0.5) n=456

New Taipei 2018
  turnout_m      20-39   +2.6 (1.2) |   +2.3 (1.5) |   +4.9   65+   +5.8 (0.9) |   +5.4 (1.2) |   +6.9   income  -1.6 (1.6) n=1028
  m_B            20-39   -6.0 (0.9) |   -2.1 (0.9) |   -8.6   65+   -6.2 (0.9) |   -2.2 (0.9) |   -6.1   income +15.1 (1.5) n=1028
  m_G            20-39   +6.0 (0.9) |   +2.1 (0.9) |   +8.6   65+   +6.2 (0.9) |   +2.2 (0.9) |   +6.1   income -15.1 (1.5) n=1028
  c_B            20-39   -6.5 (1.1) |   -2.5 (1.2) |   -8.3   65+   -4.2 (1.0) |   -0.2 (1.2) |   -4.9   income +15.1 (1.9) n=1028
  c_G            20-39   +5.6 (1.0) |   +2.6 (1.1) |   +6.8   65+   +2.4 (0.9) |   -0.6 (1.1) |   +3.3   income -11.5 (1.8) n=1028
  c_U            20-39   +0.9 (0.6) |   -0.1 (0.7) |   +1.5   65+   +1.8 (0.6) |   +0.9 (0.6) |   +1.6   income  -3.6 (1.2) n=1028
  p_KMT2020      20-39   -6.9 (0.8) |   -4.0 (0.8) |   -8.3   65+   -3.0 (0.7) |   -0.1 (0.8) |   -2.2   income +10.8 (1.3) n=1028
  p_DPP2020      20-39   +7.0 (0.8) |   +4.0 (0.9) |   +8.6   65+   +3.4 (0.8) |   +0.4 (0.8) |   +2.8   income -11.4 (1.4) n=1028
  turnout_p2020  20-39   +2.4 (1.0) |   +4.2 (1.2) |   +4.4   65+   +1.8 (0.7) |   +3.5 (0.9) |   +2.8   income  +6.8 (1.1) n=1028

New Taipei 2022
  turnout_m      20-39   +2.1 (1.4) |   +2.7 (1.5) |   +3.8   65+   +6.9 (0.9) |   +7.4 (1.1) |   +6.8   income  +1.8 (1.1) n=1032
  m_B            20-39   -2.8 (0.8) |   -0.6 (0.9) |   -5.4   65+   -4.8 (0.6) |   -2.8 (0.7) |   -5.2   income  +6.8 (0.9) n=1032
  m_G            20-39   +2.8 (0.8) |   +0.6 (0.9) |   +5.4   65+   +4.8 (0.6) |   +2.8 (0.7) |   +5.2   income  -6.8 (0.9) n=1032
  c_B            20-39   -3.4 (1.0) |   -0.8 (1.1) |   -6.1   65+   -3.9 (0.8) |   -1.4 (0.8) |   -4.4   income  +8.3 (1.1) n=1032
  c_G            20-39   +3.8 (1.0) |   +1.5 (1.1) |   +6.2   65+   +3.2 (0.8) |   +1.0 (0.8) |   +3.5   income  -7.2 (1.1) n=1032
  c_TPP          20-39   -0.8 (0.2) |   -0.6 (0.2) |   -0.7   65+   -1.2 (0.2) |   -1.0 (0.2) |   -1.4   income  +0.7 (0.2) n=1032
  c_U            20-39   +0.4 (0.6) |   -0.1 (0.6) |   +0.7   65+   +2.0 (0.4) |   +1.4 (0.4) |   +2.2   income  -1.9 (0.6) n=1032
  p_KMT2024      20-39   -5.1 (0.8) |   -3.2 (0.9) |   -6.6   65+   -1.5 (0.6) |   +0.3 (0.6) |   -1.3   income  +5.9 (0.8) n=1032
  p_DPP2024      20-39   +1.9 (0.8) |   -0.1 (0.8) |   +3.8   65+   +4.7 (0.6) |   +2.7 (0.6) |   +4.6   income  -6.4 (0.8) n=1032
  p_TPP2024      20-39   +3.2 (0.3) |   +3.3 (0.4) |   +2.8   65+   -3.2 (0.2) |   -3.0 (0.3) |   -3.3   income  +0.4 (0.4) n=1032
  turnout_p2024  20-39   +3.1 (1.1) |   +5.1 (1.2) |   +4.6   65+   +2.0 (0.6) |   +3.9 (0.7) |   +1.8   income  +6.4 (0.7) n=1032

New Taipei 2026
  turnout_m      20-39   +3.3 (1.2) |   +5.1 (1.3) |   +5.0   65+   +4.1 (0.6) |   +5.9 (0.7) |   +3.5   income  +5.9 (0.7) n=1032
  m_B            20-39   -2.1 (0.9) |   -0.1 (0.9) |   -4.4   65+   -2.4 (0.6) |   -0.3 (0.7) |   -2.5   income  +7.0 (0.9) n=1032
  m_G            20-39   +2.0 (0.9) |   +0.1 (0.9) |   +4.2   65+   +2.3 (0.6) |   +0.2 (0.7) |   +2.4   income  -6.7 (0.9) n=1032
  c_B            20-39   -3.0 (0.8) |   -1.7 (0.8) |   -4.7   65+   -0.9 (0.6) |   +0.5 (0.6) |   -0.9   income  +4.1 (0.8) n=1032
  c_G            20-39   +2.0 (0.8) |   +0.4 (0.8) |   +4.2   65+   +2.3 (0.6) |   +0.6 (0.6) |   +2.7   income  -5.1 (0.8) n=1032
  c_TPP          20-39   +0.2 (0.3) |   +0.5 (0.3) |   +0.1   65+   -1.2 (0.2) |   -0.9 (0.2) |   -1.5   income  +1.3 (0.2) n=1032
  c_U            20-39   +0.8 (0.4) |   +0.7 (0.4) |   +0.5   65+   -0.1 (0.2) |   -0.2 (0.3) |   -0.3   income  -0.3 (0.3) n=1032

Keelung 2018
  turnout_m      20-39   -1.9 (3.6) |   -2.5 (3.7) |   +1.2   65+   +5.3 (2.2) |   +4.3 (2.4) |   +6.3   income  -7.0 (4.0) n=157
  m_B            20-39   -2.1 (2.2) |   -1.0 (2.2) |   -4.2   65+   -3.1 (1.7) |   -1.1 (1.7) |   -3.9   income +14.2 (2.6) n=157
  m_G            20-39   +2.1 (2.2) |   +1.0 (2.2) |   +4.2   65+   +3.1 (1.7) |   +1.1 (1.7) |   +3.9   income -14.2 (2.6) n=157
  c_B            20-39   -0.7 (3.6) |   +0.7 (3.7) |   +0.4   65+   -1.4 (2.5) |   +1.2 (2.6) |   -1.0   income +18.3 (4.5) n=157
  c_G            20-39   -0.3 (2.7) |   -0.9 (2.5) |   +3.3   65+   +1.6 (2.0) |   +0.6 (1.9) |   +2.5   income  -7.6 (3.7) n=157
  c_U            20-39   +1.0 (2.9) |   +0.2 (3.4) |   -3.6   65+   -0.3 (2.0) |   -1.8 (2.5) |   -1.5   income -10.7 (4.7) n=157
  p_KMT2020      20-39   -4.3 (2.1) |   -3.3 (2.0) |   -5.9   65+   -4.0 (1.5) |   -2.2 (1.5) |   -3.8   income +12.4 (2.7) n=157
  p_DPP2020      20-39   +3.9 (2.3) |   +2.9 (2.1) |   +5.9   65+   +4.2 (1.6) |   +2.3 (1.6) |   +4.1   income -13.0 (2.7) n=157
  turnout_p2020  20-39   +3.6 (2.6) |   +4.4 (2.5) |   +2.1   65+   +3.5 (1.7) |   +5.0 (1.7) |   +2.1   income +10.4 (2.3) n=157

Keelung 2022
  turnout_m      20-39   -3.3 (3.2) |   -3.2 (3.3) |   -1.7   65+   +3.7 (1.7) |   +3.8 (1.8) |   +4.0   income  +0.9 (2.2) n=157
  m_B            20-39   -2.7 (2.4) |   -1.6 (2.3) |   -3.5   65+   -3.6 (1.4) |   -2.3 (1.4) |   -2.8   income  +7.9 (2.3) n=157
  m_G            20-39   +2.7 (2.4) |   +1.5 (2.3) |   +3.5   65+   +3.4 (1.4) |   +2.1 (1.4) |   +2.7   income  -8.0 (2.2) n=157
  m_third        20-39   +0.1 (0.2) |   +0.1 (0.2) |   -0.0   65+   +0.2 (0.1) |   +0.2 (0.2) |   +0.1   income  +0.2 (0.2) n=157
  c_B            20-39   -5.0 (3.4) |   -4.8 (3.5) |   -5.8   65+   -2.9 (2.2) |   -2.7 (2.3) |   -2.4   income  +1.5 (3.6) n=157
  c_G            20-39   +7.1 (3.1) |   +6.5 (3.0) |   +7.3   65+   +3.0 (2.0) |   +2.3 (2.1) |   +1.6   income  -4.7 (3.0) n=157
  c_TPP          20-39   +0.3 (0.6) |   +0.3 (0.6) |   +0.4   65+   -0.1 (0.4) |   -0.0 (0.4) |   -0.2   income  +0.5 (0.6) n=157
  c_U            20-39   -2.4 (1.7) |   -2.0 (1.8) |   -1.9   65+   -0.0 (1.1) |   +0.4 (1.1) |   +1.0   income  +2.7 (1.3) n=157
  p_KMT2024      20-39   -4.3 (2.1) |   -3.2 (2.0) |   -4.9   65+   -2.5 (1.2) |   -1.3 (1.2) |   -1.9   income  +7.4 (2.0) n=157
  p_DPP2024      20-39   +0.8 (2.4) |   -0.5 (2.2) |   +2.0   65+   +5.5 (1.4) |   +4.0 (1.3) |   +4.7   income  -9.0 (2.0) n=157
  p_TPP2024      20-39   +3.5 (1.1) |   +3.7 (1.1) |   +3.0   65+   -3.0 (0.7) |   -2.7 (0.7) |   -2.9   income  +1.6 (1.0) n=157
  turnout_p2024  20-39   +3.8 (2.3) |   +5.2 (2.1) |   +1.5   65+   +3.4 (1.4) |   +4.9 (1.2) |   +1.4   income  +9.7 (1.3) n=157

Keelung 2026
  turnout_m      20-39   -1.6 (3.2) |   -1.3 (3.3) |   +1.8   65+   +2.4 (1.7) |   +2.7 (1.8) |   +3.7   income  +1.3 (2.4) n=157
  m_B            20-39   -3.1 (2.2) |   -1.7 (2.1) |   -3.4   65+   -3.5 (1.3) |   -2.2 (1.2) |   -2.4   income  +7.4 (2.1) n=157
  m_G            20-39   +3.5 (2.2) |   +2.3 (2.1) |   +3.5   65+   +3.6 (1.2) |   +2.5 (1.2) |   +2.5   income  -6.7 (2.0) n=157
  c_B            20-39   -8.2 (3.3) |   -7.6 (3.3) |   -7.7   65+   -1.8 (1.8) |   -1.3 (1.8) |   -0.2   income  +2.9 (2.8) n=157
  c_G            20-39  +10.3 (2.8) |   +9.6 (2.8) |   +8.5   65+   +4.9 (1.6) |   +4.3 (1.6) |   +2.7   income  -3.4 (2.4) n=157
  c_TPP          20-39   +0.4 (0.7) |   +0.9 (0.7) |   +0.8   65+   -1.1 (0.5) |   -0.6 (0.5) |   -1.7   income  +2.5 (0.7) n=157
  c_U            20-39   -2.5 (2.7) |   -2.8 (2.7) |   -1.6   65+   -2.0 (1.4) |   -2.4 (1.4) |   -0.9   income  -2.1 (2.4) n=157

Taoyuan 2018
  turnout_m      20-39   +2.0 (1.2) |   +0.9 (1.3) |   +2.3   65+   +7.5 (0.9) |   +6.0 (1.1) |   +7.5   income  -4.6 (1.5) n=504
  m_B            20-39  -10.2 (1.6) |   -8.0 (1.8) |  -11.1   65+   -8.8 (1.0) |   -5.6 (1.5) |   -7.2   income  +9.8 (3.1) n=504
  m_G            20-39  +10.3 (1.6) |   +8.0 (1.7) |  +11.2   65+   +9.2 (1.0) |   +5.8 (1.4) |   +7.6   income -10.3 (3.1) n=504
  m_third        20-39   +0.1 (0.2) |   +0.1 (0.2) |   +0.0   65+   -0.1 (0.2) |   -0.1 (0.2) |   -0.2   income  -0.0 (0.3) n=504
  c_B            20-39   -9.7 (1.8) |   -8.3 (2.0) |  -10.9   65+  -10.2 (1.3) |   -8.1 (1.7) |   -8.9   income  +6.3 (3.6) n=504
  c_G            20-39   +9.3 (1.8) |   +7.7 (1.9) |  +10.3   65+   +8.3 (1.2) |   +5.9 (1.6) |   +7.7   income  -7.3 (2.8) n=504
  c_U            20-39   +0.4 (1.4) |   +0.6 (1.7) |   +0.6   65+   +1.9 (1.2) |   +2.3 (1.5) |   +1.1   income  +1.0 (3.1) n=504
  p_KMT2020      20-39   -8.2 (1.5) |   -7.0 (1.6) |   -9.1   65+   -6.4 (0.9) |   -4.7 (1.3) |   -4.8   income  +5.1 (2.8) n=504
  p_DPP2020      20-39   +8.3 (1.5) |   +7.1 (1.6) |   +9.3   65+   +7.2 (0.9) |   +5.3 (1.3) |   +5.7   income  -5.6 (2.8) n=504
  turnout_p2020  20-39   +1.6 (1.0) |   +3.1 (1.1) |   +2.2   65+   +2.4 (0.8) |   +4.6 (0.9) |   +3.0   income  +6.7 (0.9) n=504

Taoyuan 2022
  turnout_m      20-39   +0.8 (1.2) |   +1.0 (1.2) |   +1.8   65+   +6.4 (0.8) |   +7.1 (0.8) |   +7.0   income  +2.4 (0.9) n=516
  m_B            20-39  -11.5 (1.5) |  -11.3 (1.6) |  -11.5   65+  -10.2 (0.9) |   -9.6 (1.0) |   -8.6   income  +2.2 (1.5) n=516
  m_G            20-39  +10.0 (1.5) |   +9.9 (1.5) |  +10.1   65+  +10.0 (0.8) |   +9.5 (0.9) |   +8.3   income  -1.7 (1.4) n=516
  m_third        20-39   +0.9 (0.2) |   +0.9 (0.2) |   +1.0   65+   -0.5 (0.1) |   -0.3 (0.1) |   -0.5   income  +0.7 (0.2) n=516
  c_B            20-39   -8.0 (1.6) |   -8.3 (1.6) |   -7.9   65+   -7.1 (1.0) |   -7.8 (1.2) |   -5.3   income  -2.3 (1.7) n=516
  c_G            20-39  +12.0 (1.8) |  +11.9 (1.8) |  +11.8   65+  +10.1 (1.1) |   +9.8 (1.2) |   +9.0   income  -1.2 (1.7) n=516
  c_TPP          20-39   -0.6 (0.5) |   -0.4 (0.5) |   -0.6   65+   -1.5 (0.5) |   -1.0 (0.4) |   -1.9   income  +1.9 (0.5) n=516
  c_U            20-39   -3.4 (1.4) |   -3.2 (1.4) |   -3.3   65+   -1.5 (0.9) |   -1.1 (1.0) |   -1.8   income  +1.6 (1.4) n=516
  p_KMT2024      20-39  -10.1 (1.2) |  -10.1 (1.2) |  -10.2   65+   -5.5 (0.7) |   -5.4 (0.8) |   -3.9   income  +0.4 (1.1) n=516
  p_DPP2024      20-39   +6.2 (1.3) |   +6.2 (1.3) |   +6.3   65+   +9.1 (0.7) |   +9.0 (0.8) |   +7.8   income  -0.6 (1.3) n=516
  p_TPP2024      20-39   +3.9 (0.4) |   +3.9 (0.3) |   +3.9   65+   -3.7 (0.3) |   -3.6 (0.3) |   -3.9   income  +0.3 (0.4) n=516
  turnout_p2024  20-39   +2.3 (1.1) |   +3.0 (1.1) |   +3.6   65+   +2.2 (0.7) |   +3.9 (0.7) |   +2.8   income  +6.2 (0.6) n=516

Taoyuan 2026
  turnout_m      20-39   +2.1 (1.1) |   +2.9 (1.2) |   +3.4   65+   +4.6 (0.8) |   +6.0 (0.8) |   +5.1   income  +4.6 (0.8) n=516
  m_B            20-39   -8.0 (1.3) |   -8.5 (1.4) |   -8.0   65+   -6.8 (0.9) |   -7.8 (1.0) |   -5.9   income  -3.0 (1.4) n=516
  m_G            20-39   +8.0 (1.3) |   +8.5 (1.4) |   +8.0   65+   +6.8 (0.9) |   +7.8 (1.0) |   +5.9   income  +3.0 (1.4) n=516
  c_B            20-39  -10.7 (1.5) |  -10.2 (1.6) |  -10.3   65+   -6.7 (1.0) |   -7.6 (1.2) |   -5.5   income  -3.3 (1.5) n=516
  c_G            20-39   +7.3 (1.4) |   +7.2 (1.5) |   +7.4   65+   +4.2 (0.9) |   +6.0 (1.0) |   +3.4   income  +7.1 (1.4) n=516
  c_TPP          20-39   +0.3 (0.3) |   +0.2 (0.2) |   +0.6   65+   -0.6 (0.1) |   -0.3 (0.1) |   -0.6   income  +1.1 (0.2) n=516
  c_U            20-39   +3.1 (1.2) |   +2.8 (1.4) |   +2.3   65+   +3.1 (0.9) |   +1.9 (0.9) |   +2.6   income  -4.9 (1.3) n=516

## 3. 2022->2026 changes and 2026 mayor-council gaps against 2026 age shares (r across villages / within districts)

Taipei
  turnout change                 mean   +4.3 | r65 -0.41 r20-39 +0.36 | within r65 -0.30 r20-39 +0.21
  KMT mayoral share change       mean  +11.2 | r65 -0.49 r20-39 +0.51 | within r65 -0.33 r20-39 +0.29
  KMT mayor - KMT council        mean  +11.7 | r65 -0.21 r20-39 +0.22 | within r65 -0.33 r20-39 +0.25
  KMT mayor - (KMT+TPP council)  mean   +2.6 | r65 -0.05 r20-39 +0.07 | within r65 -0.23 r20-39 +0.20
  DPP mayor - DPP council        mean   +1.8 | r65 +0.15 r20-39 -0.16 | within r65 +0.08 r20-39 -0.08

New Taipei
  turnout change                 mean   +6.4 | r65 -0.38 r20-39 +0.31 | within r65 -0.26 r20-39 +0.20
  KMT mayoral share change       mean  -11.1 | r65 +0.29 r20-39 -0.22 | within r65 +0.31 r20-39 -0.20
  KMT mayor - KMT council        mean  +11.7 | r65 +0.23 r20-39 -0.29 | within r65 -0.22 r20-39 +0.20
  KMT mayor - (KMT+TPP council)  mean   +4.8 | r65 +0.35 r20-39 -0.38 | within r65 -0.08 r20-39 +0.09
  DPP mayor - DPP council        mean   -0.4 | r65 -0.43 r20-39 +0.48 | within r65 +0.01 r20-39 -0.00

Keelung
  turnout change                 mean   +2.5 | r65 -0.30 r20-39 +0.37 | within r65 -0.33 r20-39 +0.39
  KMT mayoral share change       mean   -1.8 | r65 -0.03 r20-39 +0.01 | within r65 +0.07 r20-39 -0.11
  KMT mayor - KMT council        mean  +11.4 | r65 -0.19 r20-39 +0.11 | within r65 -0.36 r20-39 +0.38
  KMT mayor - (KMT+TPP council)  mean   +6.8 | r65 -0.11 r20-39 -0.01 | within r65 -0.26 r20-39 +0.29
  DPP mayor - DPP council        mean  +13.3 | r65 +0.03 r20-39 -0.15 | within r65 +0.23 r20-39 -0.32

Taoyuan
  turnout change                 mean   +0.5 | r65 -0.22 r20-39 +0.04 | within r65 -0.25 r20-39 +0.14
  KMT mayoral share change       mean   +4.0 | r65 +0.11 r20-39 +0.11 | within r65 +0.16 r20-39 +0.04
  KMT mayor - KMT council        mean  +16.0 | r65 -0.01 r20-39 +0.05 | within r65 -0.18 r20-39 +0.21
  KMT mayor - (KMT+TPP council)  mean  +13.2 | r65 +0.03 r20-39 +0.05 | within r65 -0.10 r20-39 +0.14
  DPP mayor - DPP council        mean   +6.7 | r65 +0.19 r20-39 -0.15 | within r65 +0.24 r20-39 -0.18

## 4. Bounded ecological estimates by age group (share of electors), within districts; 95% bootstrap intervals
  Taipei     2022 20-39  KMT   14 [ 10, 22]  DPP   37 [ 28, 44]  turnout   83 [ 75, 89]
  Taipei     2022 40-64  KMT   26 [ 21, 29]  DPP   12 [  8, 17]  turnout   53 [ 49, 59]
  Taipei     2022 65+    KMT   50 [ 43, 56]  DPP   23 [ 18, 28]  turnout   75 [ 68, 81]
  Taipei     2026 20-39  KMT   39 [ 30, 51]  DPP   47 [ 33, 55]  turnout   87 [ 76, 94]
  Taipei     2026 40-64  KMT   33 [ 26, 39]  DPP   35 [ 30, 43]  turnout   69 [ 64, 74]
  Taipei     2026 65+    KMT   46 [ 39, 54]  DPP   18 [ 13, 23]  turnout   64 [ 58, 70]
  New Taipei 2022 20-39  KMT   32 [ 20, 37]  DPP   31 [ 26, 33]  turnout   64 [ 50, 69]
  New Taipei 2022 40-64  KMT   33 [ 29, 41]  DPP    6 [  5, 10]  turnout   39 [ 35, 49]
  New Taipei 2022 65+    KMT   47 [ 41, 50]  DPP   43 [ 39, 47]  turnout   90 [ 84, 92]
  New Taipei 2026 20-39  KMT   29 [ 19, 36]  DPP   49 [ 39, 53]  turnout   79 [ 66, 81]
  New Taipei 2026 40-64  KMT   32 [ 28, 38]  DPP   14 [ 13, 22]  turnout   47 [ 45, 56]
  New Taipei 2026 65+    KMT   37 [ 32, 42]  DPP   42 [ 38, 46]  turnout   80 [ 76, 83]
  Keelung    2022 20-39  KMT   26 [ 12, 39]  DPP   26 [ 14, 39]  turnout   54 [ 37, 67]
  Keelung    2022 40-64  KMT   33 [ 23, 41]  DPP   16 [ 10, 24]  turnout   50 [ 42, 61]
  Keelung    2022 65+    KMT   36 [ 29, 45]  DPP   55 [ 44, 61]  turnout   92 [ 84, 96]
  Keelung    2026 20-39  KMT   29 [  9, 40]  DPP   35 [ 21, 48]  turnout   65 [ 34, 79]
  Keelung    2026 40-64  KMT   32 [ 24, 46]  DPP   15 [  7, 25]  turnout   48 [ 39, 69]
  Keelung    2026 65+    KMT   32 [ 25, 39]  DPP   54 [ 45, 59]  turnout   87 [ 78, 91]
  Taoyuan    2022 20-39  KMT   11 [  7, 19]  DPP   30 [ 25, 34]  turnout   48 [ 42, 57]
  Taoyuan    2022 40-64  KMT   48 [ 40, 51]  DPP    4 [  3, 10]  turnout   55 [ 49, 61]
  Taoyuan    2022 65+    KMT   27 [ 22, 35]  DPP   64 [ 55, 67]  turnout   95 [ 89, 97]
  Taoyuan    2026 20-39  KMT   22 [ 17, 32]  DPP   37 [ 29, 41]  turnout   59 [ 51, 69]
  Taoyuan    2026 40-64  KMT   42 [ 34, 47]  DPP    8 [  6, 14]  turnout   50 [ 44, 57]
  Taoyuan    2026 65+    KMT   32 [ 27, 37]  DPP   53 [ 47, 56]  turnout   85 [ 79, 88]

AI disclosure statement

The code on this page was written with Claude (Anthropic’s Claude Opus 5.5 model) as a research assistant. Shen-yi Liao is responsible for it: what it computes, the cleaning rules and any errors. After another AI model reviewed the method, Shen-yi Liao chose which checks to run and asked for the method to be revised where that served readers. Under Shen-yi Liao’s direction, Claude wrote the scripts (including the bounded estimator, the robustness checks and the turnout and age analyses added on 1 December 2026) and this page and reran each analysis from the government files to check that the outputs match those published here. Shen-yi Liao did not re-run the code; the instructions above are for anyone who wants to.

← Home: all articles in this series