标签: geopandas

使用Geopandas计算与最近特征的距离

我希望使用Geopandas/Shapely 做相当于ArcPy Generate Near Table的工作.我是Geopandas和Shapely的新手,并开发了一种有效的方法,但我想知道是否有更有效的方法.

我有两个点文件数据集 - Census Block Centroids和餐馆.我希望找到每个人口普查区块中心距离它最近的餐厅的距离.对于同一个餐厅而言,对于多个街区来说,最近的餐厅没有任何限制.

这对我来说有点复杂的原因是因为Geopandas距离函数根据索引计算元素,匹配.因此,我的一般方法是将Restaurants文件转换为多点文件,然后将blocks文件的索引设置为全部相同的值.然后,所有块质心和餐馆都具有相同的索引值.

import pandas as pd
import geopandas as gpd
from shapely.geometry import Polygon, Point, MultiPoint
Run Code Online (Sandbox Code Playgroud)

现在阅读Block Centroid和Restaurant Shapefiles:

Blocks=gpd.read_file(BlockShp)
Restaurants=gpd.read_file(RestaurantShp)
Run Code Online (Sandbox Code Playgroud)

由于Geopandas距离函数按元素计算距离,我将Restaurant GeoSeries转换为MultiPoint GeoSeries:

RestMulti=gpd.GeoSeries(Restaurants.unary_union)
RestMulti.crs=Restaurants.crs
RestMulti.reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)

然后我将Blocks的索引设置为等于0(与Restaurants多点相同的值)作为元素计算的解决方法.

Blocks.index=[0]*len(Blocks)
Run Code Online (Sandbox Code Playgroud)

最后,我使用Geopandas距离函数计算每个Block质心到最近餐馆的距离.

Blocks['Distance']=Blocks.distance(RestMulti)
Run Code Online (Sandbox Code Playgroud)

请提供有关如何改进这方面的任何建议.我并不喜欢使用Geopandas或Shapely,但我希望学习ArcPy的替代方案.

谢谢您的帮助!

python pandas shapely geopandas

10
推荐指数
2
解决办法
1万
查看次数

geopandas指向多边形

我有一个GeoDataFrame的多边形(~30)和一个GeoDataFrame的点(~10k)

我想在我的GeoDataFrame中创建30个新的列(具有适当的多边形名称),如果该点存在于多边形中,则使用简单的布尔值True/False.

例如,多边形的GeoDataFrame是这样的:

id  geometry
foo POLYGON ((-0.18353,51.51022, -0.18421,51.50767, -0.18253,51.50744, -0.1794,51.50914))
bar POLYGON ((-0.17003,51.50739, -0.16904,51.50604, -0.16488,51.50615, -0.1613,51.5091))
Run Code Online (Sandbox Code Playgroud)

Points的GeoDataFrame是这样的:

counter     points
   1     ((-0.17987,51.50974))
   2     ((-0.16507,51.50925))
Run Code Online (Sandbox Code Playgroud)

预期产量:

counter          points        foo    bar
   1    ((-0.17987,51.50974))  False  False
   1    ((-0.16507,51.50925))  False  False
Run Code Online (Sandbox Code Playgroud)

我可以通过以下方式手动完成:

foo = df_poly.loc[df_poly.id=='foo']
df_points['foo'] = df_points['points'].map(lambda x: True if foo.contains(x).any()==True else False
Run Code Online (Sandbox Code Playgroud)

但鉴于我有30个多边形,我想知道是否有更好的方法.感谢任何帮助!

python point-in-polygon pandas geopandas

10
推荐指数
1
解决办法
8164
查看次数

将geopandas地理数据框转换为pandas数据帧

将geopandas地理数据框转换为pandas数据帧的最有效方法是什么?下面是我使用的方法,是否有另一种方法,通常在不产生错误时更有效或更好?

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] )
Run Code Online (Sandbox Code Playgroud)

python pandas geopandas

10
推荐指数
1
解决办法
5938
查看次数

Geopandas上的Colorbar

我想在GeoPandas上创建一个Matplotlib颜色条.

import geopandas as gp
import pandas as pd
import matplotlib.pyplot as plt

#Import csv data
df = df.from_csv('data.csv')

#Convert Pandas DataFrame to GeoPandas DataFrame
g_df = g.GeoDataFrame(df)

