1

I am trying to transform the age columns of a pandas dataframe by applying apply function. how to make below code work or is there a more pythonic way way to do this.

cps=(cps.assign(Age_grp_T=cps['age'].apply(lambda x:{x>=71:'Tradionalists',
                                                  71>x>=52:'Baby Boomers',
                                                  52>x>=46:'Generation X',
                                                  46>x>=16:'Millennials'}.get(x, ' ')))

2 Answers 2

1

i would use cut() function for that:

In [663]: labels=[' ','Millennials','Generation X','Baby Boomers','Tradionalists']

In [664]: a['category']  = pd.cut(a['age'], bins=[1, 16,46,52,71, 200],labels=labels)

In [665]: a
Out[665]:
    age      category
0    29   Millennials
1    65  Baby Boomers
2    68  Baby Boomers
3    18   Millennials
4    29   Millennials
5    58  Baby Boomers
6    15
7    67  Baby Boomers
8    21   Millennials
9    17   Millennials
10   19   Millennials
11   39   Millennials
12   64  Baby Boomers
13   70  Baby Boomers
14   33   Millennials
15   27   Millennials
16   54  Baby Boomers
17   60  Baby Boomers
18   23   Millennials
19   65  Baby Boomers
20   63  Baby Boomers
21   36   Millennials
22   53  Baby Boomers
23   29   Millennials
24   66  Baby Boomers
Sign up to request clarification or add additional context in comments.

Comments

0

I have found one more way to do this but thanks MaxU your answers works too

cps=(cps.assign(Age_grp_T=np.where(cps['age']>=71,"Tradionalists",
                      np.where(np.logical_and(71>cps['age'],cps['age']>=52),"Baby Boomers",
                      np.where(np.logical_and(52>cps['age'],cps['age']>=46),"Generation X",
                      np.where(np.logical_and(46>cps['age'],cps['age']>=16),"Millennials",-99))))
           )

I wonder which one is more efficient?

1 Comment

compare it using timeit - so you'll see which one is more efficient ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.