Pavan
Pavan

Reputation: 391

How can I label the numpy array based on values?

I have a numpy array of certain values ([5,6,7,8,10,11,12,14]); I want to label each value as:

  1. 'N' if value is less than or equal 10

  2. '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

Answers (2)

ayiyi
ayiyi

Reputation: 127

  1. for loop iter the tmp list;
  2. each element looped in the tmp list, will be judged by if ... first, match if ... then output 'Y' in new list which created by list comprehensive.
  3. does not match if ... then output 'N' in new list which created by list comprehensive.

Use list comprehensive with sentence if ...else.. just like picture below:

Upvotes: 0

Wolph
Wolph

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

Related Questions