Skip to main content
 首页 » 编程设计

python之如何将百分比添加到分组数据

2025年05月04日9artech

我正在学习 pandas 并努力解决该模块中数据的组织方式。

我按照教程和文档来处理一项基本任务:状态(“颜色”)在容器(“站点”)中出现的百分比。希望下面的代码能够阐明我拥有的和想要做的事情:

import pandas as pd 
import random 
 
# example of a few first entries generated below:  
# [('site2', 'red'), ('site3', 'red'), ('site1', 'yellow'), ... 
sites = ['site1', 'site2', 'site3'] 
colors = ['red', 'blue', 'yellow'] 
d = [] 
for i in range(0,100): 
    s = ( 
        sites[random.randint(0, 2)], 
        colors[random.randint(0, 2)], 
    ) 
    d.append(s) 
 
df = pd.DataFrame(d) 
df.columns = ['site', 'color'] 
 
grouped = df.groupby(['site', 'color']) 
p = grouped.size() 
 
# the whole group 
print(p) 
# the number of instances of 'blue' in 'site2' 
print(p['site2']['blue']) 
# the total number of instances for 'site2' 
print(p['site2'].sum()) 

输出符合预期:“对于给定站点,显示具有特定颜色的事件数”

site   color  
site1  blue      16 
       red       11 
       yellow     6 
site2  blue       9 
       red       12 
       yellow    12 
site3  blue      11 
       red        7 
       yellow    16 
dtype: int64 
9 
33 

我想要实现的是在分组数据中生成一个新列,其中包含给定站点的给定颜色的百分比。实际上,这就是上面的例子

site1  blue      16 48.4 
       red       11 33.3 
       yellow     6 18.2 
site2  blue       9 27.3 
(...) 

我清楚地知道要进行计算的数字(最后两个输出是示例),但我不知道如何实际循环遍历该组以添加计算出的百分比。

p = grouped.size() 类型是 Series。我可以用计算出的百分比以某种方式丰富它吗?

请您参考如下方法:

这可以通过除以 size 来计算通过sum在索引的第一级:

In [38]: 
 
grouped.size() / grouped.size().sum(level=0) * 100 
Out[38]: 
site   color  
site1  blue      25.714286 
       red       45.714286 
       yellow    28.571429 
site2  blue      32.432432 
       red       43.243243 
       yellow    24.324324 
site3  blue      32.142857 
       red       39.285714 
       yellow    28.571429 
dtype: float64 

当然,由于随机输入值,我上面的输出将与您的不同。

编辑

传递您希望求和的级别的名称更具可读性:

In [46]: 
 
grouped.size() / grouped.size().sum(level='site') * 100 
Out[46]: 
site   color  
site1  blue      25.714286 
       red       45.714286 
       yellow    28.571429 
site2  blue      32.432432 
       red       43.243243 
       yellow    24.324324 
site3  blue      32.142857 
       red       39.285714 
       yellow    28.571429 
dtype: float64