尝试在python中创建分组变量

Jos*_*osh 4 python ipython ipython-notebook

我有一列年龄值,我需要将其转换为 18-29、30-39、40-49、50-59、60-69 和 70+ 的年龄范围:

对于 df 'file' 中的一些数据的示例,我有:

在此处输入图片说明

并希望前往:

在此处输入图片说明

我尝试了以下方法:

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

我宁愿不只是进行分组,因为桶的大小不统一,但如果可行,我愿意将其作为解决方案。

提前致谢!

小智 7

看起来您正在使用 Pandas 库。它们包括执行此操作的函数:http : //pandas.pydata.org/pandas-docs/version/0.16.0/generated/pandas.cut.html

这是我的尝试:

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
Run Code Online (Sandbox Code Playgroud)