Creating a new column in a Pandas DF that groups by age category

Viewed 1996

I am new to coding so I apologize for asking what could be a dumb and easy question. I have searched the web and read documents but I could not find an answer and after 4 hours I am hoping for guidance.

I have a Pandas DataFrame named "data". "data" has a column for age with a ton of different ages. I would like to isolate certain age groups for different types of analysis. Like how many hours young adults work out (in an snsplot).

In my head, the best way to tackle this would have a column added in "data" that has the age_group. With the age group being assigned some logic (like in the picture attached)

I could be wrong, like I said I am only a few months into just learning python. Thanks for any help given. I plan on doing this on a few more columns once I know how.

I tried to create variables based on the age groups I was looking for

teenage = data[data['age']<=19]
yadult = data[data['age'].between(20,24)]
adult = data[data['age'].between(25,39)]
older_adult = data[data['age']>39]

That did not work when I tried to use the variable in a snsplot.

So I then tried this:

data['yadult'] = data[data['age'].between(20,24)] 

but got an error: "ValueError: The wrong number of items passed 9, placement implies 1


The end goal here is to have the "data" DataFrame with a brand new column with the age group. Like below.

Product Age Gender Education .... age_group
TM195 18 Male 14 ...... teenager
TM195 27 Male 16 ...... adult

.csv data layout :

The buckets I am trying to create:

1 Answers

With the following code, you can assign a new column age_group according to age:

data.loc[data['age']<=19, 'age_group'] = 'teenage'
data.loc[data['age'].between(20,24), 'age_group'] = 'yadult'
data.loc[data['age'].between(25,39), 'age_group'] = 'adult'
data.loc[data['age']>39, 'age_group'] = 'older_adult'
Related