GeoPandas - 网格分散数据和重新投影

GeoPandas - grid scattered data and reproject

我需要将 GeoPandas 数据框中的分散数据网格化为规则网格(例如 1 度)并获取各个网格框的平均值,然后使用各种投影绘制此数据。

我使用 gpd_lite_toolbox.

设法实现的第一点

我可以在简单的经纬度地图上绘制此结果,但是尝试将其转换为任何其他投影失败。

这是一个小例子,其中包含一些人工数据来说明我的问题:

import gpd_lite_toolbox as glt
import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
from shapely import wkt

# creating the artificial df
df = pd.DataFrame(
{'data': [20, 15, 17.5, 11.25, 16],
 'Coordinates': ['POINT(-58.66 -34.58)', 'POINT(-47.91 -15.78)',
                 'POINT(-70.66 -33.45)', 'POINT(-74.08 4.60)',
                 'POINT(-66.86 10.48)']})

# converting the df to a gdf with projection
df['Coordinates'] = df['Coordinates'].apply(wkt.loads)
crs = {'init': 'epsg:4326'}
gdf = gpd.GeoDataFrame(df, crs=crs, geometry='Coordinates')

# gridding the data using the gridify_data function from the toolbox and setting grids without data to nan
g1 = glt.gridify_data(gdf, 1, 'data', cut=False)
g1 = g1.where(g1['data'] > 1)

# simple plot of the gridded data
fig, ax = plt.subplots(ncols=1, figsize=(20, 10))
g1.plot(ax=ax, column='data', cmap='jet')

# trying to convert to (any) other projection
g2 = g1.to_crs({'init': 'epsg:3395'})

# I get the following error
---------------------------------------------------------------------------

AttributeError: 'float' object has no attribute 'is_empty'

如果这能解决问题,我也很乐意使用不同的网格化函数

你的 g1 conatin 太多 NaN 价值。

g1 = g1.where(g1['data'] > 1)
print(g1)

                                               geometry   data
0                                                   NaN    NaN
1                                                   NaN    NaN
2                                                   NaN    NaN
3                                                   NaN    NaN
4                                                   NaN    NaN
5     POLYGON ((-74.08 5.48, -73.08 5.48, -73.08 4.4...  11.25
...

您应该使用 g1[g1['data'] > 1] 而不是 g1.where(g1['data'] > 1)

g1 = g1[g1['data'] > 1]
print(g1)

                                               geometry   data
5     POLYGON ((-74.08 5.48, -73.08 5.48, -73.08 4.4...  11.25
181   POLYGON ((-71.08 -32.52, -70.08 -32.52, -70.08...  17.50
322   POLYGON ((-67.08 10.48, -66.08 10.48, -66.08 9...  16.00
735   POLYGON ((-59.08 -34.52, -58.08 -34.52, -58.08...  20.00
1222  POLYGON ((-48.08 -15.52, -47.08 -15.52, -47.08...  15.00

g2 = g1.to_crs({'init': 'epsg:3395'})
print(g2)
                                               geometry   data
5     POLYGON ((-8246547.877965705 606885.3761893312...  11.25
181   POLYGON ((-7912589.405585884 -3808795.10464339...  17.50
322   POLYGON ((-7467311.442412791 1165421.424891677...  16.00
735   POLYGON ((-6576755.516066602 -4074627.00861716...  20.00
1222  POLYGON ((-5352241.117340593 -1737775.44359649...  15.00