Python 使用线字符串将CSV转换为Geojson
我不熟悉地理空间数据,需要一种从CSV中获取以下格式数据的方法:Python 使用线字符串将CSV转换为Geojson,python,geojson,kepler.gl,Python,Geojson,Kepler.gl,我不熟悉地理空间数据,需要一种从CSV中获取以下格式数据的方法: 纬度、经度、高度、时间戳、行程标识符 并转换为适用于kepler.gl的geojson,格式为: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "vendor": "A", "vol":20}, "geometry": { "type"
纬度、经度、高度、时间戳、行程标识符
并转换为适用于kepler.gl
的geojson,格式为:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": { "vendor": "A",
"vol":20},
"geometry": {
"type": "LineString",
"coordinates": [
[-74.20986, 40.81773, 0, 1564184363],
[-74.20987, 40.81765, 0, 1564184396],
[-74.20998, 40.81746, 0, 1564184409]
]
}
}
]
}
我在Python中的尝试(主要基于)没有成功;这将返回一个ValueError,我看不到一种合并多行线的方法,因为记录之间的坐标对数量会发生变化
import csv, json
from geojson import Feature, FeatureCollection, Point, LineString
features = []
with open('Trips.csv', newline='', encoding='utf-16') as csvfile:
reader = csv.reader(csvfile, delimiter=' ')
for Latitude, Longitude, Altitude, Timestamp, ID in reader:
Latitude, Longitude = map(float, (Latitude, Longitude))
features.append(
Feature(
geometry = LineString([Latitude,Longitude,Altitude,Timestamp]),
properties = {
'ID': ID,
}
)
)
collection = FeatureCollection(features)
with open("Trips.json", "w") as f:
f.write('%s' % collection)
错误提示:
ValueError Traceback (most recent call last)
<ipython-input-1-5dadf758869b> in <module>
9 features.append(
10 Feature(
---> 11 geometry = LineString([Latitude,Longitude,Altitude,Timestamp]),
12 properties = {
13 'ID': ID
~/anaconda3/anaconda3/lib/python3.7/site-packages/geojson/geometry.py in __init__(self, coordinates, validate, precision, **extra)
30 super(Geometry, self).__init__(**extra)
31 self["coordinates"] = self.clean_coordinates(
---> 32 coordinates or [], precision)
33
34 if validate:
~/anaconda3/anaconda3/lib/python3.7/site-packages/geojson/geometry.py in clean_coordinates(cls, coords, precision)
53 new_coords.append(round(coord, precision))
54 else:
---> 55 raise ValueError("%r is not a JSON compliant number" % coord)
56 return new_coords
57
ValueError: '0' is not a JSON compliant number
ValueError回溯(最近一次调用)
在里面
9.附加功能(
10特点(
--->11几何图形=线字符串([纬度、经度、高度、时间戳],
12个属性={
13“ID”:ID
~/anaconda3/anaconda3/lib/python3.7/site-packages/geojson/geometry.py in uuuuu init_uuuu(self、坐标、验证、精度,**额外)
30超级(几何,自).\uuuuu初始(**额外)
31 self[“坐标”]=self.clean_坐标(
--->32坐标或[],精度)
33
34如果验证:
~/anaconda3/anaconda3/lib/python3.7/site-packages/geojson/geometry.py,坐标为干净坐标(cls、坐标、精度)
53新坐标追加(圆形(坐标,精度))
54.其他:
--->55 raise VALUERROR(“%r”不是符合JSON的编号“%coord”)
56返回新坐标
57
ValueError:“0”不是符合JSON的数字
问题似乎在于您正在将字符串传递给需要数字的API
for Latitude, Longitude, Altitude, Timestamp, ID in reader
应替换为将字符串转换为数字的代码。类似于:
for float(Latitude), float(Longitude), int(Altitude), int(Timestamp), ID in reader
数据示例:
51.467525 -0.445004 0 1569324754 EIN159
看起来前两个字段是浮点数,字段3,4是整数,字段5是字符串。您可以共享堆栈跟踪并指向引发错误的行吗?您也可以共享csv吗?更新了有错误的问题。csv的摘录是。错误消息的最后一行拒绝第三列中的任何数字CSV(高度)。指向CSV的链接无效。请将其上载到pastebin或尝试其他链接。请参阅我的答案-我认为它现在应该可以工作了。