数据框应用需要来自第n+1行的lambda函数

huangapple go评论69阅读模式
英文:

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

数据框应用需要来自第n+1行的lambda函数

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)

huangapple
  • 本文由 发表于 2023年2月8日 17:46:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定