2017-07-27 67 views
2
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.熊猫计数值占总数的50%

最初我正在用count计算条件,但是我到了死胡同。

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

不过,我得到以下错误: “numpy.int32”对象有没有属性“其中” 任何关于我哪里错了的想法?

干杯,布兰登

+0

您的操作顺序是错误的。 'test ['percentage']。count()'统计“百分比”列中的所有项目。没有从那里去的地方。 –

回答

2

如果要算你为了多少行需要获得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%,这是我答案中的第一行代码。

+0

谢谢Miriam,它的功能就像一个魅力。 – Bjc51192

+0

不客气:) –

+0

你选择使用np.sum()的任何原因? – Bjc51192

0

即使Miriam Farber(upvoted)已经完美地回答了这个问题,我喜欢张贴替代品。看起来它也快很多。

这里是(出口到列表并使用itertools take cumum)。

import itertools 
seq = test['percentage'].tolist() 
len(list(itertools.takewhile(lambda x: x <= 50, itertools.accumulate(seq)))) 

时机二:

%timeit len(list(itertools.takewhile(lambda x: x <= 50, itertools.accumulate(test['percentage'].tolist())))) 
#18.3 µs per loop 
%timeit np.sum(test['percentage'].cumsum()<=50) 
#335 µs per loop 

有趣的是我得到这两项业务之间的因子8更快:

%timeit test['percentage'].cumsum() 
%timeit list(itertools.accumulate(test['percentage'].tolist()))