Consider this code in Python
filter_2020 = hdb_million[hdb_million["year"]==2020] town_2020 = filter_2020["town"].unique() results_2020 = len(town_2020) print(town_2020) print("in 2020 the number of towns are:", results_2020) print("\n") filter_2021 = hdb_million[hdb_million["year"]==2021] town_2021 = filter_2021["town"].unique() results_2021 = len(town_2021) print(town_2021) print("in 2021 the number of towns are:", results_2021) print("\n") filter_2022 = hdb_million[hdb_million["year"]==2022] town_2022 = filter_2022["town"].unique() results_2022 = len(town_2022) print(town_2022) Output
['BUKIT MERAH' 'CLEMENTI' 'TOA PAYOH' 'KALLANG/WHAMPOA' 'QUEENSTOWN' 'BISHAN' 'CENTRAL AREA' 'ANG MO KIO' 'GEYLANG'] in 2020 the number of towns are: 9 ['BISHAN' 'BUKIT MERAH' 'CENTRAL AREA' 'CLEMENTI' 'QUEENSTOWN' 'SERANGOON' 'TOA PAYOH' 'BUKIT TIMAH' 'KALLANG/WHAMPOA' 'ANG MO KIO'] in 2021 the number of towns are: 10 ['ANG MO KIO' 'BISHAN' 'BUKIT TIMAH' 'CENTRAL AREA' 'CLEMENTI' 'GEYLANG' 'KALLANG/WHAMPOA' 'QUEENSTOWN' 'SERANGOON' 'TOA PAYOH' 'BUKIT MERAH' 'YISHUN' 'PASIR RIS' 'WOODLANDS' 'BUKIT BATOK' 'HOUGANG' 'MARINE PARADE' 'PUNGGOL' 'TAMPINES' 'BEDOK'] in 2022 the number of towns are: 20 Instead of repeating the codes, can I define a function to arrive at the same output ? I tried several def functions but am not successful. Most grateful for any insights. thank you