pandas insert values in order plus one

Question:

I want to make a data frame with columns from 2012 to 2100. I would like to make a data frame that gives +1 in 2012 in reference column Stand_Age(example below table), and +1 in 2013 plus +1 in 2012 and +1 in 2100 in 2099 as well. Code and the frame are below.

for i in list(range(0, 90, 1)):
    Stand_Age[i+1] = Stand_Age[i] + 1

pre year plus one by 2100

Asked By: YJK

||

Answers:

You shouldn’t use Stand_Age[i+1] but rather

df["2012"] = df["Stand_Age"] + 1

And for many rows it would need

for i in range(1, 90):
    df[str(2011+i)] = df["Stand_Age"] + i

Minimal working code:

import pandas as pd

df = pd.DataFrame({
    "Stand_Age": [1,1,2,2,3,3,4,4,5,5]
})

print(df)

for i in range(1, 10):
    df[str(2011+i)] = df["Stand_Age"] + i

print(df)

Result:

  Stand_Age
0          1
1          1
2          2
3          2
4          3
5          3
6          4
7          4
8          5
9          5

   Stand_Age  2012  2013  2014  2015  2016  2017  2018  2019  2020
0          1     2     3     4     5     6     7     8     9    10
1          1     2     3     4     5     6     7     8     9    10
2          2     3     4     5     6     7     8     9    10    11
3          2     3     4     5     6     7     8     9    10    11
4          3     4     5     6     7     8     9    10    11    12
5          3     4     5     6     7     8     9    10    11    12
6          4     5     6     7     8     9    10    11    12    13
7          4     5     6     7     8     9    10    11    12    13
8          5     6     7     8     9    10    11    12    13    14
9          5     6     7     8     9    10    11    12    13    14
Answered By: furas
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.