Recently read “a dream of Red Mansions”, read ningrong two mansion by yuan concubine’s order to go to the temple of Humility jiao festival, the centaur in drove, the scene of the car cloud cloud, very magnificent! Judge Zhang intends to talk to Baoyu in the view of purity, but the baoyu nature of daiyu is disgusted to the extreme. On the second day, Baoyu felt uncomfortable because of Taoist Priest Zhang’s words and was unhappy because Of Daiyu’s heatstroke. Go to specially for this xiaoxiang pavilion to see Daiyu, do not know however the visit that is good for originally however because of daiyu’s bigotry, capricious small temper caused the misunderstanding of two people. So far in the park xiaoxiang pavilion two people are crying and make, and even alerted jia Mother. Although they were in the same room, they were in one heart, one sobbing behind her face, the other heaving a sigh. It was really disturbing to see.

No wonder, what young man and girl in love is not in such feelings against each other to come over!

What is called:

With a smile on his brow,

The figure of ran ran was pathetic.


For a long time I felt that Python, as a weakly typed language, was awkward to write and always felt strange, either because I was used to writing strongly typed languages or because of Java or Golang preconceptions. I didn’t want to get into Python, thought the syntax was slow and un” authentic “, and even though it was powerful and problem-solving sharp, I didn’t think it was a programming language worth learning.

Until I read a post that solved a problem in a few lines of code and suddenly seemed to change my mind about Python.

In fact, as a tool, there is no good or bad language, whether static or dynamic language, are standing on the shoulder of the compiler to do some work to solve business problems. As a high-level language, Python’s concise syntax and powerful third-party libraries are its biggest strengths. As long as it makes it easier to solve problems, it is a good tool.

Geopandas Geopandas Geopandas Geopandas

Front

Due to the fact that many third-party library limited servers installed with PIP are in foreign countries, the download speed is slow.

So to speed up the download, we can configure the global PIP image download source as follows:

1. Python configuration steps:

  • usewin+EOpen file Manager and type in the address bar%appdata%;
  • Create a new one in this directorypipFolder.
  • inpipUnder the folder, create a folderpip.iniFile;
  • inpip.iniEnter the following content in the file:

[global]

timeout=6000 index-url = mirrors.aliyun.com/pypi/simple

trusted-host = mirrors.aliyun.com

At this point, we can easily install any third party library using PIP.

2. Configuration procedure using Anaconda:

  • Go to the Scripts directory of the Anaconda installation directory.
  • Right-click the CMD command line window, type the following command, and press Enter.

Conda config – add channels mirrors.tuna.tsinghua.edu.cn/anaconda/pk… Conda config – add channels mirrors.tuna.tsinghua.edu.cn/anaconda/pk… Conda config – add channels mirrors.tuna.tsinghua.edu.cn/anaconda/cl… Conda config –set show_channel_urls yes

3. View the configuration result.

conda config –show channels

About GeoPandas

GeoPandas is an open source project to make working with geospatial data in python easier. GeoPandas extends the datatypes used by pandas to allow spatial operations on geometric types. Geometric operations are performed by shapely. Geopandas further depends on fiona for file access and matplotlib for plotting.

Geopandas Package details:

As the name suggests, GeoPandas extends the popular data science library Pandas by adding support for geospatial data.

The core data structure in GeoPandas is geopandas.geodataframe, a subclass of PANDAS.DataFrame, which stores geometric columns and performs spatial operations. Geopandas.geoseries is a subclass of Pandas.Series, used to deal with geometric graphics. Thus, your GeoDataFrame is a combination of pandas.Series with traditional data (numbers, bools, text, etc.) and Geopandas.geoseries with geometry (points, polygons, etc.).

Install

If you are using Anaconda, type the following command:

conda install geopandas
Copy the code

If you are using Python, go to the following site to download the dependency first, as PIP will not help us install the dependency ourselves.

www.lfd.uci.edu/~gohlke/pyt…

Depending on your Python version and OS, select the appropriate dependency package, including

Fiona
pyproj
rtrre
shapely
GDAL
Copy the code

The actual installation sequence will result in an error. Therefore, the actual installation sequence is as follows:

GDAL->Fiona->pyproj->shapely->rtree
Copy the code

The installation command is, using GDAL as an example, as well as other commands:

PIP install GDAL 3.4.2 - cp37 - cp37m - win_amd64. WHLCopy the code

Verify that the installation is successful:

