让我从一小部分背景开始.
我有Spheres,一个大熊猫DataFrame,在时间内具有多个球体的位置和半径.
球体使用标签分组.多个球体可以共享相同的标签,同一个球体可以随时间具有多个标签.
而且,这些领域可以相互重叠,我想对每个组进行量化.
所以我写了一个函数compute_cov来计算一些代表性的数量,我可以使用它:
Spheres.groupby(by=["Time", "Label"]).apply(compute_cov)
我面临的问题是,这对我所需的速度来说太慢了(实际数据大约增加了1000倍,这已经花了1.3秒).
根据cProfile,大约82%的时间是在groupby中花费的,而在compute_cov中花费的时间是13%,其中10%是由group.values花费的.
我已经发现,如果我将“时间”索引转换为自己的列并进行排序:
Spheres = Spheres.reset_index(0).sort_values(["Time",'Label'])
groubpby要快得多(~5x,现在需要258ms).所以现在主要的问题是group.values现在需要65%的时间.
关于如何让它更快的任何想法?
def compute_cov(group):
"""
Each group contains a number of spheres (x,y,z,r),
I want to compute the mean coverage
"""
n = len(group)
# if only one sphere, no coverage
if n == 1:
return 0.
# this statement alone cost 65% !
data = group.values
# behind c_cov is a cython implementation of what is presented bellow
# the cython code is invisible to cProfile, so it's fast enough
return c_cov(data)
# for two different spheres in the group
X1, X2 = np.triu_indices_from(data.T, k=1