使用浮点切片列表切片pandas系列

1 投票
1 回答
1205 浏览
提问于 2025-04-27 23:32

我有一个很大的 pandas Series,里面的索引是浮点数。

比如说:

s = pandas.Series([1,2,3,4,5], index=[1.0,2.0,3.0,4.0,5.0])

不过里面有十万行数据。

我想把多个切片合并成一个子集的 Series。目前我是在先建立一个切片的列表,然后再把它们拼接在一起。

比如:

intervals = [(1,2), (4,8)]
s2 = pandas.concat([s.ix[start:end] for start, end in intervals])

这里的 intervals 是一个通常有10到20个条目的列表。

但是这样做 很慢。实际上,这一行代码占用了我程序执行时间的62%,而我的程序在处理一小部分数据(大约是整个数据集的1/2000)时,已经花了大约30秒。

有没有人知道更好的方法来做到这一点?

暂无标签

1 个回答

0

这段话的意思是,我们需要用一些聪明的方式来利用 numpyarray 广播功能,来检查 index 中的每个值,看看它是否在 interval 列表中的每个区间之间(这个区间的两端是开区间,也就是说要满足 >=low_end 和 <=high_end 的条件):

In [158]:
import numpy as np
def f(a1, a2):
    return (((a1 - a2[:,:,np.newaxis])).prod(1)<=0).any(0)
In [159]:

f(s.index.values, np.array(intervals))
Out[159]:
array([ True,  True, False,  True,  True], dtype=bool)
In [160]:

%timeit s.ix[f(s.index.values, np.array(intervals))]
1000 loops, best of 3: 212 µs per loop
In [161]:

%timeit s[f(s.index.values, np.array(intervals))]
10000 loops, best of 3: 177 µs per loop
In [162]:

%timeit pd.concat([s.ix[start: end] for start, end in intervals])
1000 loops, best of 3: 1.64 ms per loop

结果:

1    1
2    2
4    4
5    5
dtype: int64

撰写回答