1

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

2 Answers 2

3

You can iterate through a loop,

for year in [2020, 2021, 2022]: filter_year = hdb_million[hdb_million["year"]== year] town = filter_year["town"].unique() results = len(town) print(town) print(f"in {year} the number of towns are:", results) print("\n") 
Sign up to request clarification or add additional context in comments.

1 Comment

As much as it's an option. I think they were looking for a function with a def
0

If you just want the print things to be repeated using a function.

def print_town_info(year, town_input): filter_year = town_input[town_input["year"] == year] town = filter_year["town"].unique() print(town) print("in " + str(year) + " the number of towns are:", len(town)) print("\n") 

Then if you want it in a loop:

for y in [2020, 2021, 2022]: print_town_info(y, hdb_million) 

2 Comments

Many thanks AER. I struggled a bit to understand why do we need 2 arguments in def print_town_info(year, town_input): .. I tried the following and it seems to work def print_town_info(year): filter_year=hdb_million[hdb_million["year"] == year] .. with the rest of your codes. Is my code technically correct
More if you want to use a different dataframe that's all. Sure, if it works that's also fine. I just don't like assuming variables inside functions. But yes, if it's already defined in that file it'll work. Remember to accept the answer as well (points for you) if it answers your question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.