-1

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)
ajmnz
  • 742
  • 7
  • 19
  • You are trying to convert the header row. Before your for-loop put `next(reader)`. Of course then you will get the error `ValueError: could not convert string to float: '41.384..'` because of the trailing decimals. – Steven Rumbalski Mar 15 '20 at 15:36
  • When in doubt, print. Put `print(repr(latitude), repr(longitude))` before the failing `map` and see what you get. – tdelaney Mar 15 '20 at 15:38
  • @tdelaney: In this case that is unnecessary because the error message says directly what value it could not convert. – Steven Rumbalski Mar 15 '20 at 15:39
  • @StevenRumbalski - i am aware of the error message. Printing variables with unexpected data is generally useful and considering that the variable and its included text are the same, the error message could be confusing. – tdelaney Mar 15 '20 at 15:43

1 Answers1

1

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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561