在try/except语句中使用continue

2024-09-30 00:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个Pandas数据帧,并遍历行以查找相关数据,在本例中是颜色。在大多数情况下,“Color”列的单元格将被填充,在这种情况下,我不需要在该行的其他单元格中搜索颜色,可以继续到下一行。但是,如果不存在“Color”列,Pandas将引发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的comment,但是,如果我正确理解yield,这将终止函数,而不是循环的这个迭代。我想在Python中做的是可能的吗

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


Tags: to数据selfdataframepandasfor颜色情况

热门问题