#Plot
plt.figure(figsize=(15,15)) 
g_plot = g_df.plot(column='column_name',colormap='hot',alpha=0.08)
plt.colorbar(g_plot)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-55-5f33ecf73ac9> in <module>()
      2 plt.figure(figsize=(15,15))
      3 g_plot = g_df.plot(column = 'column_name', colormap='hot', alpha=0.08)
----> 4 plt.colorbar(g_plot)

...

AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None'
Run Code Online (Sandbox Code Playgroud)

我不知道如何让colorbar工作.

python matplotlib pandas geopandas

9
推荐指数
1
解决办法
6938
查看次数

GeoPandas在点上设置CRS

给定以下GeoDataFrame:

h=pd.DataFrame({'zip':[19152,19047],
               'Lat':[40.058841,40.202162],
               'Lon':[-75.042164,-74.924594]})
crs='none'
geometry = [Point(xy) for xy in zip(h.Lon, h.Lat)]
hg = GeoDataFrame(h, crs=crs, geometry=geometry)
hg

       Lat          Lon     zip     geometry
0   40.058841   -75.042164  19152   POINT (-75.042164 40.058841)
1   40.202162   -74.924594  19047   POINT (-74.924594 40.202162)
Run Code Online (Sandbox Code Playgroud)

我需要像使用另一个GeoDataFrame一样设置CRS(像这样):

c=c.to_crs("+init=epsg:3857 +ellps=GRS80 +datum=GGRS87 +units=mi +no_defs")
Run Code Online (Sandbox Code Playgroud)

我试过这个:

crs={'init': 'epsg:3857'}
Run Code Online (Sandbox Code Playgroud)

还有这个:

hg=hg.to_crs("+init=epsg:3857 +ellps=GRS80 +datum=GGRS87 +units=mi +no_defs")
Run Code Online (Sandbox Code Playgroud)

......但没有运气.

