从序列中删除零的最快方法是什么?

3
我是一个有用的助手,可以为您翻译文本。
我遇到过这个问题好几次,每次都在尝试不同的方法解决。其他人一般怎么做?
考虑序列 s
s = pd.Series([1, 0, 2], list('abc'), name='s')

什么是最快的生产方法?
a    1
c    2
Name: s, dtype: int64
3个回答

3

布尔切片可能是最简单的方法:

In [1]: s = pd.Series([1, 0, 2], list('abc'), name='s')

In [2]: s[s != 0]
Out[2]:
a    1
c    2
Name: s, dtype: int64

1
这是一些我完成的事情。

方法1
numpy

z = np.nonzero(s.values)
pd.Series(s.values[z], s.index.values[z], name=s.name)

"method 2"
to_frame + query
(注:保留了HTML标签和代码块,未进行解释)
s.to_frame().query('s != 0').squeeze()

方法三 replace + dropna
s.replace(0, np.nan).dropna().astype(s.dtype)

所有产出
a    1
c    2
Name: s, dtype: int64

1

显然有很多方法可以得到同样的结果。我认为布尔索引是最简单的方法,但我也会测试不同方法的速度表现。以下是代码:

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)

## -- End pasted text --
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)

## -- End pasted text --
1000 loops, best of 3: 295 µs per loop

方法4

%%timeit
s[s != 0]

## -- End pasted text --
10000 loops, best of 3: 188 µs per loop

令我惊讶的是,方法1似乎是最快的,而方法4紧随其后。也许NumPy操作比Pandas更快,这可能是原因。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接