【发布时间】:2022-01-13 18:12:18
【问题描述】:
我正在尝试迭代 pandas DataFrame 的行并将函数一一应用于行。函数的输入值取决于上一行的结果。
这是一个例子:
import numpy as np
import pandas as pd
import math
def predict_loc(df, lon, lat):
R = 6378.1 # Radius of the Earth
brng = np.deg2rad(df.wdir) # Bearing is radians.
d = df.wspd * df.delta * 60 / 1e3 # Distance in km
lat2 = math.asin(
math.sin(lat) * math.cos(d / R)
+ math.cos(lat) * math.sin(d / R) * math.cos(brng)
)
lon2 = lon + math.atan2(
math.sin(brng) * math.sin(d / R) * math.cos(lat),
math.cos(d / R) - math.sin(lat) * math.sin(lat2),
)
lat2 = np.rad2deg(lat2)
lon2 = np.rad2deg(lon2)
return lon2, lat2
dates = pd.date_range("20130101", periods=6, freq="1H")
df = pd.DataFrame(
np.random.randn(6, 3),
index=dates,
columns=[
"wdir",
"wspd",
"delta",
],
)
lon = 0
lat = 1
for index, row in df.iterrows():
lon, lat = predict_loc(row, lon, lat)
在本例中,lon 和 lat 的初始值分别为 0 和 1。
然后,由predict_loc 函数预测位置。新的 lon 和 lat 是下一行的输入。我想要的是最后的经纬度。
有没有更快的方法来完成这项任务?谢谢。
【问题讨论】:
-
您好,“更快地完成任务”是指您正在寻找简化
predict_loc或者功能还不错,但您正在寻找更快的东西比iterrows()? -
嗨@Laurent,我的意思是比
iterrows()更快。