首页 > 解决方案 > 在 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 中实现吗?

我没有很多使用对象和类的练习,所以如果你也想在那里给我反馈,请做。

标签: pythonpandastry-catchcontinue

解决方案


推荐阅读