【发布时间】:2018-11-30 04:24:22
【问题描述】:
我有一个DataFrame,其中包含lat 和lng 列。我也有包含多边形的FeatureCollection geojson。给定这个多边形,我如何分割我的df 并以有效的方式只选择给定多边形内的行?我想避免循环遍历df 并手动检查每个元素。
d = {'lat' : [0,0.1,-0.1,0.4],
'lng' : [50,50.1,49.6,49.5]}
df = pd.DataFrame(d)
这是显示 1 个多边形和 4 个点的要素集合。如您所见,只有最后一点在外面。
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
0,
49
],
[
0.6,
50
],
[
0.1,
52
],
[
-1,
51
],
[
0,
49
]
]
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
0,
50
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
0.1,
50.1
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
-0.1,
49.6
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
0.4,
49.5
]
}
}
]
}
this map 显示多边形和点。
编辑: 以下是我目前拥有的代码,但正如您所料,它非常慢。
from shapely.geometry import shape, Point
# check each polygon to see if it contains the point
for feature in feature_collection['features']:
polygon = shape(feature['geometry'])
for index, row in dfr.iterrows():
point = Point(row.location_lng, row.location_lat)
if polygon.contains(point):
print('Found containing polygon:', feature)
其中dfr 是我的DataFrame,包含location_lat 和location_lng。 feature_collection 是一个只有多边形的geojson 特征集合(请注意,上面的geojson 示例仅用于解释问题,它只有1 个多边形并且有一些点可以说明问题)。
【问题讨论】:
-
感谢 @erncyp 没有帮助我,因为它使用 matplotlib,我不想那样做。我更喜欢使用类似熊猫的方法。
-
您是否从
feature_collection创建了数据框df?如果是的话怎么办?在您的代码中,您在dfr上使用iterrows而不是df,是一样的吗? -
@Ben.T 感谢您的提问。我会尽力澄清。上面的例子只是为了解释这个任务。一般来说,我有一个大型数据框 (
dfr) 和一个大型特征集合,仅包含多边形。我会尝试编辑问题。