Home > Mobile >  How do I add a new column that increments by 1 every 3 rows?
How do I add a new column that increments by 1 every 3 rows?

Time:06-10

How do I add a new column that increments by 1 every 3 rows? .....................................

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

CodePudding user response:

Use ineteger division by 3 by default index values:

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

Or for general solution create helper array:

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

CodePudding user response:

You can use:

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

or, in case you can't rely on the index, with numpy:

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

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
  • Related