1

I am using GeoPandas' read_file function to read a shapefile and to_file function to save to GeoJSON. This is working fast and good.

But I need to save only the attribute table without the geometry or with empty geometry.

How can I do that?

import geopandas as gpd
import pandas as pd
import fiona


def main():
filepath = "D:\\DATA\layers1\\TTL_TRANSPORT.shp"
destination = "D:\\DATA\\jsonfiles\sample.json"

gdf = gpd.read_file(filepath)

df = pd.DataFrame(gdf)
columns_without_geom = gdf.columns

print( columns_without_geom)

if 'geometry' in columns_without_geom:
   columns_without_geom.drop('geometry')

gdf = gdf[columns_without_geom]
df = pd.DataFrame(gdf)
df.to_json(destination)
df.to_json(destination)
0
5

GeoPandas is an addon to Pandas where a geometry column has special meaning and writing output writes geospatial file formats. If you want to export just the non-spatial data, the easiest way would be to create a plain Pandas DataFrame from your GeoDataframe, so the geometry column loses its special meaning, and then remove it.

To do so in one "step":

df = pd.DataFrame(gdf).drop(columns="geometry")

Then you can use the resulting DataFrame's to_json() as intended.

df.to_json(destination)
0

If needed, you can convert your dataframe to pandas dataframe and save it with:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html

so something like:

df = pd.DataFrame(gdf)
df.to_json(output)

You might have to select columns without geometry.

columns_without_geom = gdf.columns
if 'geometry' in columns_without_geom: 
     columns_without_geom.remove('geometry')

gdf = gdf[columns_without_geom]
df = pd.DataFrame(gdf)
df.to_json(output)
6
  • hi jan thanks for your reply i am getting this error " module 'geopandas' has no attribute 'DataFrame' " – lord corwin Jul 24 '20 at 13:31
  • now i am getting this error "columns_without_geom.remove('geometry') AttributeError: 'Index' object has no attribute 'remove' " – lord corwin Jul 24 '20 at 13:50
  • pandas.Index are very similar to python sets, you should use .difference(['geometry']). Since set difference operation supports non-overlapping sets, you can avoid the if and instead use gdf = gdf.loc[:,gdf.columns.difference(['geometry'])] – Javier JC Jul 24 '20 at 14:13
  • hola Javier i am getting this error "No geometry data set yet (expected in column 'geometry'.)" while gdf.to_file – lord corwin Jul 24 '20 at 14:30
  • Now the error is, you removed geometry column. So you have to cast it to pandas dataframe as in my comment and save it via pandas and not geopandas, since it does not have geometry. – Jan Doležal Jul 24 '20 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.