I want to add a new column called id
to my pandas DataFrame. If the value of id
is just a fixed number, then I can create a new column as follows:
JavaScript
x
3
1
id_value = 1
2
df.insert(0, 'id', id_value)
3
However, in my case I need to create batches of 3 rows, as follows:
JavaScript
1
12
12
1
id
2
1
3
1
4
1
5
2
6
2
7
2
8
3
9
3
10
3
11
12
How can I do it?
Advertisement
Answer
You can create array by np.arange
with integer division by 3
, so starting by 0
, if need custom first number add id_value
:
JavaScript
1
3
1
id_value = 1
2
df.insert(0, 'id', np.arange(len(df)) // 3 + id_value)
3
If there is default index values also working:
JavaScript
1
17
17
1
df = pd.DataFrame({'a':np.random.randint(10, size=10)})
2
3
id_value = 1
4
df.insert(0, 'id', df.index // 3 + id_value)
5
print (df)
6
id a
7
0 1 2
8
1 1 8
9
2 1 5
10
3 2 3
11
4 2 1
12
5 2 1
13
6 3 9
14
7 3 2
15
8 3 7
16
9 4 5
17