【发布时间】:2021-11-29 23:00:32
【问题描述】:
我有一个大约 300000 行的 pandas 数据框 A。每行都有一个纬度和经度值。
我还有一个大约 10000 行的第二个 pandas 数据帧 B,它有一个 ID 号、最大和最小纬度以及最大和最小经度。
对于A中的每一行,我需要B中对应行的ID,这样A中的行的经纬度就包含在B中的行所代表的边界框内。
到目前为止,我有以下内容:
ID_list = []
for index, row in A.iterrows():
filtered_B = B.apply(lambda x : x['ID'] if row['latitude'] >= x['min_latitude']
and row['latitude'] < x['max_latitude'] \
and row['longitude'] >= x['min_longitude'] \
and row['longitude'] < x['max_longitude'] \
else None, axis = 1)
ID_list.append(B.loc[filtered_B == True]['ID']
创建 ID_list 变量的目的是将其作为 ID 列添加到 A。包括大于或等于和小于条件,以便 A 中的每一行只有一个来自 B 的 ID。
上面的代码在技术上是可行的,但它每分钟完成大约 1000 行,这对于这么大的数据集是不可行的。
任何提示将不胜感激,谢谢。
编辑:示例数据框:
答:
| location | latitude | longitude |
|---|---|---|
| 1 | -33.81263 | 151.23691 |
| 2 | -33.994823 | 151.161274 |
| 3 | -33.320154 | 151.662009 |
| 4 | -33.99019 | 151.1567332 |
乙:
| ID | min_latitude | max_latitude | min_longitude | max_longitude |
|---|---|---|---|---|
| 9ae8704 | -33.815 | -33.810 | 151.234 | 151.237 |
| 2ju1423 | -33.555 | -33.543 | 151.948 | 151.957 |
| 3ef4522 | -33.321 | -33.320 | 151.655 | 151.668 |
| 0uh0478 | -33.996 | -33.990 | 151.152 | 151.182 |
预期输出:
ID_list = [9ae8704, 0uh0478, 3ef4522, 0uh0478]
【问题讨论】:
-
请分享示例数据帧,以及预期的输出。
-
您没有添加预期的输出数据帧
-
A 中的值一定会在 B 中找到吗?如果不是,那么 A 中该行的输出应该是什么?会有多个匹配项吗?
-
如果没有找到,填上nan。而且只有一场比赛
-
尝试 np.vectorize 或此处提到的其他替代方法,而不是
apply,看看它是否仍然很慢。 stackoverflow.com/questions/52673285/…