我有一个这样的系列:
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
我想计算该系列中开头和结尾零的数目。因此,在这种情况下,我应该以3开始,因为在第一个非零数字之前有3个零,而在尾随零是1,因为在最后一个非零之后的序列尾部有一个零。
我到目前为止所做的
到目前为止,我的解决方案是使用累计和
sum(s.cumsum() == 0) # begenning
np.sum(np.cumsum(s.values[::-1]) == 0) # trailing
但是对于非常大的序列,这尤其慢,尤其是尾随零的计算,我需要一种替代方法。
答案 0 :(得分:5)
使用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)
输出:
3 1
基准测试(快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)
经过测试和编辑:适用于全零和非零情况。
答案 1 :(得分:0)
出于好奇,我检查了另一种普通的熊猫方法,并针对具有1.000.000行的系列测试了所有三个版本。
事实证明,克里斯的版本比原始版本快18倍,比我的熊猫版本快2倍。但请注意,我的pandas版本在以下假设下工作:索引是从0开始的连续整数索引(因此.iloc[i]
的返回结果与.loc[i]
相同),而chris'版本与索引。
def test_pandas_version(s):
truth=(s!=0)
idxs= truth.index.where(truth, np.NaN)
#first_one=idxs.min()
first_one=truth.idxmax()
last_one= idxs.max()
whole_len= truth.shape[0]
prefix_len= first_one
suffix_le= whole_len - last_one - 1
if prefix_len == np.NaN:
prefix_len= whole_len
suffix_len= 0
return (prefix_len, suffix_le)
def test_original_version(s):
suffix_len = np.sum(np.cumsum(s.values[::-1]) == 0) # begenning
prefix_len= sum(s.cumsum() == 0)
return (prefix_len, suffix_le)
def test_np_version(s):
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
return (head, trail)
for func in [test_np_version, test_pandas_version, test_original_version]:
before= datetime.now()
for i in range(100):
result= func(s1)
after= datetime.now()
time_diff= (after-before).total_seconds()
print(f'result for {func.__name__} was {result} in {time_diff} seconds')