Home > Net >  How to assign a number if a value falls within a range in pandas
How to assign a number if a value falls within a range in pandas

Time:08-09

I have the following pd.Series:

amount = pd.Series([25.35, 30.0, 23.13, 100.0, 75.0])

I want to assing a number if a value in a series falls within a range. In essence, for every 25 I want to assign a 3. For example:

25 -> 3

50 -> 6

75 -> 9 and so on.

I want the output to look something like this.

data = {'amount': {0: 25.35, 1: 30.0, 2: 23.13, 3: 100.0, 4: 75.0},
 'number': {0: 3, 1: 3, 2: 0, 3: 12.0, 4: 9}}
expected = pd.DataFrame.from_dict(data)
    amount  number
0   25.35   3.0
1   30.00   3.0
2   23.13   0.0
3   100.00  12.0
4   75.00   9.0

I tried using the following function, expecting to apply to the target column using the .apply() method, but raises the error SyntaxError: invalid syntax for line elif >= 50 x < 75:

amount = pd.Series([25.35, 30.0, 23.13, 100.0, 75.0])
def miles(amount):
    for x in amount:
        if 25 >= x < 50:
            return int(3)
        elif >= 50 x < 75:
            return int(6)
        elif >= 75 x < 100:
            return int(9)
        elif >= 100 x < 125:
            return int(12)
        else:
            pass

Any help is appreciated. Thank you!

CodePudding user response:

Sounds like you want the integer (floor) division of your series with 25:

3 * (amount // 25)

For the full DF:

>>> df = pd.DataFrame({'amount': amount, 'number': 3 * (amount//25)})
>>> df
   amount  number
0   25.35     3.0
1   30.00     3.0
2   23.13     2.0
3  100.00    12.0
4   75.00     9.0

CodePudding user response:

Pandas data frame has its own // (floor division) arithmetic operator.

So the complete code :

import pandas as pd
 
# just creating your initial dataframe :

data = {'Amount': [25.35, 30.0, 23.13, 100.0, 75.0]}
df = pd.DataFrame(data)

#adding the Number column to this data frame with //: 

df['Number'] = 3*df.floordiv(25)

print(df)       # or just df if using a notebook

will give you a tidy result of :

   Amount  Number
0   25.35     3.0
1   30.00     3.0
2   23.13     0.0
3  100.00    12.0
4   75.00     9.0
  • Related