-4

I have a set of numbers that I would like to change to a string based on if the number is within a given range.

Given df (these are int, not strings):

tempList
10
98
33
65
254

Ranges:

<40 = "Cold Temp"
41-80 = "Good Temp"
>81 = "Hot Temp"

Desired Output:

tempList
Cold Temp
Hot Temp
Cold Temp
Good Temp
Hot Temp
Wheaty
  • 1
  • 1

3 Answers3

0
df['tempList'].apply(lambda x: "Cold Temp" if x < 40 else ("Good Temp" if x < 81 else "Hot Temp"))
BloomShell
  • 833
  • 1
  • 5
  • 20
0

You can use pd.cut here.

df['Ranges'] = pd.cut(x=df['tempList'],
                      bins=[0,40,80,np.inf], 
                      labels=['Cold Temp', 'Good Temp', 'Hot Temp'])
print(df)
   tempList     Ranges
0        10  Cold Temp
1        98   Hot Temp
2        33  Cold Temp
3        65  Good Temp
4       254   Hot Temp
Rabinzel
  • 7,757
  • 3
  • 10
  • 30
0

we can use np.where

import pandas as pd
import numpy as np
df = pd.DataFrame(columns=['temperature'])
df['temperature'] = [10,98,33,65,254]
    
df['temperature'] = np.where(df['temperature']<40, 'cold', np.where(df['temperature']<80, 'good', 'hot'))
    
print(df)
AltunE
  • 375
  • 3
  • 10