映射多个Foursquare结果且API结果为空时,如何在数据帧为空时抑制Python中的KeyError

如何解决映射多个Foursquare结果且API结果为空时,如何在数据帧为空时抑制Python中的KeyError

我正在检索 Foursquare 场地数据并将其绘制在 folium 地图上。我正在同一张地图上绘制多个 API 调用结果。

当 API 由于搜索中没有查询的场所而返回空的 JSON 结果时,它会抛出 KeyError,因为代码引用了数据帧中不存在的列,因为 API 结果为空。

我想继续显示带有其他结果的地图,并让代码忽略或抑制 API 结果为空的实例。

我尝试过 try/except/if 来测试数据框是否为空白,但无法弄清楚如何“忽略空白并跳到下一个 API 结果”。

任何建议将不胜感激。

## Foursquare Query 11 - name origin location
address = 'Convent Station,NJ' ## Try "Madison,NJ" for working location example
geolocator = Nominatim(user_agent="foursquare_agent")
location = geolocator.geocode(address)
latitude = location.latitude
longitude = location.longitude

## name search parameters
search_query = 'Pharmacy'
radius = 1200

## define corresponding URL
url = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&ll={},{}&oauth_token={}&v={}&query={}&radius={}&limit={}'.format(CLIENT_ID,CLIENT_SECRET,latitude,longitude,ACCESS_TOKEN,VERSION,search_query,radius,LIMIT)
results = requests.get(url).json()

## Convert to pandas dataframe
# assign relevant part of JSON to venues
venues = results['response']['venues']
venues
# tranform venues into a dataframe
dataframe = json_normalize(venues)

## Filter results to only areas of interest
# keep only columns that include venue name,and anything that is associated with location
filtered_columns = ['name','categories'] + [col for col in dataframe.columns if col.startswith('location.')] + ['id']
dataframe_filtered = dataframe.loc[:,filtered_columns]

# function that extracts the category of the venue
def get_category_type(row):
  try:
        categories_list = row['categories']
  except:
        categories_list = row['venue.categories']
        
  if len(categories_list) == 0:
        return None
  else:
        return categories_list[0]['name']

# filter the category for each row
dataframe_filtered['categories'] = dataframe_filtered.apply(get_category_type,axis=1)

# clean column names by keeping only last term
dataframe_filtered.columns = [column.split('.')[-1] for column in dataframe_filtered.columns]

## Visualize the data
dataframe_filtered.name

    # add the query 11 pharmacies as blue circle markers
for name,lat,lng,label in zip(dataframe_filtered.name,dataframe_filtered.lat,dataframe_filtered.lng,dataframe_filtered.name+" - "+dataframe_filtered.city+","+dataframe_filtered.state):
  folium.CircleMarker(
        [lat,lng],radius=5,color='blue',popup= label,fill = True,fill_color='blue',fill_opacity=0.6
    ).add_to(venues_map)

    ###
    ###
    ###

 
# display map
print('Location loaded,search parameters defined,url generated,results saved & converted to dataframe,map generated!')
venues_map

API结果为空时报错(搜索半径内没有Foursquare结果)

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:21: FutureWarning:

pandas.io.json.json_normalize is deprecated,use pandas.json_normalize instead

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-57-2deac5f680d4> in <module>()
     24 # keep only columns that include venue name,and anything that is associated with location
     25 filtered_columns = ['name','categories'] + [col for col in dataframe.columns if col.startswith('location.')] + ['id']
---> 26 dataframe_filtered = dataframe.loc[:,filtered_columns]
     27 
     28 # function that extracts the category of the venue

6 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self,key,indexer,axis,raise_missing)
   1296             if missing == len(indexer):
   1297                 axis_name = self.obj._get_axis_name(axis)
-> 1298                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   1299 
   1300             # We (temporarily) allow for some missing keys with .loc,except in

KeyError: "None of [Index(['name','categories','id'],dtype='object')] are in the [columns]"

解决方法

如果您只想让 KeyError 静音,请尝试以下操作:

try:
   ...
except KeyError as ke:
   pass

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?