Pandas中的分箱
假设你有一个Pandas的数据表,里面有一些数据:
"Age","Gender","Impressions","Clicks","Signed_In"
36,0,3,0,1
73,1,3,0,1
30,0,3,0,1
49,1,3,0,1
47,1,11,0,1
现在,我想要根据年龄为每一行创建一个新的分类变量(也就是新的一列),这个新列会显示每个人的年龄范围。比如,对于某一行数据:
36,0,3,0,1
我希望新列能显示'35到45岁之间'。
最终的数据记录应该看起来像这样:
36,0,3,0,1,'Between 35 and 45'
1 个回答
3
你应该准备一组示例数据,这样可以帮助别人更好地回答你的问题:
import pandas as pd
import numpy as np
d = {'Age' : [36, 73, 30, 49, 47],
'Gender' : [0, 1, 0, 1, 1],
'Impressions' : [3, 3, 3, 3, 11],
'Clicks' : [0, 0, 0, 0, 0],
'Signed_In' : [1, 1, 1, 1, 1]}
df = pd.DataFrame(d)
这样别人就可以轻松地复制和粘贴,而不需要手动去创建你遇到的问题。
numpy的round函数可以对负的小数位进行四舍五入:
df['Age_rounded'] = np.round(df['Age'], -1)
Age Clicks Gender Impressions Signed_In Age_rounded
0 36 0 0 3 1 40
1 73 0 1 3 1 70
2 30 0 0 3 1 30
3 49 0 1 3 1 50
4 47 0 1 11 1 50
然后你可以把一个字典应用到这些值上:
categories_dict = {30 : 'Between 25 and 35',
40 : 'Between 35 and 45',
50 : 'Between 45 and 55',
70 : 'Between 65 and 75'}
df['category'] = df['Age_rounded'].map(categories_dict)
Age Clicks Gender Impressions Signed_In Age_rounded category
0 36 0 0 3 1 40 Between 35 and 45
1 73 0 1 3 1 70 Between 65 and 75
2 30 0 0 3 1 30 Between 25 and 35
3 49 0 1 3 1 50 Between 45 and 55
4 47 0 1 11 1 50 Between 45 and 55