【发布时间】:2020-04-12 20:13:50
【问题描述】:
我正在尝试将元组从数据帧转换为线串。这是我从 csv 文件导入的数据框的一部分。
Unnamed: 0 name route decode
0 0 Funshine! ofosF|mqaShJ@?rLh@d@veCIVd@LbEJfJ^f@lE?Rp@^L~g... '[(-105.28, 39.999), (-105.282, 39.998), (-105.282, 39.99), (-105.28, 39.995), (-105.282, 39.99), (etc)]'
如果我手动将解码列的内容复制并粘贴到 LineString() 条件中,它会转换它。我收到的错误发布在下面。
line = LineString(df.decode[0])
print(line)
Traceback (most recent call last):
File "shapely\speedups\_speedups.pyx", line 86, in shapely.speedups._speedups.geos_linestring_from_py
AttributeError: 'str' object has no attribute '__array_interface__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/taylo/PycharmProjects/PermitProj/Polyline Decode.py", line 20, in <module>
line = LineString(df.decode[1])
File "C:\Users\taylo\Miniconda3\envs\ExcelPermitExe\lib\site-packages\shapely\geometry\linestring.py", line 48, in __init__
self._set_coords(coordinates)
File "C:\Users\taylo\Miniconda3\envs\ExcelPermitExe\lib\site-packages\shapely\geometry\linestring.py", line 97, in _set_coords
ret = geos_linestring_from_py(coordinates)
File "shapely\speedups\_speedups.pyx", line 166, in shapely.speedups._speedups.geos_linestring_from_py
AssertionError
我最终想循环它,所以我将它设置为数据帧列解码。这是我为最终将线串写入列而创建的循环。
def linestringdecode(name, decode):
try:
return LineString(decode)
except:
print(name)
return np.nan
df['decode'] = df.apply(lambda x: linestringdecode(x[1], x[3]), axis=1)
如何编写此代码以避免此错误并将元组转换为数据框中的列?
【问题讨论】:
-
嗨,你能提供你的样本数据作为字典吗?与当前格式一样,它难以阅读/理解以及导入。 Pandas 有一个方便的方法
df.to_dict()。 -
输出量很大,但本质上就是这样,[118, 'Up Bear, Green, down to bike', '{icsFbaraS
AGqCPvWeAvBTpDlBnBj@tBtAnAjAbEG^CbA~ClBlBdAj@c@uA?s@~ @cCXeCl@Sx', '[(-105.28, 39.99), (-105.28, 39.99), (-105.28, 39.99), (-105.28, 39.99), (-105.282, 39.99), (列表有大约 50 或所以更多对)]' -
所以解码列包含多个元组(带坐标)但是总数据帧只有一行?还是有更多这样的行?
-
大概有500行类似这个
-
我找到了解决方案并编辑了我的答案。请注意,我必须将传递给
linestringdecode的列更改为索引 4 才能正确传递decode列作为参数。请检查这是否也适用于您的情况
标签: python-3.x pandas geopandas