Issue
I have a numpy array of 0-23
numbers, and I was testing numpy select function there. where the conditions are:
- num <= 10
- num > 10
choices are:
- A
- B
Its pretty simple approach like this:
import numpy as np
arr = np.arange(24)
cond = [
arr <= 10,
arr > 10
]
choices = ['A', 'B']
result = np.select(cond, choices)
print(result)
I want to know that can I put else condition in the select function, because if you look at the 2nd condition then its basically the else condition. If there are multiple conditions then it can become really difficult to put all the condition in that list. Can anyone please help?
Solution
numpy.select
has another parameter called default
that is similar to else
coniditon i.e. if none of the conditions are True
, the value passed to default
will be used, so the above condition and choice lists can be reduced to a single length lists
import numpy as np
arr = np.arange(24)
cond = [arr <= 10] #Only one condition representing if
choices = ['A'] #Only one value if condition is True
result = np.select(cond, choices, default='B') # default as B for else part
print(result)
['A' 'A' 'A' 'A' 'A' 'A' 'A' 'A' 'A' 'A' 'A' 'B' 'B' 'B' 'B' 'B' 'B' 'B'
'B' 'B' 'B' 'B' 'B' 'B']
Answered By - ThePyGuy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.