如何将WKT格式的坐标转换为纬度和经度列



我从Twitter上提取了坐标数据。我得到的分数是WKT格式的。我想把它们分成纬度和经度两列。坐标的格式为

{'type': 'Point', 'coordinates': [77.58168, 12.8952]}
{'type': 'Point', 'coordinates': [77.64363, 12.9739]}
{'type': 'Point', 'coordinates': [75.9372318, 12.44627712]}
{'type': 'Point', 'coordinates': [77.5945627, 12.9715987]}
{'type': 'Point', 'coordinates': [77.53584257, 13.05144109]}
{'type': 'Point', 'coordinates': [77.5945627, 12.9715987]}
{'type': 'Point', 'coordinates': [77.58721, 12.96643]}

我使用str.replace 删除了所有标点符号和不需要的文本

df['coordinates'] = df.coordinates.str.replace('type,?' , '')
df['coordinates'] = df.coordinates.str.replace('Point,?' , '')
df['coordinates'] = df.coordinates.str.replace('coordinates,?' , '')
df['coordinates'] = df.coordinates.str.replace('{,?' , '')
df['coordinates'] = df.coordinates.str.replace(',,?' , '')
df['coordinates'] = df.coordinates.str.replace(':,?' , '')
df['coordinates'] = df.coordinates.str.replace('],?' , '')
df['coordinates'] = df.coordinates.str.replace(',?' , '')
df['coordinates'] = df.coordinates.str.replace('},?' , '')
df['coordinates'] = df.coordinates.str.replace("'',?" , "")

我试着用来拆分专栏

df = pd.DataFrame(df.coordinates.str.split(' ',1).tolist(),
columns = ['Long','Lat'])

但它不起作用。请让我知道如何将WKT转换为坐标列

geopandas文档介绍了使用shapely导入WKT格式的数据。在他们的例子中,给定您的数据帧df,您可以尝试:

from shapely import wkt
import geopandas as gpd
df['coordinates'] = df['coordinates'].apply(wkt.loads)
gdf = gpd.GeoDataFrame(df, geometry='coordinates')

如果您愿意,您可以通过以下操作获取纬度和经度,并将其分配回原始数据帧。

df['lat'] = gdf.geometry.x
df['long'] = gdf.geometry.y

由于您没有提供一个完整的最低限度的工作示例,我还没有测试过这段代码,但我认为它应该可以工作。

最新更新