pandas数据帧中范畴列的概率

2024-05-20 15:27:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的熊猫数据帧

0 Age color country
1  23  red    Us
2  25  black  UK
3  19  blue   UK
4  10  red    India
5  15  red    UK

我要做的是在“颜色”列中找到每个类别的概率,并得到如下结果:

^{pr2}$

如何在元组中找到概率? 像这样:

0 color color_pro
1 red    0.6 
2 black  0.2
3 blue   0.2
4 red    0.6
5 red    0.6

我想得到另一个元组的概率:

0 color_pro
1  0.6 
2  0.2
3  0.2
4  0.6
5  0.6

Tags: 数据age颜色bluered概率类别country
2条回答

使用groupbycount获得值,然后计算比例。在

df['color_pro'] = df.groupby('color')['color'].transform('count')
df['color_pro'] = df['color_pro'].map(lambda x : x/len(df))

或者,把这两条线连在一起,我们也能做到。在

^{2}$

相关问题 更多 >