Question:
The data I used look like this
I want to calculate each variable growth for each year so the result will look like this
I already do it manually for each variable for each year with code like this
Is there a way to do it more efficient escpecially if I have more year and/or more variable?
Answer:
Input
Next, a loop is created and the columns are filled:
Output
In the loop, the year is extracted from the column name, converted to int, 1 is added to it. The value is again converted to a string, the prefix ‘_Xn’ is added. A new_name variable is created, to which the string ‘_gro ‘ is also appended. A column is created and filled with calculated values.
If you want to count, for example, for three years, then you need to add not 1, but 3. This is with the condition that your data will be ordered. And note that the loop does not go through all the elements: for i in range(1, len(df.columns) – 2):. In this case, it skips the Subject column and stops short of the last two values. That is, you need to know where to stop it.
If you have better answer, please add a comment about this, thank you!