I am trying to post a question to StackOverflowStack Overflow (and also relevant on a few other sites) but am met with the following message:
Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon.
I'm not entirely sure why given that I've followed the formatting where I believe it is required. My question is formatted as follows:
I would like to calculate the annual percentage change in GDP for respective countries in a dataset. The dataset is formatted as follows,{do something with each row corresponding to a annual recording for a countrythis data}:
| Country | Year | LifeExp | GDP |
|---|---|---|---|
| Chile | 2000 | 77.3 | 7.79e+10 |
| Chile | 2000 | 77.3 | 7.79e+10 |
| Chile | 2000 | 77.3 | 7.79e+10 |
| ... | ... | ... | ... |
| Zimbabwe | 2013 | 58.0 | 1.55e+10 |
| Zimbabwe | 2014 | 59.2 | 1.59e+10 |
| Zimbabwe | 2015 | 60.7 | 1.63e+10 |
Ideally, I would like to loop over the rows and if the country in that row is the same as the previous row, calculate the percentage change in GDP between the two rows.
Until now, I have had to go through each country individually and append it to a new column GDP% myself. I've tried to put the code below into a loop and have the country name as a variable (below: 'Chile'), but to no avail{do more stuff with this data}.
gdp_data['GDP%'] = 0
gdp_country = gdp_data[gdp_data['Country'] == 'Chile']
gdp_data['GDP%'] = gdp_country['GDP'].pct_change()
Is there a (correct and) more efficient way?