Ger*_*ges 3 python series pandas
我有一个这样的系列:
s = pd.Series([0, 0, 0, 1, 2, 3])
s
Out[00]:
0 0
1 0
2 0
3 1
4 2
5 0
dtype: int64
Run Code Online (Sandbox Code Playgroud)
我想计算该系列中开始和尾随零的数目。所以在这种情况下,我应该以3开始,因为在第一个非零数字之前有3个零,而在尾随零是1,因为在最后一个非零之后的序列尾部有一个零。
我到目前为止所做的
到目前为止,我的解决方案是使用累计和
sum(s.cumsum() == 0) # begenning
np.sum(np.cumsum(s.values[::-1]) == 0) # trailing
Run Code Online (Sandbox Code Playgroud)
但这对于非常大的序列(尤其是尾随零位计算)而言非常慢,我需要一种替代方法。
用途numpy.nonzero:
import numpy as np
n_rows = len(s)
indices = np.nonzero(s)[0]
if indices.size>0:
head = indices[0]
trail = n_rows - indices[-1] -1
else:
head, trail = n_rows, n_rows
print(head, trail)
Run Code Online (Sandbox Code Playgroud)
输出:
3 1
Run Code Online (Sandbox Code Playgroud)
基准测试(快15倍):
s = np.zeros(100000)
s[30000:50000] +=1
s = pd.Series(s)
%%timeit
n_rows = len(s)
indices = np.nonzero(s)[0]
if indices.size>0:
head = indices[0]
trail = n_rows - indices[-1] -1
else:
head, trail = n_rows, n_rows
# 661 µs ± 8.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
sum(s.cumsum() == 0) # begenning
np.sum(np.cumsum(s.values[::-1]) == 0) # trailing
# 9.39 ms ± 163 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Run Code Online (Sandbox Code Playgroud)
测试和编辑:在全零和非零情况下都可以正常工作。