I have a GeoDataFrame as follows:
import pandas as pd
import geopandas
df = pd.DataFrame([[1, 0], [0, 1]], columns=[['location', 'location'], ['x', 'y']])
df["geometry"] = geopandas.points_from_xy(df['location','x'], df['location', 'y'])
gdf = geopandas.GeoDataFrame(df, geometry="geometry", crs="EPSG:4326")
gdf
# location geometry
# x y
# 0 1 0 POINT (1.00000 0.00000)
# 1 0 1 POINT (0.00000 1.00000)
Problem: Using the GeoDataFrame to_file
method results in a not very explicit TypeError
:
gdf.to_file("test.shp")
# ...
#
# TypeError: Cannot interpret '<geopandas.array.GeometryDtype object at 0x7f99fdf45070>' as # a data type
What could be the reason and how could this be solved?
Note: This error is already described in another question but in an unrelated context.
It appears that GeoDataFrame.to_file
requires a column with exactly the name geometry
: No multilevel columns, no geom
, no geometry_
, etc.
Therefore, the above problem can be solved by flattening the column index:
gdf_flatcols = gdf.set_axis([x[0] if x[1] == "" else "_".join(x)
for x in gdf.columns], axis=1)
and to_file
will work just fine:
gdf_flatcols.to_file("test.shp")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.