Pandas - 列之间的欧几里得距离

Dan*_*iel 3 python numpy pandas

我有一个数据框如下:

           uuid        x_1         y_1         x_2         y_2
0        di-ab5      82.31      184.20      148.06      142.54  
1        di-de6      92.35      185.21       24.12       16.45
2        di-gh7     123.45        0.01         NaN         NaN 
...
Run Code Online (Sandbox Code Playgroud)

我正在尝试计算新列之间[x_1, y_1][x_2, y_2]新列中的欧几里德距离(在本例中不是实际值)。

           uuid       dist
0        di-ab5      12.31    
1        di-de6      62.35   
2        di-gh7        NaN
Run Code Online (Sandbox Code Playgroud)

注意事项:

  1. 某些行包含NaN某些数据点
  2. 可以将原始数据框中的数据表示为点(即[1.23, 4.56]),而不是分割 x 和 y 坐标

我目前正在使用以下脚本:

df['dist']  = np.sqrt((df['x_1'] - df['x_2'])**2 + (df['y_1'] - df['y_2'])**2)
Run Code Online (Sandbox Code Playgroud)

但它看起来很冗长并且经常失败。有没有更好的方法使用 pandas、numpy 或 scipy 来做到这一点?

Fel*_*nza 7

您可以使用np.linalg.norm,即:

df['dist'] = np.linalg.norm(df.iloc[:, [1,2]].values - df.iloc[:, [3,4]], axis=1)
Run Code Online (Sandbox Code Playgroud)

输出:

     uuid     x_1     y_1     x_2     y_2        dist
0  di-ab5   82.31  184.20  148.06  142.54   77.837125
1  di-de6   92.35  185.21   24.12   16.45  182.030960
2  di-gh7  123.45    0.01     NaN     NaN         NaN
Run Code Online (Sandbox Code Playgroud)