地理数据框架.to_file函数:字段类型<class 'bytes'>无效。

8

我正在处理shp文件,但是在保存geodataframe到shp文件时遇到了问题。

import pandas as pd
import numpy as np
import os
import geopandas
location = '/home/braulio/Documents/example.shp'
datos = geopandas.read_file(location, encoding='UTF-8')

我处理数据没有问题,但当我尝试保存时出现了问题。

A.to_file(r"/home/braulio/Documents/example2.shp")

并返回一个错误:

ValueError                                Traceback (most recent call last)
<ipython-input-23-6a842789b4b4> in <module>
----> 1 A.to_file(r"/home/braulio/Documents/example2.shp")

~/anaconda3/envs/braulio/lib/python3.7/site-   packages/geopandas/geodataframe.py in to_file(self, filename, driver,   schema, **kwargs)
411         """
412         from geopandas.io.file import to_file
--> 413         to_file(self, filename, driver, schema, **kwargs)
414 
415     def to_crs(self, crs=None, epsg=None, inplace=False):

~/anaconda3/envs/braulio/lib/python3.7/site-packages/geopandas/io/file.py in to_file(df, filename, driver, schema,**kwargs)
109         with fiona.open(filename, 'w', driver=driver, crs=df.crs,
110                         schema=schema, **kwargs) as colxn:
--> 111             colxn.writerecords(df.iterfeatures())
112 
113 

~/anaconda3/envs/braulio/lib/python3.7/site-packages/fiona/collection.py in writerecords(self, records)
347         if self.mode not in ('a', 'w'):
348             raise IOError("collection not open for writing")
--> 349         self.session.writerecs(records, self)
350         self._len = self.session.get_length()
351         self._bounds = self.session.get_extent()

fiona/ogrext.pyx in fiona.ogrext.WritingSession.writerecs()

fiona/ogrext.pyx in fiona.ogrext.OGRFeatureBuilder.build()

ValueError: Invalid field type <class 'bytes'>

你在处理数据方面做了什么?在读取数据后,直接将数据框保存下来时,是否遇到了相同的问题?看起来你正在尝试保存一些Shapefile不支持的数据类型。 - martinfleis
你的地理数据框中有一列无效的数据类型(dtype)。看起来,bytes 数据类型无法被 geopandas 处理或写入 shapefiles。检查你的列的数据类型,并删除或转换该列。你可以谷歌“检查数据帧列数据类型”以获取如何执行此操作的说明。 - jberrio
在检查数据框列的dtype后,所有列的类型都是object。我删除了shp文件中的一列,然后就可以工作了,但我并不真正理解发生了什么。 - Braulio Linares
3个回答

6

'bytes' 和一些其他类型,比如 'list',在 shapefile 中不受支持。这里是一个讨论此问题的 GitHub issue 的链接。

我建议删除包含 'bytes' 类型对象的列,然后保存 shapefile。

如果该列真的很重要,请将其值更改为 'string' 类型,然后保存 shapefile。


1
我将问题解决,将编码更改为Latin-1。
datos = geopandas.read_file(location, encoding='latin1')

0
以下内容在我的情况下有效("ValueError:无效的字段类型""),希望对您有所帮助:
A = A.apply(pd.to_numeric, errors='ignore')
A = gpd.GeoDataFrame(A) # optional
A.set_geometry(col='geometry', inplace=True) # optional
A.to_file(path)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接