Reputation: 13
For example, the double values in the first array [1.2,4.6,3.7,11.2,13,5,18.9,0.3,20.0,26.7,1]
now I want to create another array based on the first one with states 1, 2 and 3
for every value in the first array that is in the range [0,10)
add the value 1 in the second array
so the range [0,10)
represents state 1
the range [10,20)
represents state 2
the range [20,30)
represents state 3
so at the end, the second array would look like [1,1,1,2,2,2,1,3,3,1]
This is a transition state array that will help to build the transition matrix in python **
Upvotes: 0
Views: 129
Reputation: 251
If you do not want to use numpy (see yatu's solution) or want to explicitly see a basic pure Python implementation, check out the below:
arr = [1.2,4.6,3.7,11.2,13,5,18.9,0.3,20.0,26.7,1]
def get_state(el):
if 0 <= el < 10:
return 1
elif 10 <= el < 20:
return 2
elif 20 <= el < 30:
return 3
else:
raise Exception(f"Unexpected value: {el}")
res = [get_state(el) for el in arr]
# [1, 1, 1, 2, 2, 1, 2, 1, 3, 3, 1]
Upvotes: 0
Reputation: 88285
If numpy is an option this is quite simple with np.digitize
:
import numpy as np
a = np.array([1.2,4.6,3.7,11.2,13,5,18.9,0.3,20.0,26.7,1])
np.digitize(a, (0,10,20))
# array([1, 1, 1, 2, 2, 1, 2, 1, 3, 3, 1], dtype=int64)
Upvotes: 2