Reputation: 391
I have a numpy array of certain values ([5,6,7,8,10,11,12,14]); I want to label each value as:
'N' if value is less than or equal 10
'Y' if value is greater than 10
My output will be an array/list that has the values: ['N','N','N','N','N','Y','Y','Y']
I am new to python and immediately need the solution for a project. Kindly help me. Please don't give negative points because i cannot ask any more questions.
Upvotes: 0
Views: 637
Reputation: 127
Upvotes: 0
Reputation: 80061
There are many ways of doing this. Here are a few options:
In [1]: import numpy
In [2]: x = numpy.array([5,6,7,8,10,11,12,14])
In [3]: x
Out[3]: array([ 5, 6, 7, 8, 10, 11, 12, 14])
In [4]: x > 10
Out[4]: array([False, False, False, False, False, True, True, True], dtype=bool)
In [5]: ['Y' if y > 10 else 'N' for y in x]
Out[5]: ['N', 'N', 'N', 'N', 'N', 'Y', 'Y', 'Y']
In [6]: [{True: 'Y', False: 'N'}[y] for y in x > 10]
Out[6]: ['N', 'N', 'N', 'N', 'N', 'Y', 'Y', 'Y']
You could also use map
or something of course :)
Upvotes: 1