加速groupby.apply pandas匹配

时间:2018-02-14 11:33:52

标签: python algorithm pandas numpy dataframe

我在笛卡尔平面上有一个带有ID(在这种情况下是颜色)的点的数据帧,以及在同一平面上定义它们的中心位置的一组圆。圆圈的半径均为2个单位。

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: points_df = pd.DataFrame([['green', 10., 10., 100],
               ['green', 5, 5, 200],
               ['blue', 9, 9, 3000 ],
               ['blue', 8, 8, 4000]], columns = ['color', 'x', 'y', 'height' ])

In [4]: points_df    
    color   x   y   height
0   green   10.0    10.0    100
1   green   5.0 5.0 200
2   blue    9.0 9.0 3000
3   blue    8.0 8.0 4000

In [5]: circles = np.array([[10, 10], [5, 5], [9,9], [8,8]])

对于每个圈子,我想找到落在圈子中的每种颜色的点数据框中的条目。如果每种颜色有多个条目,那么我想在这个圆圈中找到最大的“高度”值。

为了简单起见,我们假设我有一个函数point_selection,它从circles数组中获取数据帧和一行并执行此选择。然后我将此函数应用于我的数据框:

def point_selection(df, circle):
    #distance calculation and selection here
    return selected_df_row

groupby_color = points_df.groupby('color')
df_list = []

for circle in circles:
    selected = groupby_color.apply(point_selection, circle)
    df_list.append(selected.set_index('color', inplace=True))

final_df = pd.concat(df_list)

我目前正在为数据框中的大量行(~200000)和大量的圆(~15000)执行此操作,是否有人有任何简单的方法来加速这些计算?据说groupby.apply相当缓慢,但我想不出另一种方法。

1 个答案:

答案 0 :(得分:1)

似乎你需要:

def point_selection(df, circle):
    #distance calculation and selection here
    return pd.Series(selected_df_row)

df = points_df.groupby('color').apply(point_selection, circle)