python 连续比较运算_python – 如何计算DataFrame中连续TRUE的数量?

我们基本上会利用两个哲学 –

Catching shifts on compared array和

Offsetting each column results so that we could vectorize it.

因此,有了这个意图,这是实现预期结果的一种方法 –

def maxisland_start_len_mask(a, fillna_index = -1, fillna_len = 0):

# a is a boolean array

pad = np.zeros(a.shape[1],dtype=bool)

mask = np.vstack((pad, a, pad))

mask_step = mask[1:] != mask[:-1]

idx = np.flatnonzero(mask_step.T)

island_starts = idx[::2]

island_lens = idx[1::2] - idx[::2]

n_islands_percol = mask_step.sum(0)//2

bins = np.repeat(np.arange(a.shape[1]),n_islands_percol)

scale = island_lens.max()+1

scaled_idx = np.argsort(scale*bins + island_lens)

grp_shift_idx = np.r_[0,n_islands_percol.cumsum()]

max_island_starts = island_starts[scaled_idx[grp_shift_idx[1:]-1]]

max_island_percol_start = max_island_starts%(a.shape[0]+1)

valid = n_islands_percol!=0

cut_idx = grp_shift_idx[:-1][valid]

max_island_percol_len = np.maximum.reduceat(island_lens, cut_idx)

out_len = np.full(a.shape[1], fillna_len, dtype=int)

out_len[valid] = max_island_percol_len

out_index = np.where(valid,max_island_percol_start,fillna_index)

return out_index, out_len

样品运行 –

# Generic case to handle all 0s columns

In [112]: a

Out[112]:

array([[False, False, False],

[False, False, False],

[ True, False, False],

[ True, False, True],

[False, False, False],

[ True, False, True],

[ True, False, False],

[ True, False, True],

[False, False, True],

[ True, False, False]])

In [117]: starts,lens = maxisland_start_len_mask(a, fillna_index=-1, fillna_len=0)

In [118]: starts

Out[118]: array([ 5, -1, 7])

In [119]: lens

Out[119]: array([3, 0, 2])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值