英文:
dataframe apply lambda function that requires value from row n+1
问题
import geopy.distance
distCalcExample = geopy.distance.geodesic((49.18443, -0.36098), (49.184335, -0.361185)).m
r = {'poly':[(49.419453, 0.232884),(49.41956, 0.23269),(49.41956, 0.23261),(49.41953, 0.23255),(49.41946, 0.23247)}
df=pd.DataFrame(r)
df['dist']=0
df
需要计算行n和n+1的坐标之间的距离。我考虑使用geopy,就像distCalcExample中一样,结合apply和lambda函数。但我还没有成功实现。最简单的方法是什么?
英文:
I have a dataframe and geopy to calculate distances between two geo coordinates as follows :
import geopy.distance
distCalcExample = geopy.distance.geodesic((49.18443, -0.36098), (49.184335, -0.361185)).m
r = {'poly':[(49.419453, 0.232884),(49.41956, 0.23269),(49.41956, 0.23261),(49.41953, 0.23255),(49.41946, 0.23247)]}
df=pd.DataFrame(r)
df['dist']=0
df
I need to calculate the distance between coordinates of rows n and n+1.
I was thinking of using geopy as in distCalcExample, along with apply and a lambda function.
But i have not managed to achieve it. What would be the simplest way to make it?
答案1
得分: 1
首先创建包含移位值的列:
df["shifted"] = df["poly"].shift()
然后使用逐行应用:
df[["poly", "shifted"]].apply(lambda x: geopy.distance.geodesic(x[0], x[1]).m, axis=1)
英文:
First create a column including the shifted values
df["shifted"] = df["poly"].shift()
Then use apply rowwise:
df[["poly","shifted"]].apply(lambda x: geopy.distance.geodesic(x[0],x[1]).m,axis=1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论