#python #python-2.7 #api #arcpy
#python #python-2.7 #API #arcpy
Вопрос:
Я пытаюсь считывать данные из API CDC 500 cities для интеграции в более масштабный пространственный анализ. Я пишу скрипт на python с использованием arcpy и пары других библиотек.
Три больших шага: 1. считывание и преобразование данных в правильный формат 2. объединение данных в шейп-файл переписного тракта 3. табулирование пересечений для пересчета до уровня ZCTA
Однако есть какая-то проблема с форматированием, и он не может выполнить инструмент объединения таблиц.
Я новичок в python, но я пробовал читать данные с помощью response.read(), а также использовать библиотеку json с помощью json.dumps() и json.loads(), но, похоже, ни один из них не делает то, что я хочу.
Вот что у меня есть прямо сейчас:
Url="https://chronicdata.cdc.gov/resource/47z2-4wuh.csv"
Query='?PlaceName='
SelectedCity=raw_input('Enter the city of interest')
#define function to check for valid input
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
#create if then statement to print an error if the input is not a string
#will need to change the elif statement to identify special characters
#We could just pull in all the data, convert to point shapefile and then clipped to area of interest....
if hasNumbers(SelectedCity) == False:
Request=Url Query SelectedCity.title()
print('You're API request URL:' Request)
else:
print("That input does not match any possible city name")
#open the request defined above
response=requests.get(Request)
#read file to json
Json=json.dumps(response.content)
saveData = open("jsonOutput.json", "wt")
saveData.write(Json)
saveData.close()
censusTract=tkFileDialog.askopenfilename(parent= tkObj,title='Select City Census Tract File')
myMessage = 'Census Tract={0}'.format(censusTract)
print(myMessage)
#fieldmapping
fieldmappings = arcpy.FieldMappings()
fieldmappings.addTable(censusTract)
fieldmappings.addTable(saveData)
zipFieldIndex = fieldmappings.findFieldMapIndex('GEOID')
fieldmap = fieldmappings.getFieldMap(zipFieldIndex)
#Get the output field's properties as a field object
field = fieldmap.outputField
#Rename the field and pass the updated field object back into the field map
field.name = 'GEOID'
field.aliasName = 'GEOID'
fieldmap.outputField = field
#create input names
inlayer=censusTract
infield="GEOID"
jointable=response
joinfield="TractFIPS"
CDCshape = arcpy.AddJoin_management(inlayer,infield,jointable,joinfield)
Результатом этого должен быть шейп-файл с объединенными данными CDC 500 cities ИЛИ фрейм данных, которым можно манипулировать с помощью pandas или других библиотек, а затем присоединять к шейп-файлу.
Комментарии:
1. в запросах есть метод .json. r = requests.get(url).json()
Ответ №1:
Я бы предложил использовать Pandas для чтения файла csv в фрейм данных. А затем вы можете фильтровать, очищать и объединять данные. Установите pandas, если он еще не установлен
pip install pandas
import pandas as pd
import requests
Url="https://chronicdata.cdc.gov/resource/47z2-4wuh.csv"
file_ouput=pd.read_csv(Url)
print(file_output)
Чтобы преобразовать фрейм данных в json
file_json = file_output.to_json(orient='records')