エラー発生状況
以下のようなコードで、表題のエラーが発生した。
instance.coords
# ... 途中略
File "/usr/local/lib/python3.8/site-packages/shapely/geometry/base.py", line 960, in coords
raise NotImplementedError(
NotImplementedError: Multi-part geometries do not provide a coordinate sequence
原因
instance.geom_type
が "LineString"
なら instance.coords
を実行できるのですが、例えば "MultiLineString"
だったりすると、 .coords
を呼べないようです。
自分のコードからなぜ MultiLineString
が作成されたのかはわかりませんでしたが、 MultiLineString
は以下のように作成することができます。
from shapely.geometry import MultiLineString
multi_line_string = MultiLineString([
[(0.1, 0.2), (0.2, 0.2), (0.2, 0.1)],
[(0.2, 0.3), (0.3, 0.3), (0.3, 0.2)],
])
print(multi_line_string)
# 実行結果
MULTILINESTRING ((0.1 0.2, 0.2 0.2, 0.2 0.1), (0.2 0.3, 0.3 0.3, 0.3 0.2))
これに対して .coords
を呼び出そうとすると、同じエラーが発生します。
multi_line_string.coords
# 実行結果
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
Cell In[23], line 1
----> 1 multi_line_strg.coords
File /usr/local/lib/python3.8/site-packages/shapely/geometry/base.py:960, in BaseMultipartGeometry.coords(self)
958 @property
959 def coords(self):
--> 960 raise NotImplementedError(
961 "Multi-part geometries do not provide a coordinate sequence")
NotImplementedError: Multi-part geometries do not provide a coordinate sequence
対処
このような場合には、以下のようにして中身をバラしてあげたら、 .coords
を呼び出すことができました。
line_instances = []
if instance.geom_type == "MultiLineString":
for single_line in instance.geoms:
line_instances.append(single_line)
# 一つずつ coords を実行してあげる
line_instances[0].coords