'Creating a squential number counter using a user input and a numpy array
I'm trying to create a counter that counts sequentially up to a total that the user specifies, then starts at zero and repeats for the length of my data frame. First, I ask the user to enter the counter to define a 'block':
block_cycles = int(input('Please enter the number of cycles that constitute a block: \n\n'))
Then, I take that value, and try to create a numpy array that builds an array of sequential numbers, up to the user input and then resets to 1 and begins again. After that, I place it in a list, and then build a column to append to my dataframe. This is my current idea:
# Fill out Sequential Numbers and append title
lens = len(raw_data.index)
arr = np.arange(lens)
a = arr // (block_cycles)
sequential = np.where(a == 0, arr + 1, np.nan)
sequential_list = sequential.tolist()
sequential_list.insert(0,'*Sequential number')
interim_data_output['SN5'] = sequential_list
However, this only fills up my array up to the block_cycles number. For example, if my input was 3, my output would be this:
print (interim_data_output['SN5'])
0 *Sequential number
1 1.0
2 2.0
3 3.0
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
Which is not my desired output as I would like it to repeat. This is my desired output:
print (interim_data_output['SN5'])
0 *Sequential number
1 1.0
2 2.0
3 3.0
4 1.0
5 2.0
6 3.0
7 1.0
8 2.0
Where am I going wrong in order to achieve this, and get the counter to repeat? Any held would be most appreciated
Solution 1:[1]
counter that counts sequentially up to a total that the user specifies, then starts at zero and repeats
You might get that effect using numpy's functions arange and tile, for example to have 5 cycles of 0,1,2 you might do:
import numpy as np
arr = np.tile(np.arange(3),5)
print(arr) # [0 1 2 0 1 2 0 1 2 0 1 2 0 1 2]
or harnessing itertools getting desired number of elements (here 15):
import itertools
lst = list(itertools.islice(itertools.cycle(range(3)),15))
print(lst) # [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daweo |
