将geopandas geodataframe转换为pandas datafram

2024-04-28 20:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

将geopandas geodataframe转换为pandas数据frame的最有效方法是什么?下面是我使用的方法,有没有其他方法在不产生错误方面更有效或更好?

import geopandas as gpd
import pandas as pd

# assuming I have a shapefile named shp1.shp
gdf1 = gpd.read_file('shp1.shp')

# then for the conversion, I drop the last column (geometry) and specify the column names for the new df
df1 = pd.DataFrame(gdf1.iloc[:,:-1].values, columns = list(gdf1.columns.values)[:-1] )

Tags: columnsthe方法importpandasforascolumn
1条回答
网友
1楼 · 发布于 2024-04-28 20:26:27

不需要将GeoDataFrame转换为值数组,可以直接将其传递给DataFrame构造函数:

df1 = pd.DataFrame(gdf)

上面将保留“geometry”列,这对于将其作为普通数据帧是没有问题的。但如果您真的想删除该列,可以这样做(假设该列称为“geometry”):

df1 = pd.DataFrame(gdf.drop(columns='geometry'))
# for older versions of pandas (< 0.21), the drop part: gdf.drop('geometry', axis=1)

两个注释:

  • 通常不需要将GeoDataFrame转换为普通的DataFrame,因为从DataFrame知道的大多数方法都可以正常工作。当然,在某些情况下确实需要它(例如,在没有几何图形的情况下绘制数据),那么上述方法是最好的方法。
  • 第一种方法(df1 = pd.DataFrame(gdf))将不获取GeoDataFrame中数据的副本。从效率的角度来看,这通常是好的,但是根据您希望对数据帧执行的操作,您可能需要一个实际的副本:df1 = pd.DataFrame(gdf, copy=True)

相关问题 更多 >