Wtow
Wtow

Reputation: 108

Geopandas geometry to geojson in geopandas dataframe

I have a geopandas object and I want to conver geometry to string. Normaly geometry is like below

file = geopandas.read_file("test.TAB")
# its content is 

ID                                                            ***
MI_PRINX                                                      ***9.0

geometry                POLYGON ((4496597.53 4537154.3691, 4496022.574... 
Name: 0, dtype: object

I little bit blured the data as it is private. As it is seen, geometry is object of shapely.Polygon and I want to change it by its geojson format.

Polygon(...)

If I write something like below

file.iloc[0].geometry = geopandas.GeoSeries(file.iloc[0]).geometry.to_json()

I got this error:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  file.loc[0].geometry = "something"

I want to have a data like that:


{"type": "FeatureCollection", "features": [{"id": "0", "type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[4496597.53, 4537154.3691], [4496022.574, 4537169.5574], [4495738.723, 4537227.9468], [4495722.012, 4537167.8742], [4495576.619, 4536541.8022], [4495762.527, 4536487.3604], [4495791.462, 4536284.4807], [4495800.719, 4536212.8866], [4495810.617, 4536200.223], [4495837.107, 4536191.6469], [4495838.469, 4536186.0163], [4495795.469, 4536178.2817], [4495750.385, 4536174.0539], [4495724.456, 4536165.7583], [4495684.381, 4536143.9576], [4495678.931, 4536140.9919], [4495702.776, 4536145.22], [4495729.345, 4536153.7961], [4495771.905, 4536163.3739], [4495803.284, 4536165.8987], [4495842.678, 4536165.3376], [4495891.008, 4536160.1279], [4495943.867, 4536151.6919], [4496009.109, 4536152.2532], [4496096.593, 4536148.5863], [4496453.701, 4536103.3015], [4496597.53, 4537154.3691]]]}, "bbox": [4495576.619, 4536103.3015, 4496597.53, 4537227.9468]}], "bbox": [4495576.619, 4536103.3015, 4496597.53, 4537227.9468]}

I dont want to create new dataframe as its size is so big. Is there any way to do ?

Upvotes: 1

Views: 1738

Answers (2)

Tim
Tim

Reputation: 563

The geo_interface method may help you. It returns the geometries in the form of a dictionary.

file = file.__geo_interface__

Upvotes: 2

Michael Delgado
Michael Delgado

Reputation: 15442

Instead of to_geojson, you can convert all geometry columns to well known text with geopandas.GeoDataFrame.to_wkt:

file = file.to_wkt()

Upvotes: 0

Related Questions