计算两个列表中两点之间的距离

时间:2018-08-07 21:01:28

标签: python numpy types distance

B1, B2,B3
-232.34 -48.48 -260.77
-233.1 -49.48 -253.6
-232.44 -50.81 -250.25
-233.02 -51.42 -248.88
-232.47 -51.95 -248.06
-232.17 -52.25 -247.59
-232.6 -52.83 -245.82
-232.29 -53.63 -243.98
-231.65 -53.24 -243.76

o1,o2,o3
-302.07 -1.73 -280.1
-302.13 -3.37 -273.02
-303.13 -4.92 -269.74
-302.69 -4.85 -268.32
-303.03 -5.61 -267.45
-302.55 -5.2 -267.22
-302.6 -5.91 -266.01
-302.46 -6.41 -264.79
-302.59 -7.4 -264.96







import numpy as np
# Convert your arrays to numpy arrays
B1 = np.asarray(B1)
B2 = np.asarray(B2)
B3 = np.asarray(B3)
o1 = np.asarray(o1)
o2 = np.asarray(o2)
o3 = np.asarray(o3)
# Find the distance in a single, vectorized operation
force = np.sqrt(np.sum(((B1-o1)**2, (B2-o2)**2, (B3-o3)**2), axis=0))
print(force)
print(B1,B2,B3,o1,o2,o3)
#87.08173861378742 is the result of force
#-231.65 -53.24 -243.76 -302.59 -7.4 -264.96 is the result for 
B1,B2,B3,o1,o2,o3
#the code only uses last data set for the force calculation. It should use 

所有数据

The data type of B1-o3 changed from 
 <class 'numpy.float64'> to <class 'numpy.ndarray'> after the code runs.

我想计算两个点(O和B)之间的距离。每个点都来自3D系统。我认为我的数据类型有问题,但是找不到。

2 个答案:

答案 0 :(得分:0)

B1=np.array([-232.34 ,-233.1])
B2=np.array([ -48.48,-49.48 ])
B3=np.array([ -260.77,-253.6 ])
O1=np.array([-302.07 ,-302.13])
O2=np.array([-1.73 ,-280.1])
O3=np.array([-1.73 ,-273.02])

提供axis=1将满足您的需求

force = np.sqrt(np.sum(((B1-O1)**2, (B2-O2)**2, (B3-O3)**2), axis=1))
print(force)
[ 98.11938544 235.3107454  259.76693015]

答案 1 :(得分:0)

我将这两个表放入两个文本文件中。 table_B.txt和table_o.txt

import pandas as pd
df1 = pd.read_csv('table_B.txt',sep = ' ',header=None)
df2 = pd.read_csv('table_o.txt',sep = ' ',header=None)

x = (df1[0] - df2[0])**2 + (df1[1] - df2[1])**2 + (df1[2] - df2[2])**2
x**.5

0    86.148037
1    85.254967
2    86.503343
3    86.026667
4    86.614556
5    86.904452
6    86.655193
7    87.101168
8    87.081739
dtype: float64

这是您想要的吗?我将每个表读入pandas数据框。然后将df1和df2中行之间的差平方。然后,我将所有列加在一起并取平方根。

最后,每一行都有一系列距离。

相关问题