Python中的距离欧几里德

2024-05-16 23:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算坐标列表和一个名为cord的坐标之间的距离

预期结果是一个列表,其中包含坐标列表的第i个元素与跳线之间的所有距离

例如:

我有一个数据框df,它有一个列Geo_形状,带有一个列表列表。 我需要计算一个列表,这个列表中所有元素的距离都是线

^{tb1}$

跳线=[1.2,5.3]

代码

我试着运行这个代码

df['Geo_Shape'].apply(lambda x: np.linalg.norm(x - [cord]*len(x), axis=1))

但我有一个错误:

TypeError: unsupported operand type(s) for -: 'list' and 'list'

有人知道怎么修吗

谢谢你的帮助


Tags: 数据lambda代码元素距离df列表list
2条回答

您需要将numpy.linalg.norm中的x转换为numpy.ndarray

df['Geo_Shape'].apply(lambda x: np.linalg.norm(np.array(x) - cord, axis=1))

输出:

0    [3.0, 3.7107950630558943, 4.294182110716777]
Name: Geo_Shape, dtype: object

谢谢你的帮助

当我尝试时:

df['Geo_Shape'].apply(lambda x: np.linalg.norm(np.array(x) - cord, axis=1))

我有以下错误:

TypeError: unsupported operand type(s) for -: 'list' and 'float'

所以我试着这样做:

df['Geo_Shape'].apply(lambda x: np.linalg.norm(np.array(x) - np.array([cord]*len(x)), axis=1))

还是同样的错误

你知道怎么了吗

相关问题 更多 >