Trying to create grouped variable in python

China☆狼群 提交于 2019-12-19 11:42:47

问题


I have a column of age values that I need to convert to age ranges of 18-29, 30-39, 40-49, 50-59, 60-69, and 70+:

For an example of some of the data in df 'file', I have:

and would like to get to:

I tried the following:

file['agerange'] = file[['age']].apply(lambda x: "18-29" if (x[0] > 16
                                       or x[0] < 30) else "other")

I would prefer not to just do a groupby since the bucket sizes aren't uniform but I'd be open to that as a solution if it works.

Thanks in advance!


回答1:


It looks like you are using the Pandas library. They include a function for doing this: http://pandas.pydata.org/pandas-docs/version/0.16.0/generated/pandas.cut.html

Here's my attempt:

import pandas as pd

ages = pd.DataFrame([81, 42, 18, 55, 23, 35], columns=['age'])

bins = [18, 30, 40, 50, 60, 70, 120]
labels = ['18-29', '30-39', '40-49', '50-59', '60-69', '70+']
ages['agerange'] = pd.cut(ages.age, bins, labels = labels,include_lowest = True)

print(ages)

   age agerange
0   81      70+
1   42    40-49
2   18    18-29
3   55    50-59
4   23    18-29
5   35    30-39



回答2:


Wouldn't a nested loop be the simplest solution here?

import random
ages = [random.randint(18, 100) for _ in range(100)]
age_ranges = [(18,29), (30,39), (40,49), (50,59), (60,69),(70,)]

for a in ages:
        for r in age_ranges:
                if a >= r[0] and (len(r) == 1 or a < r[1]):
                        print a,r
                        break



回答3:


You can use itertools.groupby using // 10 as the key function.

In [10]: ages = [random.randint(18, 99) for _ in range(100)]

In [11]: [(key, list(group)) for (key, group) in itertools.groupby(sorted(ages), key=lambda x: x // 10)]
Out[11]: 
[(1, [18]),
 (2, [20, 21, 21, 22, 23, 24, 25, 26, 26, 26, 27, 27, 28]),
 (3, [30, 30, 32, 32, 34, 35, 36, 37, 37]),
 (4, [41, 42, 42, 43, 43, 44, 45, 47, 48]),
 (5, [50, 51, 52, 53, 54, 55, 56, 56, 56, 56, 57, 58, 58, 58, 58]),
 (6, [60, 61, 62, 62, 62, 65, 65, 66, 66, 66, 66, 67, 69, 69, 69]),
 (7, [71, 71, 72, 72, 73, 75, 75, 77, 77, 78]),
 (8, [83, 83, 83, 83, 84, 84, 85, 86, 86, 87, 87, 88, 89, 89, 89]),
 (9, [91, 91, 92, 92, 93, 94, 97, 97, 98, 98, 99, 99, 99])]

Remember that groupby needs sorted data, though, so sort first. Or do it manually, using a dictionary and a loop.

In [14]: groups = collections.defaultdict(list)

In [15]: for x in ages:
   ....:     groups[x//10].append(x)

In [16]: groups
Out[16]: defaultdict(<type 'list'>, {1: [18], 
             2: [26, 28, 21, 20, 26, 24, 21, 27, 25, 23, 27, 26, 22], 
             3: [37, 30, 32, 32, 35, 30, 36, 37, 34], 
             4: [45, 42, 43, 41, 47, 43, 48, 44, 42], 
             5: [52, 56, 58, 55, 58, 51, 58, 58, 57, 56, 53, 56, 50, 54, 56], 
             6: [69, 65, 62, 61, 65, 66, 66, 62, 69, 66, 67, 66, 60, 62, 69], 
             7: [71, 77, 71, 72, 77, 73, 78, 72, 75, 75], 
             8: [87, 83, 84, 86, 86, 83, 83, 87, 85, 83, 89, 88, 84, 89, 89], 
             9: [99, 92, 99, 98, 91, 94, 97, 92, 98, 97, 91, 93, 99]})

For more complex grouping, you can make the key function arbitrarily complicated. E.g., for putting everybody at the age of 70 and above into one group, use lambda x: min(x // 10, 7). This works for both approaches. You can even convert the key to a string if you prefer that:

In [23]: keyfunc = lambda x: "{0}0-{0}9".format(x//10) if x < 70 else "70+"
In [24]: [(key, list(group)) for (key, group) in itertools.groupby(sorted(ages), key=keyfunc)]
Out[24]: 
[('10-19', [18]),
 ('20-29', [20, 21, 21, 22, 23, 24, 25, 26, 26, 26, 27, 27, 28]),
 ('30-39', [30, 30, 32, 32, 34, 35, 36, 37, 37]),
 ('40-49', [41, 42, 42, 43, 43, 44, 45, 47, 48]),
 ('50-59', [50, 51, 52, 53, 54, 55, 56, 56, 56, 56, 57, 58, 58, 58, 58]),
 ('60-69', [60, 61, 62, 62, 62, 65, 65, 66, 66, 66, 66, 67, 69, 69, 69]),
 ('70+',   [all the rest]]



回答4:


A friend came up with this response offline that works: def age_buckets(x): if x < 30: return '18-29' elif x < 40: return '30-39' elif x < 50: return '40-49' elif x < 60: return '50-59' elif x < 70: return '60-69' elif x >=70: return '70+' else: return 'other'

file['agerange'] = file.age.apply(age_buckets)

Thanks to everyone who took a crack at this!



来源:https://stackoverflow.com/questions/34165876/trying-to-create-grouped-variable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!