如何使用Python以快速方式向json添加信息

时间:2014-05-24 11:48:07

标签: python json csv pandas

我有包含地方的geojson文件。其中“'停车':0”。

'type': 'Feature', 
'properties': {
 ...// Other fields
'latitude': -74.0121613846062,
'longitude': 40.7043040747924,
'parking': 0 }

我想从另一个csv文件数据集更新它。

-------------------------------------------
 latitude    + Longitude + Possible_parking 
-------------------------------------------
-74.012161      40.804        -1

-1:无法停车

1:可能停车

我想更新geojson文件。

data = pd.read_csv("data/_all.csv")

geojson_in = open('data/input.json', 'r')
tracts_geojson = json.load(geojson_in)
geojson_in.close()


# For each record in the geojson file, add location information
for i, r in enumerate(tracts_geojson['features']):
    for x in range(len(data.latitude.values)):
        if ((r['properties']['latitude']==data["latitude"][x]) and (r['properties']['longitude']== data["longitude"][x])):
            r['properties']['parking'] = str(data['Possible_parking'][x])

我使用的脚本问题是需要很长时间(现在+24小时)。 我不想直接将csv文件转换为json,因为input.json包含我在CSV文件中找不到的其他信息。

有没有更快速的方式来做到这一点?

1 个答案:

答案 0 :(得分:5)

您正在循环遍历JSON文件中每个功能的整个停车CSV行;这是一个N * M循环;一个600MB的CSV文件包含大约3000万个停车位条目(每行大约21个字节),并且您正在遍历所有3000万个每个功能

您想要将整个CSV文件加载到字典中:

import csv

with open(("data/_all.csv", 'rb') as incsv:
    reader = csv.reader(incsv)
    next(reader, None)  # skip presumed header
    parking = {(lat, long): park for lat, long, park in reader}

使用此代替循环遍历每个JSON条目的整个数据集:

for feat in tracts_geojson['features']:
    lat, long = feat['properties']['latitude'], feat['properties']['longitude']
    if (lat, long) in parking:
        feat['properties']['parking'] = parking[lat, long]

字典中的查找需要恒定的时间;而不是每个功能3000万个循环,现在每个功能使用一个直接查找。