我有一个个人数据框,每个人都有 X 和 y 坐标,并且我有一个包含多个多边形的 .shp 文件。
个人数据框如下所示:
ind_ID | x_坐标 | y_坐标 |
---|---|---|
1 | 2.333 | 6.572711 |
2 | 3.4444 | 6.57273 |
.shp 文件如下所示:
代码 | 形状长度 | 形状区域 |
---|---|---|
222 | .22 | .5432 |
2322 | .54322 | .4342 |
122 | .65656 | .43 |
2122 | .5445 | .5678 |
我想要做的是在数据框中添加一个新列,以便使用该坐标位于其中的 .shp 文件的链接代码标记每个坐标。为此,我构建了以下代码:
from shapely.geometry import Point
import csv
from shapely.geometry.polygon import Polygon
import shapefile
from shapely.geometry import shape # shape() is a function to convert geo objects through the interface
import numpy as np
import pandas as pd
import shapefile as shp
Individual = pd.read_csv("dataframe.csv")
sf = shapefile.Reader('path to the shape file.shp')
sf.shapes()
len(sf.shapes())
# function to read the shapefile
def read_shapefile(sf):
"""
Read a shapefile into a Pandas dataframe with a 'coords'
column holding the geometry information. This uses the pyshp
package
"""
fields = [x[0] for x in sf.fields][1:]
records = sf.records()
shps = [s.points for s in sf.shapes()]
df = pd.DataFrame(columns=fields, data=records)
df = df.assign(coords=shps)
return df
df = read_shapefile(sf)
df.shape
我使用 read_shapefile 函数查找每个特征内的所有 x,y 点,输出 DF
代码 | 形状长度 | 形状区域 | 编码 |
---|---|---|---|
222 | .22 | .5432 | 3.23232,2.72323,3.931226,2.543,3.435534 .... |
2322 | .54322 | .4342 | 3.23232,2.72322,3.111226,2.343,3.12312 ... |
122 | .65656 | .43 | 3.2323,2.23325,3.1212,2.1221,3.12321 ... |
2122 | .5445 | .5678 | 3.9232,2.23232,2.931226,1.2123,3.213 ... |
下一步是检查每个induvial,无论它是否落在任何cooded点内,如果是,则将新列添加到Individual df包含形状文件的相应代码。我需要这部分的帮助^^",我开始检查 sh 数据坐标中的 x,y
Individual.["X","Y"].isin(sf .["coords"]).astype(int)
我无法检查,因为有错误。输出需要是:个人数据框看起来像:
ind_ID | x_坐标 | y_坐标 | 代码 |
---|---|---|---|
1 | 2.333 | 6.572711 | 222 |
2 | 3.4444 | 6.57273 | 122 |