Home > Blockchain >  Is there a way to turn this into a loop?
Is there a way to turn this into a loop?

Time:09-11

Is there a way to turn this into a loop, where the city names (berlin, munich, hamburg, cologne) are looped in the calculations as well as in the print? If so, how do i do it?

max_b = airquality_berlin['NO2'].max() 
min_b = airquality_berlin['NO2'].min()
 
print(f"The inter-annual range of NO2-concentration in Berlin is: {max_b-min_b}\n")

max_b = airquality_munich['NO2'].max() 
min_b = airquality_munich['NO2'].min()
 
print(f"The inter-annual range of NO2-concentration in Munich is: {max_b-min_b}\n")

max_b = airquality_hamburg['NO2'].max() 
min_b = airquality_hamburg['NO2'].min()
 
print(f"The inter-annual range of NO2-concentration in Hamburg is: {max_b-min_b}\n")

max_b = airquality_cologne['NO2'].max() 
min_b = airquality_cologne['NO2'].min()
 
print(f"The inter-annual range of NO2-concentration in Cologne is: {max_b-min_b}\n")

CodePudding user response:

You'll be wanting to put your data in a data structure. For example, here is a way of doing it with a list of dictionaries.

cities = [
    {"name": "Berlin", "air_quality": airquality_berlin},
    {"name": "Munich", "air_quality": airquality_munich},
    {"name": "Hamburg", "air_quality": airquality_hamburg},
    {"name": "Cologne", "air_quality": airquality_cologne},
]
for city in cities:
    name = city["name"]
    max_b = city["air_quality"]["NO2"].max()
    min_b = city["air_quality"]["NO2"].min()
    print(f"The inter-annual range of NO2-concentration in {name} is: {max_b - min_b}")

CodePudding user response:

If it's lazy to make an additional dictionary :)

airquality_berlin = pd.DataFrame({'NO2': [1, 2, 3, 4, 5]})
airquality_munich = pd.DataFrame({'NO2': [11, 12, 13, 14, 15]})
airquality_hamburg = pd.DataFrame({'NO2': [21, 22, 23, 24, 55]})

v = None
for v in locals():
    if v.split('_')[0] == 'airquality':
        print(f"The inter-annual range of NO2-concentration in {v.split('_')[1].capitalize()} is: "
              f"{locals()[v]['NO2'].max() - locals()[v]['NO2'].min()}")

Prints:

The inter-annual range of NO2-concentration in Berlin is: 4
The inter-annual range of NO2-concentration in Munich is: 4
The inter-annual range of NO2-concentration in Hamburg is: 34
  • Related