Search code examples
pythoncsvgeojsonmap-function

Python map() function - ValueError: could not convert string to float


I'm trying to convert a csv file to geoJSON. Calling the map() function throws ValueError: could not convert string to float: 'latitude'. This is where I'm at now. Can't figure out what's wrong with the code.

CSV Sample:

id    name  host_id  host_name  neighbourhood_group  neighbourhood  latitude  longitude...
2314  Flat  3242     John       Someplace            Anotherplace   41.384..  41.384..

Code:

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)

Solution

  • Your code is reading the header of the csv file, trying to interpret it. Simply add the line

    next(reader)
    

    before the for loop, and you should be OK.