Skip to main content
 首页 » 编程设计

python之pandas 计算占总数 50% 的值

2024年10月01日7zfyouxi

test={'price':[1,3,4,2,1,2,1,6]} 
test=pd.DataFrame(test) 
test=test.sort_values('price', ascending=False) 
sum_test=test.sum() 
test['percentage']=(test/sum_test)*100 

我想做的是计算百分比列中总和为 50% 的值的数量。唯一的条件是价格列必须降序排列。在提供的示例数据中,正确的输出为 2。

最初我正在考虑使用带计数的条件,但我走到了死胡同。

test['percentage'].count().where(test['percentage'].sum()<=50,0) 

但是,我收到以下错误: 'numpy.int32' 对象没有属性 'where' 想知道我哪里出错了吗?

干杯,布兰登

请您参考如下方法:

如果您想计算达到 50% 所需的行数,可以这样做:

np.sum(test['percentage'].cumsum()<=50) 

这会给你 2。注意

test['percentage'].cumsum() 

给予

7     30.0 
2     50.0 
1     65.0 
3     75.0 
5     85.0 
0     90.0 
4     95.0 
6    100.0 
Name: percentage, dtype: float64 

所以上面的结果是百分比的累计总和。然后你可以统计其中有多少小于50%,这是我答案中的第一行代码。