python统计正数个数,计算Python数组中的连续正值

I'm trying to count consecutive up days in equity return data - so if a positive day is 1 and a negative is 0, a list y=[0,0,1,1,1,0,0,1,0,1,1] should return z=[0,0,1,2,3,0,0,1,0,1,2].

I've come to a solution which is neat in terms of number of lines of code, but is very slow:

import pandas

y=pandas.Series([0,0,1,1,1,0,0,1,0,1,1])

def f(x):

return reduce(lambda a,b:reduce((a+b)*b,x)

z=pandas.expanding_apply(y,f)

I'm guessing I'm looping through the whole list y too many times. Is there a nice Pythonic way of achieving what I want while only going through the data once? I could write a loop myself but wondering if there's a better way.

Thanks!

解决方案

why the obsession with the ultra-pythonic way of doing things? readability + efficiency trumps "leet hackerz style."

I'd just do it like so:

a = [0,0,1,1,1,0,0,1,0,1,1]

b = [0,0,0,0,0,0,0,0,0,0,0]

for i in range(len(a)):

if a[i] == 1:

b[i] = b[i-1] + 1

else:

b[i] = 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值