I have two data frames (df1,df2) and I want to iterate through both the data frames and match the key values in the two data frames. If matched I want to perform a specific action.
df1:
ID Name lat/long
1 xyz (23,12)
df2:
ID Store lat/long
1 pharmacy (23,13)
I want to iterate through the two df and find the distance between the two co ordinates where ID is the same.
Example if df1['id'] == df2['ID']: Find distance between two lat/lon
You haven't provided a lot of information in the question, so this might be off.
Assumptions:
df1 =
ID Name lat/long
0 1 A (23, 12)
1 2 B (24, 12)
2 3 C (25, 12)
3 10 D (30, 12)
df2 =
ID Store lat/long
0 1 a (23, 13)
1 2 b (24, 13)
2 3 c (25, 13)
3 11 e (30, 13)
And: the columns lat/long
contain tuples
. If not do df1["lat/long"] = df1["lat/long"].map(eval)
and the same for df2
.
Then this
from haversine import haversine
df3 = pd.merge(df1, df2, on="ID", how="inner")
df3["Distance"] = df3[["lat/long_x", "lat/long_y"]].apply(
lambda row: haversine(*row),
axis="columns"
)
df3 = df3.drop(columns=["lat/long_x", "lat/long_y"])
leads to
ID Name Store Distance
0 1 A a 102.355413
1 2 B b 101.581547
2 3 C c 100.776739
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.