[英]Python Shapely Cant Find Points Within Polygon When Looping Polygons
我有一個帶有lat和lon的商店位置的csv文件 。 我也有一個帶有美國人口普查區域多邊形特征的geojson文件。 我想使用Python查看每個位置存在於哪些多邊形中。
我正在使用Shapely Python庫的contains()來遍歷商店位置的csv文件,獲取緯度和經度坐標,然后檢查坐標是否存在於geojson文件的多邊形之一內。
如果我先遍歷每個位置/坐標,然后遍歷每個多邊形,則使用contains()或inside()來檢查多邊形是否包含該點,那么我編寫的代碼就可以成功工作。
但這太慢了,所以我想反過來進行這個過程,並首先遍歷polygons / geojson文件,然后對照成千上萬的坐標檢查成千上萬的多邊形,而不是反過來。
但是,當我簡單地切換循環以對照坐標檢查多邊形時,contains()不會找到任何匹配項,即使在我首先遍歷坐標並針對多邊形檢查它們時找到了正確的匹配項。 除了反轉之外,它是相同的代碼。
代碼(包含錯誤):
with open(mapFile) as f:
data = json.load(f)
#Loop through features in Geojson file
for feature in data['features']:
polygon = shape(feature["geometry"])
for row in locationsFile:
#get point coordinates from file
pointLat = float(row[13])
pointLon = float(row[14])
point = Point(pointLon, pointLat)
print(polygon.contains(point))
if polygon.contains(point):
#Grab data
newx = feature["properties"]["x"]
newy = feature["properties"]["y"]
newz = feature["properties"]["z"]
#append data
row.append(newx)
row.append(newy)
row.append(newz)
#update file
newFile.writerow(row)
break
此代碼可產生准確的結果:
with open(mapFile) as f:
data = json.load(f)
#Loop through coordinates in CSV file
for row in locationsFile:
#get point coordinates from file
pointLat = float(row[13])
pointLon = float(row[14])
point = Point(pointLon, pointLat)
#Loop through features in Geojson file
for feature in data['features']:
polygon = shape(feature["geometry"])
if polygon.contains(point):
#Grab data
newx = feature["properties"]["x"]
newy = feature["properties"]["y"]
newz = feature["properties"]["z"]
#append data
row.append(newx)
row.append(newy)
row.append(newz)
#update file
newFile.writerow(row)
break
兩種情況下, break
行為都會有所不同。 它只會打破最里面的循環,在“正確”的情況下,是通過data['features']
的循環,但在錯誤的情況下,是通過locationsFile
的循環
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.