小编典典

试图在python中创建分组变量

python

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

对于df“文件”中某些数据的示例,我有:

在此处输入图片说明

并希望到达:

在此处输入图片说明

我尝试了以下方法:

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

我宁愿不只是进行分组,因为存储桶的大小不是统一的,但如果可行的话,我会对此开放。

提前致谢!


阅读 241

收藏
2021-01-20

共1个答案

小编典典

看来您正在使用Pandas库。它们包括执行此操作的功能:http : //pandas.pydata.org/pandas-
docs/version/0.16.0/genic/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
2021-01-20