Example

Note: The following code can be run separately and output to the console


geopandas.GeoSeries

Structure POINT

from shapely.geometry import Point
from geopandas import geopandas

s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
print(s)
Copy the code

Construct a POINT with a coordinate system

from shapely.geometry import Point
from geopandas import geopandas

s = geopandas.GeoSeries(
    [Point(1, 1), Point(2, 2), Point(3, 3)], crs="EPSG:3857")
Copy the code

geopandas.GeoSeries.area

1. Construct a geographic set and measure the area

from shapely.geometry import Polygon, LineString, Point
s = geopandas.GeoSeries(
    [
        Polygon([(0, 0), (1, 1), (0, 1)]),
        Polygon([(10, 0), (10, 5), (0, 0)]),
        Polygon([(0, 0), (2, 2), (2, 0)]),
        LineString([(0, 0), (1, 1), (0, 1)]),
        Point(0, 1)
    ]
)
area = s.area
print(area)
Copy the code

geopandas.GeoSeries.boundary

Construct a geographic collection and return a low-dimensional object (extract)

from shapely.geometry import Polygon, LineString, Point from geopandas import geopandas s = geopandas.GeoSeries([Polygon([(108.923166,35.363084), (109.322899,35.274691), (109.355755,35.283365),(108.936301,35.380966),(108.923166,35.363084)]), LineString([(0, 0), (1, 1), (1, 0)]), Point(0, 0), ] ) boundary = s.boundary print(boundary)Copy the code

geopandas.GeoSeries.x

Gets the X value of the geographic object

from shapely.geometry import Point
from geopandas import geopandas

s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
s.x
print(s.x)
Copy the code

geopandas.GeoSeries.within

Returns whether two geometers are contained, with the value bool

from shapely.geometry import Polygon, LineString, Point
from geopandas import geopandas

s1 = geopandas.GeoSeries(
    [
        Polygon([(0, 0), (2, 2), (0, 2)]),
        Polygon([(0, 0), (1, 2), (0, 2)]),
        LineString([(0, 0), (0, 2)]),
        Point(0, 1),
    ],
)
s2 = geopandas.GeoSeries(
    [
        Polygon([(0, 0), (1, 1), (0, 1)]),
        LineString([(0, 0), (0, 2)]),
        LineString([(0, 0), (0, 1)]),
        Point(0, 1),
    ],
    index=range(1, 5),
)

polygon = Polygon([(0, 0), (2, 2), (0, 2)])
within = s1.within(polygon)

print(within)

print(s1.within(s2))

print(s1.within(polygon))
Copy the code

geopandas.GeoSeries.to_json

Geographic collection to JSON

from shapely.geometry import Point
s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
s.to_json()
Copy the code

geopandas.GeoDataFrame.set_crs

GeoDataFrame set CRS

import os
import sys
import pyproj
from shapely.geometry import Point
from geopandas import geopandas

# os.environ['PROJ_LIB'] = os.path.dirname(sys.argv[0])
# os.environ['PROJ_LIB'] = "D:\ProgramData\Anaconda3\Library\share\proj\"

d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
gdf = geopandas.GeoDataFrame(d)
print(gdf.crs)
gdf = gdf.set_crs('epsg:4490')
print(gdf.crs)
Copy the code

geopandas.read_file

Reading vector files

from geopandas import geopandas from geopandas.geodataframe import GeoDataFrame df = Geopandas. GeoDataFrame. From_file (" W: \ \ desktop \ GeYao \ graduation thesis GIS \ \ city park district six SHP planar. "SHP) head = df. Head (6) print (the head)Copy the code

Missing and empty geometries

Default and null values

from shapely.geometry import Polygon

from geopandas import geopandas

s = geopandas.GeoSeries([Polygon([(0, 0), (1, 1), (0, 1)]), None, Polygon([])])

print(s.area)
print(s.union(Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])))
print(s.intersection(Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])))
Copy the code

1. Creating a GeoDataFrame from a DataFrame with coordinates

import pandas as pd import geopandas import matplotlib.pyplot as plt df = pd.DataFrame( {'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'], 'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'], 'Latitude': [34.58, 15.78, 33.45, 4.60, 10.48], 'Longitude' : [-58.66, -47.91, -70.66, -74.08, -66.86]}) geometry=geopandas.points_from_xy(df.Longitude, df.Latitude)) print(gdf.head()) world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) # We restrict to South America. ax = world[world.continent == 'South America'].plot( color='white', edgecolor='black') # We can now plot our ``GeoDataFrame``. gdf.plot(ax=ax, color='red') plt.show()Copy the code

