# List comprehension - using list element as a conditional to select data to operate on

I was working through the ‘Variance and Standard Deviation’ module within the ‘Learn Statistics with Python’ section, specifically the Variance in Weather) project.

There is a loop that takes each month of the dataset (each month is represented by an integer 1-12) and calculates the average temperature for that month. Here is the code:

``````> for i in range(1, 13):
>   month = london_data.loc[london_data["month"] == i]["TemperatureC"]
>   print("The mean temperature in month "+str(i) +" is "+ str(np.mean(month)))
``````

I wanted to replace the integers with actual month names, so I made a dictionary and used it to replace the integers in the ‘month’ column:

``````> month_dict = {
>   1 : "January",
>   2 : "February",
>   3 : "March",
>   4 : "April",
>   5 : "May",
>   6 : "June",
>   7 : "July",
>   8 : "August",
>   9 : "September",
>   10 : "October",
>   11 : "November",
>   12 : "December"
> }
>
> new_df = london_data.replace({"month" : month_dict})
``````

I tried to replicate the loop to use each month in a list of months to calculate the average wind speed:

``````> month_list = new_df['month'].unique().tolist()

> for month in month_list:
>   print("The average wind speed in " +month+" is " + str(np.average(new_df["WindSpeedKMH"])))
``````

This code produces a sentence for each month, but the calculated value (the average windspeed) is the same for every month.

Is there a way I can calculate the average windspeed for each month in the year using this list comprehension? I have searched Google and spent a long time playing around myself but I can’t figure out a way to do it inside the list comprehension.

Any help greatly appreciated!