Home > Enterprise >  Define a function to a dataframe
Define a function to a dataframe

Time:10-20

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

CodePudding user response:

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")

CodePudding user response:

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)
  • Related