gpt4 book ai didi

python - 分组/分类年龄列

转载 作者:行者123 更新时间:2023-11-28 20:32:24 25 4
gpt4 key购买 nike

我有一个数据框 dfdf 有一列 'Ages'

>>> df['年龄']

Age Data

我想对这些年龄段进行分组并创建一个类似这样的新列

If age >= 0 & age < 2 then AgeGroup = Infant
If age >= 2 & age < 4 then AgeGroup = Toddler
If age >= 4 & age < 13 then AgeGroup = Kid
If age >= 13 & age < 20 then AgeGroup = Teen
and so on .....

我如何使用 Pandas 库实现此目的。

我试过这样做

X_train_data['AgeGroup'][ X_train_data.Age < 13 ] = 'Kid'
X_train_data['AgeGroup'][ X_train_data.Age < 3 ] = 'Toddler'
X_train_data['AgeGroup'][ X_train_data.Age < 1 ] = 'Infant'

但是这样做我得到了这个警告

/Users/Anand/miniconda3/envs/learn/lib/python3.7/site-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy This is separate from the ipykernel package so we can avoid doing imports until /Users/Anand/miniconda3/envs/learn/lib/python3.7/site-packages/ipykernel_launcher.py:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

如何避免此警告并以更好的方式做到这一点。

最佳答案

使用pandas.cut带参数 right=False 表示不包括 bins 的最右边缘:

X_train_data = pd.DataFrame({'Age':[0,2,4,13,35,-1,54]})

bins= [0,2,4,13,20,110]
labels = ['Infant','Toddler','Kid','Teen','Adult']
X_train_data['AgeGroup'] = pd.cut(X_train_data['Age'], bins=bins, labels=labels, right=False)
print (X_train_data)
Age AgeGroup
0 0 Infant
1 2 Toddler
2 4 Kid
3 13 Teen
4 35 Adult
5 -1 NaN
6 54 Adult

最后用于替换缺失值使用 add_categoriesfillna :

X_train_data['AgeGroup'] = X_train_data['AgeGroup'].cat.add_categories('unknown')
.fillna('unknown')
print (X_train_data)
Age AgeGroup
0 0 Infant
1 2 Toddler
2 4 Kid
3 13 Teen
4 35 Adult
5 -1 unknown
6 54 Adult

bins= [-1,0,2,4,13,20, 110]
labels = ['unknown','Infant','Toddler','Kid','Teen', 'Adult']
X_train_data['AgeGroup'] = pd.cut(X_train_data['Age'], bins=bins, labels=labels, right=False)

print (X_train_data)
Age AgeGroup
0 0 Infant
1 2 Toddler
2 4 Kid
3 13 Teen
4 35 Adult
5 -1 unknown
6 54 Adult

关于python - 分组/分类年龄列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52753613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com