【问题标题】:Python map() function - ValueError: could not convert string to float [duplicate]Python map()函数-ValueError:无法将字符串转换为浮点数[重复]
【发布时间】: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


【解决方案1】:

您的代码正在读取 csv 文件的标题,并试图解释它。只需添加一行

next(reader)

for 循环之前,你应该没问题。

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 2018-04-23
    • 2015-03-25
    • 2021-12-23
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    相关资源
    最近更新 更多