我有以下数据框架。
SGCODE X Y
0 T0IQ00000000017200015 27.687276 -26.001460
1 T0IQ00000000017200022 27.699453 -26.003298
2 T0IQ00000000017800128 27.753478 -26.047500
有一个用户定义的函数
def haversine_distance(lat1, lon1, lat2, lon2, rlim):
r = 6371
phi1 = np.radians(lat1)
phi2 = np.radians(lat2)
delta_phi = np.radians(lat2 - lat1)
delta_lambda = np.radians(lon2 - lon1)
a = np.sin(delta_phi / 2)**2 + np.cos(phi1) * np.cos(phi2) * np.sin(delta_lambda / 2)**2
res = r * (2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a)))
if rlim >= res:
return np.round(res, 2)
当我试着在df上运行带有if语句的函数时,我得到了下面的错误。当我删除if-statement时,它工作正常,并且我得到了输出,我是否错过了if-statement语法中的一些明显的东西?
distances_km = []
for row in sample_unq_sg_codes_latlong.itertuples(index=False):
distances_km.append(
haversine_distance(sample_unq_sg_codes_latlong["X"], sample_unq_sg_codes_latlong["Y"], row.X, row.Y,5)
)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
然而,当我运行单个函数的迭代时,它就能正常工作。
haversine_distance(27.687276, -26.001460, 27.699453, -26.003298,5)
1.37
我认为你应该在if语句的行中添加断点,或者至少打印出lim和res。可能你的问题是res和lim不是int或floats,而是数组或其他东西。
长话短说:检查你要比较的两个东西的类型,并确保比较的结果是bool(而不是系列)。
你可以通过'if'的条件得到numpy数组。
任何一个lim和res是np数组,那么比较的结果也会是numpy数组。
这就是为什么它要求你在'if'的条件中使用any(any one True)或all(all true)。