use*_*649 0 python csv json pandas
我有包含地点的geojson文件。始终“停放:0”。
'type': 'Feature',
'properties': {
...// Other fields
'latitude': -74.0121613846062,
'longitude': 40.7043040747924,
'parking': 0 }
Run Code Online (Sandbox Code Playgroud)
我想从另一个csv文件数据集更新它。
-------------------------------------------
latitude + Longitude + Possible_parking
-------------------------------------------
-74.012161 40.804 -1
Run Code Online (Sandbox Code Playgroud)
-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])
Run Code Online (Sandbox Code Playgroud)
我正在使用的脚本的问题是它花费了很长时间(现在+24小时)。我不想直接将csv文件转换为json,因为input.json包含我在CSV文件中找不到的其他信息。
有什么pythonic方法可以更快地做到这一点?
您正在遍历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}
Run Code Online (Sandbox Code Playgroud)
使用此方法,而不是遍历每个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]
Run Code Online (Sandbox Code Playgroud)
字典中的查询需要固定的时间;现在,您无需为每个功能使用3000万个循环,而是可以对每个功能进行一次直接查找。