0

I have an array with three kinds of value:

a = np.array([150, 50, 200, 50, 150])

How do I replace the values with ordered integers so that 50's are replaced with 0's, 150's with 1's, and 200's with 2's like so:

[1, 0, 2, 0, 1]?

Thank you.

3
  • by ordered, do you mean the rank of the element in a sorted series? Commented Aug 2, 2019 at 10:36
  • I would try something like order the list (asc) and find the position of each element in the original lit on the ordered list. Commented Aug 2, 2019 at 10:37
  • Try with: np.floor(a / 100).astype(int) Commented Aug 2, 2019 at 10:45

3 Answers 3

2

You can just use integer division for your requirement.

a = a // 100
>>> a
array([1, 0, 2, 0, 1], dtype=int32)
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, it does work for this numbers. Not sure it's what the user wanted.
Neither am I. OP has only given explicit examples, not any logic, hence hard to infer.
2

You can use np.vectorize if you have to map different numbers to different keys

Ex:

a = np.array([150, 50, 200, 50, 150, 300])
check_value = {50:0, 150: 1, 200:2}

print(np.vectorize(lambda x: check_value.get(x, x))(a))

Output:

[  1   0   2   0   1 300]

Comments

0

Assuming that your intention is to replace elements with their corresponding rank when sorted..

# sample data
a = np.array([150, 50, 200, 50, 150])

# get the rank of the elment
rank_list = np.unique(np.sort(a))

# get the index of the element in the rank list
output = [np.where(rank_list==x)[0][0] for x in a]

output will give you [1, 0, 2, 0, 1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.