显然有很多方法可以得到同样的结果。我认为布尔索引是最简单的方法,但我也会测试不同方法的速度表现。以下是代码:
s = pd.Series([1, 0, 2], list('abc'), name='s')
方法一
%%timeit
z = np.nonzero(s.values)
pd.Series(s.values[z], s.index.values[z], name=s.name)
The slowest run took 5.23 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 83.9 µs per loop
方法2
%%timeit
s.to_frame().query('s != 0').squeeze()
## -- End pasted text --
1000 loops, best of 3: 1.86 ms per loop
方法 3
%%timeit
s.replace(0, np.nan).dropna().astype(s.dtype)
1000 loops, best of 3: 295 µs per loop
方法4
%%timeit
s[s != 0]
10000 loops, best of 3: 188 µs per loop
令我惊讶的是,方法1似乎是最快的,而方法4紧随其后。也许NumPy操作比Pandas更快,这可能是原因。