user9996043
user9996043

Reputation: 229

Pandas - Fill N rows for a specific column with a integer value and increment the integer there after

I have a dataframe to which I added say a column named col_1. I want to add integer values to that column starting from the first row that increment after every 4th row. So the new resulting column should have values of as such.

     col_1
       1
       1
       1
       1
       2
       2
       2
       2

The current approach I have is a very brute force one:

for x in range(len(df)):
    if x <= 3:
        df['col_1'][x] = 1
    if x >3 and x <= 7:
        df['col_1'][x] = 2

This might work for something small but when moving to something larger it will chew up a lot of time.

Upvotes: 1

Views: 1682

Answers (1)

jezrael
jezrael

Reputation: 862911

If there si default RangeIndex you can use integer division with add 1:

df['col_1'] = df.index // 4 + 1

Or for general solution use helper array by lenght of DataFrame:

df['col_1'] = np.arange(len(df)) // 4 + 1

For repeat 1 and 2 pattern use also modulo by 2 like:

df = pd.DataFrame({'a':range(20, 40)})
df['col_1'] = (np.arange(len(df)) // 4) % 2 + 1
print (df)
     a  col_1
0   20      1
1   21      1
2   22      1
3   23      1
4   24      2
5   25      2
6   26      2
7   27      2
8   28      1
9   29      1
10  30      1
11  31      1
12  32      2
13  33      2
14  34      2
15  35      2
16  36      1
17  37      1
18  38      1
19  39      1

Upvotes: 1

Related Questions