如何添加每3行增加1的新列?



如何添加每3行增加1的新列?.....................................

Dataframe             
a    b
0    20   30
1    44   12 
2    58   23 
3    20   30
4    44   12 
5    58   23
6    20   30
7    44   12 
8    58   23 
Expected Output:             
a    b    year
0    20   30    1995
1    44   12    1995
2    58   23    1995
3    20   30    1996
4    44   12    1996
5    58   23    1996
6    20   30    1997
7    44   12    1997
8    58   23    1997

使用3的整数除法,默认索引值:

df['year'] = df.index // 3 + 1995

或对于一般解决方案创建辅助数组:

df['year'] =  np.arange(len(df.index)) // 3 + 1995

您可以使用:

df['year'] = 1995 + df.index//3

或者,如果您不能依赖索引,使用numpy:

import numpy as np
df['year'] = 1995 + np.arange(len(df))//3

输出:

a   b  year
0  20  30  1995
1  44  12  1995
2  58  23  1995
3  20  30  1996
4  44  12  1996
5  58  23  1996
6  20  30  1997
7  44  12  1997
8  58  23  1997