I have a data-frame like this
name qty1 qty2 set_id
0 name0 2 5 1000
1 name1 1 7 1000
2 name2 0 4 1000
3 name3 6 6 1000
4 name4 8 8 1000
5 name5 0 3 1000
I want to update the set_id column like this. (for every nth row(here 3rd row) new set id to be updated.)
name qty1 qty2 set_id
0 name0 2 5 1
1 name1 1 7 1
2 name2 0 4 2
3 name3 6 6 2
4 name4 8 8 3
5 name5 0 3 3
CodePudding user response:
IIUC, you can use a list comprehension
and assign it's return to your set_id column:
df['set_id'] = pd.Series([(i 1) for i in range(len(df)) for n in range(2)])
prints:
name qty1 qty2 set_id
0 0 name0 2 5 1
1 1 name1 1 7 1
2 2 name2 0 4 2
3 3 name3 6 6 2
4 4 name4 8 8 3
5 5 name5 0 3 3
You can adjust the number in range(2)
to determine your 'nth' row, as you call it.
CodePudding user response:
You can use pd.RangeIndex
and repeat
:
N = 2 # 3rd row
df['set_id'] = pd.RangeIndex(1, 1 len(df)//N).repeat(N)
print(df)
# Output:
name qty1 qty2 set_id
0 name0 2 5 1
1 name1 1 7 1
2 name2 0 4 2
3 name3 6 6 2
4 name4 8 8 3
5 name5 0 3 3
Or the same with np.arange
and np.repeat
:
N = 2 # 3rd row
df['set_id'] = np.repeat(np.arange(1, 1 len(df)//N), N)
print(df)
# Output:
name qty1 qty2 set_id
0 name0 2 5 1
1 name1 1 7 1
2 name2 0 4 2
3 name3 6 6 2
4 name4 8 8 3
5 name5 0 3 3