一些重要的说明:

  1. 上面.to_crs方法工作的另一个GeoDataFrame来自一个形状文件,几何列是多边形而不是点.在应用.to_crs方法后,其"几何"值看起来像这样:

    POLYGON((-5973.005380655156 3399.646267693398 ...当我用hg GeoDataFrame尝试上面的内容时,它们仍然看起来像常规的纬度/经度坐标.

  2. 如果/当这个结果出来时,我会用多边形GeoDataFrame连接这些点,以便绘制两个(多边形顶部的点).

  3. 当我在使用.to_crs方法之前首先尝试连接GeoDataFrames,然后我一次在点和多边形行上使用该方法时,我收到以下错误:

    ValueError:无法转换朴素几何.请先在对象上设置crs.

提前致谢!

python-3.x geopandas

9
推荐指数
2
解决办法
8607
查看次数

从GeoPandas图中重新定位图例

我正在使用GeoPandas绘图功能绘制带有图例的地图.当我绘制时,我的传说出现在图的右上角.这是它的样子: 在此输入图像描述

我想将图例移到图表的下半部分.对于正常的matplotlib图,我通常会做这样的事情:

fig, ax = plt.subplots(1, figsize=(4.5,10))
lima_bank_num.plot(ax=ax, column='quant_cuts', cmap='Blues', alpha=1, legend=True)
ax.legend(loc='lower left')
Run Code Online (Sandbox Code Playgroud)

但是,不考虑此修改.

matplotlib geopandas

9
推荐指数
2
解决办法
4365
查看次数

使用 Geopandas,如何选择不在多边形内的所有点?

我有一个包含芝加哥地址的 DataFrame,我已将其地理编码为纬度和经度值,然后编码为 Point 对象(使 DataFrame 成为 GeoDataFrame)。一小部分已使用芝加哥以外的 LatLong 值进行了错误的地理编码。我有一个用于芝加哥边界(GeoDataFrame)的 shapefile,我想选择点位于芝加哥边界多边形之外的所有行。

选择多边形内的所有点很容易(通过 geopandas sjoin 函数),但我还没有找到一种选择不在多边形内的点的好方法。一个存在吗?

python pandas shapely geopandas

9
推荐指数
1
解决办法
4707
查看次数

安装geopandas时出错:在Anaconda中必须指定GDAL API版本

安装geopandas时引发此错误。我一直在网上寻找它的解决方案,但是他们都没有真正解释发生的事情以及如何解决它。这是完整的错误:

    Collecting geopandas
  Using cached https://files.pythonhosted.org/packages/24/11/d77c157c16909bd77557d00798b05a5b6615ed60acb5900fbe6a65d35e93/geopandas-0.4.0-py2.py3-none-any.whl
Requirement already satisfied: shapely in c:\users\alvaro\anaconda3\envs\tfdeeplearning\lib\site-packages (from geopandas) (1.6.4.post2)
Requirement already satisfied: pandas in c:\users\alvaro\anaconda3\envs\tfdeeplearning\lib\site-packages (from geopandas) (0.20.3)
Collecting fiona (from geopandas)
  Using cached https://files.pythonhosted.org/packages/3a/16/84960540e9fce61d767fd2f0f1d95f4c63e99ab5d8fddc308e8b51b059b8/Fiona-1.8.4.tar.gz
    Complete output from command python setup.py egg_info:
    A GDAL API version must be specified. Provide a path to gdal-config using a GDAL_CONFIG environment variable or use a GDAL_VERSION environment variable.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Alvaro\AppData\Local\Temp\pip-install-oxgkjg8l\fiona\
Run Code Online (Sandbox Code Playgroud)

python anaconda conda geopandas

9
推荐指数
8
解决办法
1万
查看次数

为 geopandas 添加图例

我有一张智利地图(http://labgeo.ufro.cl/fichas/chile_geo/ficha_cl_geo.html第一个链接上面写着“智利大陆”),想绘制它并添加一些我有纬度的中心点经度数据。

\n\n

我是 geopandas 和 matplotlib 的新手,但我设法使用这篇文章中 matplotlib 的建议答案以不同颜色的点的形式绘制地图:Color by Column Values in Matplotlib

\n\n

这是我的代码:

\n\n
#Loading data, since I am making the coordinates up they won\xc2\xb4t fit the map nicely but you will get the idea\n\nmap_= gpd.read_file("cl_continental_geo.shp")\ngeo_df_ = pd.DataFrame({"id":np.random.randint(20, size=133) ,"Latitude": np.random.normal(-34.406922,7.819504, 133), "Longitud": np.random.normal(-71.243350,1.254126, 133)})\n\ngeometry =[Point(xy) for xy in zip( geo_df_["Longitud"],geo_df_["Latitude"])]\ngeo_df_ =gpd.GeoDataFrame(geo_df_, crs={"init":"epsg:4326"},geometry= geometry)\n\n# creating color map for categories\ncategories = np.unique(geo_df_["id"])\ncolors = np.linspace(0, 1, len(categories))\ncolordict = dict(zip(categories, colors))\n\n#matching it to the geopandas df\ngeo_df_["Color"] = …
Run Code Online (Sandbox Code Playgroud)

python matplotlib legend shapefile geopandas

9
推荐指数
1
解决办法
2万
查看次数

geopandas:sjoin 'NoneType' 对象没有属性 'intersection'

我正在尝试对两个开源数据集进行空间连接。我遇到了一个AttributeError: 'NoneType' object has no attribute 'intersection'错误。通过确保删除空几何体似乎已经解决了类似的错误,但这似乎没有帮助。我还安装了 spatialindex-1.9.3 和 rtree-0.9.3。我正在使用 Python 3.8

import geopandas as gpd
import pandas as pd
from shapely.geometry import Point

# Import LSOA polygon data
LSOA_polygons = gpd.read_file('https://raw.githubusercontent.com/gausie/LSOA- 2011-GeoJSON/master/lsoa.geojson')

# Remove any empty geometry
LSOA_polygons = LSOA_polygons[LSOA_polygons.geometry.type == 'Polygon']

# UK charge point data
url_charge_points = 'http://chargepoints.dft.gov.uk/api/retrieve/registry/format/csv'
charge_points = pd.read_csv(url_charge_points, lineterminator='\n', low_memory=False, usecols=[0,3,4])

# Create a geometry column 
geometry = [Point(xy) for xy in zip(charge_points['longitude'], charge_points['latitude'])]

# Coordinate reference system : WGS84
crs = …
Run Code Online (Sandbox Code Playgroud)

python geopandas

9
推荐指数
1
解决办法
3482
查看次数