【问题标题】:How to remove unwanted double quotes when converting CSV to GeoJSON将 CSV 转换为 GeoJSON 时如何删除不需要的双引号
【发布时间】:2018-04-09 14:59:46
【问题描述】:

我开始使用 Python3,我正在编写一个脚本来将 CSV 文件转换为 GeoJSON 文件。 转换有效,但我的坐标仍有问题,格式不正确。我需要删除双引号,但它不起作用。

这是我的部分代码:

def readCsvFile():
    features=[]
    geoJson={}
    with open('resources/data_export.csv',newline= '') as csvfile:
        csvReader = csv.DictReader(csvfile,delimiter=',',quotechar='|')
        for row in csvReader:
            features.append({'type': 'Feature',
                            'geometry': {
                                'type': 'Point', "coordinates" : [str(row['longitude']), str(row['latitude'])]}, 'properties': {'id': decodeString(row['id']), 'field1': decodeString(row['field1']), 'field2': decodeString(row['field2'])})

    geoJson = {'type': 'FeatureCollection', 'features': features}
    return json.dumps(geoJson)

我得到了这个结果:

{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": ["16.394564", "48.246426"]}, "properties": {"id": "0", ...

虽然我应该得到:

{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.394564, 48.246426]}, "properties": {"id": "0",

【问题讨论】:

  • 在您的预期结果中,您的坐标列表中仍然有两个",这是正确的吗?
  • 您确实意识到json.dumps 返回str 对吧?
  • 是的,这正是我需要删除的内容
  • 尝试发布你的data_export.csv的前两行左右
  • 我在回答中建议的浮点转换适用于您提供的行..(刚刚在 Python 3.6 上测试过)我认为您可能在其他地方有无效行

标签: python json python-3.x csv geojson


【解决方案1】:

尝试将其转换为浮点数而不是字符串:

"coordinates" : [float(row['longitude']), float(row['latitude'])]}

【讨论】:

  • 我试过了,我得到了那个错误:'type': 'Point', "coordinates" : [float(row['longitude']), float(row['latitude'] )]},ValueError:无法将字符串转换为浮点数:
  • float("16.394564") 适合我。 print(row['longitude']) 是什么?
  • 我假设您的 row['longitude'] 和 row['latitude'] 包含无法解析为浮点数的无效数据...您能否如上所述发布它们的结果?
  • HoudaF:根据您在问题中显示的结果,这无关紧要,但请尝试改用float(str(row['longitude']))float(str(row['latitude']))。正如 Orphamiel 所说,您似乎有一些无效数据,除非您编辑问题以包含 csv 输入文件中的一些实际示例数据,否则我们无法帮助您。
  • 完美,当我尝试只使用 2 行而不是 1000 行时,它起作用了,正如你提到的,有一些无效数据。谢谢
【解决方案2】:

我在不同的项目中做过很多这样的事情。我喜欢使用 pandas 并重写了您可以使用的代码示例(如果您有兴趣的话)。 Pandas 将确保您的列自动转换为浮点数。

import pandas as pd
import json
import requests

def df2geojson(df, latlng = []):
    """Function converting pandas table to GEOJSON-format-string"""
    features = []
    for ind, row in df.iterrows():
        geometry = dict(type='Point', coordinates=row[latlng].tolist())
        properties = {k:v for k,v in row.items() if k not in latlng}
        features.append(dict(type='Feature',geometry=geometry, properties=properties))
    return dict(type="FeatureCollection",features=features)

data = '''\
id,field1,field2,longitude,latitude
0,100,100,0,16.394564,48.246426
1,200,200,0,16.494564,48.346426'''

filelikeobject = pd.compat.StringIO(data)          # simulates a file-object
df = pd.read_csv(filelikeobject)                   # should be: 'resources/data_export.csv'
jsonstr = df2geojson(df, ['latitude','longitude']) # pass dataframe and latlng colnames

#with open('output.geojson','w') as f:              # finally write to file
#    json.dump(jsonstr,f,indent=2)                  # disabled

baseurl = 'http://geojson.io/#data=data:application/json,'     # geojson.io url
url = baseurl+requests.utils.requote_uri(json.dumps(jsonstr))  # encode the json

print(url)

生成可以单击的 URL(如果文件很大,则使用文件转储):http://geojson.io/#data=data:application/json,%7B%22type%22:%20%22FeatureCollection%22,%20%22features%22:%20[%7B%22type%22:%20%22Feature%22,%20%22geometry%22:%20%7B%22type%22:%20%22Point%22,%20%22coordinates%22:%20[48.246426,%2016.394564000000003]%7D,%20%22properties%22:%20%7B%22id%22:%20100.0,%20%22field1%22:%20100.0,%20%22field2%22:%200.0%7D%7D,%20%7B%22type%22:%20%22Feature%22,%20%22geometry%22:%20%7B%22type%22:%20%22Point%22,%20%22coordinates%22:%20[48.346426,%2016.494564]%7D,%20%22properties%22:%20%7B%22id%22:%20200.0,%20%22field1%22:%20200.0,%20%22field2%22:%200.0%7D%7D]%7D

【讨论】:

  • 谢谢,好像很有趣,所以我会开始使用它。
  • @HoudaF 如果您正在使用 csv 文件,那么除了 pandas(今天)真的没有其他选择。
  • 我正在处理一个 10000 行的文件作为开始,但这仅适用于 1000 行,我将尝试 Pandas,我提到我正在开始,所以我真的需要这些建议。谢谢
  • @HoudaF 另请注意,在这种情况下,仅指定 lat 和 lng 的列,其他列成为属性。 Pandas 还允许您插入 nrows= 参数来限制行数。
  • 很好,非常感谢。我会立即开始使用它。
猜你喜欢
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 2016-02-02
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多