Creating a dataframe of Shapely polygons gives “Va

2019-08-08 18:43发布

问题:

I want to create a heatmap of say, provincial population of China and I found this guide to a similar problem here.

I have no problem going through the example code though I have to admit that I don't thoroughly understand them all. However when I was trying to mimic the example by using the shapefile of China, the code ran ok till the following

df_map = pd.DataFrame({
    'poly': [Polygon(xy) for xy in m.china],
    'ward_name': [ward['NAME'] for ward in m.china_info]})

It generates an error that says

ValueError: A LinearRing must have at least 3 coordinate tuples

Can someone please explain to me what causes this error?

回答1:

It is usually a good idea to include the complete error message in your question when you report an error. Python tracebacks include more information than the final error message, including the module and line number where the error occurred.

Your error is occurring in the shapely code. I can reproduce the error message by passing Polygon a sequence of just two points; Polygon requires at least three points. Here's an example.

Import Polygon from the shapely library:

>>> from shapely.geometry import Polygon

Passing a sequence of three points works:

>>> p = Polygon([(0, 0), (0, 1), (1, 1)])

But giving just two points causes the error:

>>> p = Polygon([(0, 0), (0, 1)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/warren/anaconda/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 229, in __init__
    self._geom, self._ndim = geos_polygon_from_py(shell, holes)
  File "/home/warren/anaconda/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 445, in geos_polygon_from_py
    geos_shell, ndim = geos_linearring_from_py(shell)
  File "/home/warren/anaconda/lib/python2.7/site-packages/shapely/geometry/polygon.py", line 393, in geos_linearring_from_py
    "A LinearRing must have at least 3 coordinate tuples")
ValueError: A LinearRing must have at least 3 coordinate tuples

Apparently there is an item in m.china that has fewer than three points. You are using ipython, so you could print m.china before attempting to create df_map. That should help you determine what is going on.