使用列和行索引对函数进行矢量化



我构建了一个程序,从一个数据帧中获取值,并将其用作另一个数据帧的输入。 df_coordinate 是具有 x 和 y 坐标行(大小介于 0 和 max_size_x 或 max_size_y 之间的(的数据帧。 updated_coordinates 是一个具有屏幕大小的新数据帧,它使用坐标和一种欧氏距离来使坐标表示区域而不是像素。 代码按照我的预期工作,但现在它变慢了。我知道矢量化要快得多,我尝试尽可能多地实现它。然而 我似乎找不到一种方法来使用使用列和行索引的公式进行矢量化。如您所见,使用 .apply 我使用 x.name 和 x.index,但是有没有办法更快地实现这一点?

max_size_x = 1080
max_size_y = 720
for index, row in df_coordinate.iterrows():
updated_coordinates = pd.DataFrame(np.zeros((max_size_x, max_size_y))) # to do: maybe empty instead of zeroes, and already delete the ones from attention_max
current_time = df_coordinate.loc[index]
coordinate_x = current_time['x_coordinate']
coordinate_y = current_time['y_coordinate']
# calculate area with Euclidean distance:
updated_coordinates = updated_coordinates.apply(lambda x: 1/ ( np.power((np.sqrt(np.power(x.name-coordinate_x,2) + np.power(x.index-coordinate_y,2))),2)))

我通过在循环外添加以下内容找到了答案:

df_x = pd.DataFrame(np.zeros((image_size_x, image_size_y))) 
df_x = df_x.apply(lambda x: x.name) 
df_y = pd.DataFrame(np.zeros((image_size_x, image_size_y))) 
df_y = df_y.apply(lambda x: x.index) 

并将 .apply 函数替换为向量:

updated_coordinates = 1/ ( * np.power((np.sqrt(np.power(df_x - gaze_x,2) + np.power(df_y - gaze_y,2))),2))

我已经检查过了,运行速度是原来的十倍以上。

最新更新