【问题标题】:How to a conditional join(like SQL where join) of Dataframes in Python如何在 Python 中对 Dataframe 进行条件连接(如 SQL where join)
【发布时间】:2020-06-20 05:23:25
【问题描述】:

我有两个如下所示的数据框

df1

visit_counts SG_lat   SG_long
0   3222.0  33.13623    -91.942026
1   6243.0  33.241981   -92.668384
2   5225.0  33.27683    -93.212498
3   6107.0  33.461784   -94.039191
4   3712.0  33.567683   -92.83685799999999

df2

num_transactions lat_dgr    long_dgr
0   45433   35.293364   -93.716224
1   41172   35.293364   -93.716224
2   41909   35.293364   -93.716224
3   37979   35.293364   -93.716224
4   43546   35.293364   -93.716224

如果两个坐标之间的地理距离小于 100m,我想内连接这些数据框 像下面的伪代码

## pseudo code
coords_1 = (df1.SG_lat, df1.SG_long)
coords_2 = (df2.lat_dgr, df2.long_dgr)
geopy.distance.vincenty(coords_1, coords_2).m < 100

在 SQL 中,我们可以使用下面的 where 条件来做到这一点

ST_DISTANCE(ST_GEOGPOINT(long_dgr,lat_dgr), ST_GEOGPOINT( sg_long,sg_lat)) <= 100

pandas 合并函数不允许 where 条件。有没有其他方法可以加入这两个数据框。我没有任何其他键列要加入,然后使用 loc 进行过滤。

【问题讨论】:

  • 你想计算所有可能的距离,还是只计算公共行/索引的距离?
  • @anon01 我想计算所有可能的距离,然后如果距离小于 100 则连接值,即我正在寻找距离

标签: python pandas dataframe pandas-groupby


【解决方案1】:

如果您希望计算表中所有行组合的距离,您可以:1) 创建表的笛卡尔积,2) 计算距离 3) 根据阈值进行过滤。由于您正在扩展所有行组合,因此内存效率很低,但至少计算起来很简单:

import pandas as pd
from geopy.distance import geodesic

# create a dummy key to join all rows from df1 to df2:
df1["dummy_key"] = 0
df2["dummy_key"] = 0

# create cartesian product table
df3 = pd.merge(left=df1, right=df2, on="dummy_key").drop(columns=["dummy_key"])

# apply geodesic (newer version of geopy.distance.vincenty) to get the distance in meters for each row
dist = df3.apply(lambda row: geodesic((row["SG_lat"], row["SG_long"]), (row["lat_dgr"], row["long_dgr"])).m, axis=1) 

# filter for rows that you desire:
df3 = df3[dist < 100]

【讨论】:

  • 这将计算公共索引行的距离,但实际上我是根据距离进行组合以找到公共行。该表还有一些其他列和纬度,经度未按任何顺序排序.所以,我正在寻找基于距离的内部连接。
  • @krishnakoti 有道理,我会更新。你的桌子有多大,你有多少内存?
  • 这些表是中等大小的,它们都包含大约 2k 行。
  • @krishnakoti 修改了上面的答案。这是一个类似的问题/解决方案,讨论了其他一些方法:stackoverflow.com/questions/23508351/…
  • FWIW,似乎最近在有关 pandas API 的对话中讨论了这一点:github.com/pandas-dev/pandas/issues/7480
猜你喜欢
  • 2015-05-02
  • 2016-05-15
  • 1970-01-01
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多