简体   繁体   English

Geopandas:如何读取 csv 并转换为带有多边形的 geopandas dataframe?

[英]Geopandas: how to read a csv and convert to a geopandas dataframe with polygons?

I read a .csv file as a dataframe that looks like the following:我将.csv文件读取为 dataframe,如下所示:

import pandas as pd
df = pd.read_csv('myFile.csv')
df.head()
    BoroName    geometry
0   Brooklyn    MULTIPOLYGON (((-73.97604935657381 40.63127590...
1   Queens      MULTIPOLYGON (((-73.80379022888098 40.77561011...
2   Queens      MULTIPOLYGON (((-73.8610972440186 40.763664477...
3   Queens      MULTIPOLYGON (((-73.75725671509139 40.71813860...
4   Manhattan   MULTIPOLYGON (((-73.94607828674226 40.82126321...

I want to convert it to a geopandas dataframe.我想将它转换为 geopandas dataframe。

import geopandas as gpd
crs = {'init': 'epsg:4326'}
gdf = gpd.GeoDataFrame(df, crs=crs).set_geometry('geometry')

but I get the following error但我收到以下错误

TypeError: Input must be valid geometry objects: MULTIPOLYGON (((-73.97604935657381 40.631275905646774, -73.97716511994669 40.63074665412933,....

For some reason geopandas seems to be unable to convert a geometry column from a pandas dataframe.由于某种原因,geopandas 似乎无法从 pandas dataframe 转换几何列。 You could try two approaches.您可以尝试两种方法。

Number 2: Try applying the shapely wkt.loads function on your column before converting your dataframe to a geodataframe.数字 2:在将 dataframe 转换为地理数据框之前,尝试在列上应用匀称的wkt.loads function。

from shapely import wkt

df['geometry'] = df['geometry'].apply(wkt.loads)
gdf = gpd.GeoDataFrame(df, crs='epsg:4326')

Either way should work.无论哪种方式都应该有效。 Good luck!祝你好运!


Do not use - crashes spyder and jupyter kernel for some people不要使用 - 使某些人崩溃 spyder 和 jupyter kernel

Number 1: Try loading the csv directly with geopandas第一:尝试直接用 geopandas 加载 csv

gdf = gpd.read_file('myFile.csv')
gdf.crs = 'epsg:4326'

You could also try this:你也可以试试这个:

gdf = gpd.GeoDataFrame(
    df, geometry=gpd.points_from_xy(df.longitude, df.latitude)
)

This will convert those lat/long columns to points这会将那些纬度/经度列转换为点

Dudes, there are wkt geometry strings in the original dataframe, not xy columns, so i would suggest read this: DataFrame with WKT Column to GeoPandas Geometry伙计们,原始 dataframe 中有 wkt 几何字符串,而不是 xy 列,所以我建议阅读: DataFrame with WKT Column to GeoPandas Geometry

Geopandas puts a geometry column at the end if you load directly.如果直接加载,Geopandas 会在末尾放置一个几何列。 Found this out by experimenting with column names and it worked通过试验列名发现了这一点并且它有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM