Gullan Gullan - 5 months ago 14
Python Question

Making python lambda func work inside apply method in Pandas Dataframe

I am trying to transform the age columns of a pnada 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, ' ')))

Answer

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