0

I would like to change values in a column based on its range, how should I do it?

here is a sample dataset

Id    Number

0      2
1      2
2      2
3      2
4     23
5      6
6     16
7     10
8     15
9      8
10     6
11     9
12     1

Here is the range:

   if number >=6 and <12 then 1
   if number ==12, then 2
   if number >=13 and <=17, then 3
   if number >17 and <=22 then 4
   else 5

How should I do it?

almo
  • 561
  • 2
  • 16

1 Answers1

1

I'd use NumPy's select():

import numpy as np

np.select([
    df.Number.between(6, 11),
    df.Number == 12,
    df.Number.between(13, 17),
    df.Number.between(18, 22)],
    [1, 2, 3, 4], 5)
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Zwick many thanks. I just ran it. The number did not change. I will try it again. Thank you. Will let you know, if it does not work – almo Sep 17 '20 at 11:00
  • @almo: The code I wrote does not modify the data structure, it produces a new array which you need to store somewhere. P.S. why do people always leave the "n" out of my name? – John Zwinck Sep 17 '20 at 11:01
  • @thanks, now it shows. Is there any way to use replace, map, etc? Just would like to see if there is any other approaches to solve it. I accepted your answer:) – almo Sep 17 '20 at 11:03