python - 在 try/except 语句中使用 continue
问题描述
我正在使用 Pandas 数据框并遍历行以查找相关数据,在本例中为颜色。大多数情况下,“颜色”列的单元格将被填充,在这种情况下,我不需要在该行中的其他单元格中搜索颜色,可以继续下一行。但是,如果不存在“颜色”列,Pandas 将引发 a KeyError
,我将需要创建该列并向其添加值。这是我的代码片段:
class Reader(object):
def __init__(self, dataframe):
"""Grabs column headers, converts dataframe from unicode string objects to
Python string objects, sets dataValues class variable equal to a numpy array of the sheet"""
self.headers = dataframe.columns.values
self.dataFrame = dataframe.applymap(str)
self.dataValues = self.dataFrame[:].values
class Extractor(object):
"""Extracts relevant spec information from a sku (row)"""
def getColor(self, colorRef):
"""Looks in Model Name and Description for color information.
Uses pre-existing color database (colorRef).
Returns dataFrame column 'Color' """
index = 0
newColorArray = [] #this will not be returned, its sole purpose is to keep track of colors
for sku in myData.dataValues:
try:
if myData.dataFrame.iloc[index, myData.dataFrame.columns.get_loc('Color') != ('' or ' '):
continue #color exists, move to next row
except KeyError:
newColorArray = ['']*myData.dataFrame.shape[0]
#Remaining code searches for colors
当我尝试执行该代码块时,我得到一个SyntaxError
. 我已经阅读了 e-satis 的评论,但是如果我理解yield
正确,这将终止函数而不是循环的迭代。我正在尝试做的事情甚至可能在 Python 中实现吗?
我没有很多使用对象和类的练习,所以如果你也想在那里给我反馈,请做。
解决方案
推荐阅读
- python - Python-无法通过 TCP/IP 连接转发 HID 数据
- c# - 使用 MEF 对象作为 XmlIncludes 的 XML 反序列化
- python - 如何从我的语料库 TF-IDF 中删除元组?
- javascript - 对数组的第二个参数求和
- python - 使用 pytecplot 脚本在 tecplot 中执行方程
- apache - .htaccess 将 index.html 重定向到 index2.html
- akka - 如何更改使用哪个prometheus抓取metrcs的端口号
- html - 如何强制浏览器自动从服务器检索新页面而不是返回缓存页面
- python - 我在尝试使用 pip 时遇到错误,我无法理解错误消息。有人可以告诉我该怎么做吗?
- ios - Ionic 3 Cordova - Apple 登录有时会在首次登录尝试时抛出 ASAuthorizationErrorUnknown 导致应用程序被拒绝