0

please bear with me as this is my first time ask a question.

I have table users with columns

users_id age
0001_a 17
0002_a 18
0003_a 22
0004_a 25
0005_a 40
0006_a 18
0007_a 55
0008_a 41
0009_a 32
0010_a 18
0011_a 43
0012_a 41
0013_a 48

...

the list goes on as the age listed on the table between 17 - 55 i want to grouping the age by if age 17 - 40 category as young-adult else age 41 - 55 category as middle-adult

my python code like this

import pandas as pd

# assume that i successfully import the table users
df = pd.read_csv(user)

# list of age ranges
age_ranges = [18, 40, 50, 100]

# create column age category
df['age_category'] = #this column filled with age category that i defined earlier

i lost, can somebody help me create the code. thank you

My expected output will be something like this

users_id age age_category
0001_a 17 young-adult
0002_a 18 young-adult
0003_a 22 young-adult
0004_a 25 young-adult
0005_a 40 young-adult
0006_a 18 young-adult
0007_a 55 middle-adult
0008_a 41 middle-adult
0009_a 32 young-adult
0010_a 18 young-adult
0011_a 43 middle-adult
0012_a 41 middle-adult
0013_a 48 middle-adult
Rint
  • 1
  • 1
  • Use `df['age_category'] = np.where(df['age'].lt(41), 'young-adult','middle-adult')`, if need set multple groups use `pd.cut` – jezrael Mar 03 '23 at 07:36

0 Answers0