【发布时间】:2020-06-26 21:20:39
【问题描述】:
我正在尝试将convert 一个csv 文件发送到geoJSON。调用map() 函数抛出
ValueError: could not convert string to float: 'latitude'。
这就是我现在的位置。无法弄清楚代码有什么问题。
CSV 样本:
id name host_id host_name neighbourhood_group neighbourhood latitude longitude...
2314 Flat 3242 John Someplace Anotherplace 41.384.. 41.384..
代码:
import csv, json
from geojson import Feature, FeatureCollection, Point
features = []
with open('listings_04-15.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for id, name, host_id, host_name, neighbourhood_group, neighbourhood, latitude, longitude, room_type, price, minimum_nights, number_of_reviews, last_review, reviews_per_month, calculated_host_listings_count, availability_365 in reader:
latitude, longitude = map(float, (latitude, longitude))
features.append(
Feature(
geometry = Point((longitude, latitude)),
properties = {
'name': name,
'host_name': host_name,
'neighbourhood_group': neighbourhood_group,
'neighbourhood': neighbourhood,
'room_type': room_type,
'price': price,
'minimum_nights': minimum_nights,
'number_of_reviews': number_of_reviews,
'last_review': last_review,
'reviews_per_month': reviews_per_month,
'availability_365': availability_365
}
)
)
collection = FeatureCollection(features)
with open('listings_04-15.geojson', "w") as f:
f.write('%s' % collection)
【问题讨论】:
-
您正在尝试转换标题行。在你的for循环之前放
next(reader)。当然,由于尾随小数,你会得到错误ValueError: could not convert string to float: '41.384..'。 -
如有疑问,请打印。将
print(repr(latitude), repr(longitude))放在失败的map之前,看看你会得到什么。 -
@tdelaney:在这种情况下,这是不必要的,因为错误消息直接说明了它无法转换的值。
-
@StevenRumbalski - 我知道错误消息。打印带有意外数据的变量通常很有用,并且考虑到变量及其包含的文本相同,错误消息可能会令人困惑。
标签: python csv geojson map-function