Search code examples
pythonfunctionfor-loopvariablesautomatic-storage

Automatically calculating percentage and store into variables


I am currently on a demographic project. I have data from 3 different countries and their birth statistics in each month.

My question: I want to calculate the percentage people born in each month and plot it for each country. (x = Month, y = Percentage born) Therefore, I want to calculate the percentages first. I want to do this per iteration over all months to improve my code. So far:

EU = df2["European Union - 28 countries (2013-2020)"]
CZE = df2["Czechia"]
GER = df2["Germany including former GDR"]

EU_1 = EU[1] / EU[0] *100
EU_2 = EU[2] / EU[0] *100
etc.

for each month and 3 countries.

How can I calculate all automatically by changing Country [i] and store every value separately (Function, for loop?)

Thank you very much!


Solution

  • You could do something like this:

    EU = df2["European Union - 28 countries (2013-2020)"]
    monthly_percentages = [num_born / EU[0] * 100 for num_born in EU[1:]]
    

    Assuming that the first element of EU is the total births that year and the rest are the births per each month. If you wanted to do all the countries automatically, you could loop through each country and calculate the birth percentage for each month, then store it somewhere. It would look something like:

    country_birth_percentages = []
    
    for country in countries:
        country_birth_percentages.append([num_born / country[0] * 100 for num_born in country[1:]])