The running results are as follows:

2. create a Isodensity map

import pandas as pd import numpy as np import pandas as pd import matplotlib.pyplot as plt import geopandas as gpd from shapely.geometry import Point, AdjustText as aT Import mapclassify Import Warnings plt.rcParams[' adjust.sans-serif '] = ['SimHei'] Plt.rcparams ['axes. Unicode_minus '] = False map_name = "Xi 'an area topic map" warnings. Filterwarnings ('ignore') # Read data in geodataframe format Geo_ = gpd.geodatafame. From_file ('W: Google_Download ', Print (geo_) geo_. Head (3) df = pd.read_csv(r 'c :\Users\ wanbin \Desktop\ Poi.csv ', Encoding =' utF-8 ') df['geometry'] = list(zip(df['wgs84_lon'], df[' wGS84_lat '])) # Gpd_df = GPD.GeoDataFrame(df) base = df['geometry'] Plot (color='lightblue', edgecolor='grey', figsize=(15, 15)) marker="o", markersize=50, Alpha =0.01) # Add the location plt.gca().xaxis.set_major_locator(plt.nulllocator ()) # remove the X-axis scale Plt.gca ().yaxis.set_major_locator(plt.nulllocator ()) # remove yaxis scale geo_.plot(figsize=(8, 6), # image size column='name', # scheme='quantiles', # MapClassify- legend=True, # legend= 'Pastel1_r', Format ('{}'. Format (map_name), fontsize=18, Fontweight ='bold') # display grid, Plt.grid (True, alpha=0.5) plt.show() #plt.savefig('./image/{}.png'. Format (map_name), dpi=300)Copy the code

The following is the operation result. The red patch is POI point in Cheng6 district of Xi ‘an, which is more than 210,000 points.

Summary

Geopandas has many functions. Here I have selected several functions to run and learn. If you are interested, you can learn them according to your own needs.

Geopandas is a combination of Python and GIS. According to its website, Geopandas provides a variety of features, including extensive geographical data processing, rapid mapping of basic maps, and flexible map design.

I think it can meet most of the GIS small scenes, but in the case of more complex business scenes or functions, I may have to rely on desktop software to assist the completion.

In general, I feel that it is very sharp to solve some small GIS problems.

Worth learning!

Error Summary

Here is an additional record of a mistake, I check, online information for a long time to calculate the solution.

Record down here for everyone’s reference!

Geopandas (geopandAs) can be used to read vector files or maps, causing an invalid projection error in pyProJ library.

Pyproj. Ecception. CRSError: Invalid the projection: epsg: 2263: (Internal Proj Error:…)

This is a common error troubleshooting scheme provided on Proj’s official website, which can provide ideas, but does not solve the problem.

Why am I getting the error “Cannot find proj.db”?

The file proj.db must be readable for the library to properly function. Like other resource files, it is located using a set of search paths. In most cases, the following paths are checked in order:

  • A path provided by the environment variable PROJ_LIB.
  • A path built into PROJ as its resource installation directory (typically .. /share/proj relative to the PROJ library).
  • The current directory.

Note that if you’re using conda, activating an environment sets PROJ_LIB to a resource directory located in that environment.

Proj. Db may have a problem with this file, because SQLite error is always reported. Specifically, it is an error about initializing the query.

Print the current pyProJ resource pointing path using the following code:

data_dir = pyproj.datadir.get_data_dir()
print(data_dir)
Copy the code

On my laptop the path points to D: ProgramData Anaconda3 Lib site-packages PyProj proj_dir share proj

The proj. db in this file is about 7.7m, but the proj. db in the /share/ Proj installation directory of Anaconda is 5.36m.

I couldn’t think of a solution, Replace proj.db under D: ProgramData Anaconda3 Lib site-packages pyproj proj_dir share proj with proj.db under Anaconda installation directory /share/proj.

Just as the saying goes: “Inadvertently inserted willow trees grow shade”, unexpectedly the problem seems to be solved. The program can correctly vector file reading and drawing.

Logically, dependencies downloaded by Anaconda are handled better and are harder to make.

I remember I saw on the Internet that Pyproj library is built on EPSG database, this error may be caused by a version conflict.

Hopefully we can figure out why later.

If you know the reason, please write to me