使这个数据清理循环更容易

2024-04-20 10:47:46 发布

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

我正在用python2.7清理一些人类分类数据,主要是使用pandas,但是使用numpy.isreal()检查float,因为有些人显然在'background_color'之类的字段中输入了float。不管怎么说,我正在发布一个例子,说明我当前设置的一种颜色的外观是什么样的,它可以工作,只是看起来不太像Python,在循环的末尾,blues是所有索引的列表,其中background_color不区分大小写'BLUE'

blueShapes=[]
for i in range(imageData.shape[0]):
    if not (np.isreal(imageData.loc[i,'background_color'])):
        if imageData.loc[i,'background_color'].upper()=='BLUE':
            blueShapes.append(i)

似乎我可以使用map函数来让这个更具python风格,更漂亮。就像我说的,它按预期运行,但似乎太…C或Java了,无法用Python编写。提前感谢您的回复。你知道吗

-编辑:我删除了计数,因为它是一个旧循环的遗迹


Tags: 数据numpypandasif分类blue人类float
3条回答

可以定义一个lambda函数,该函数返回具有特定字符串值的行索引

getRowIndexWithStringColor = lambda df, color: [i for i in range(df.shape[0]) if (not np.isreal(df.loc[i,'background_color'])) and df.loc[i,'background_color'].upper()==color)]
rowIndexWithBlue = getRowIndexWithStringColor(imageData, 'BLUE')

你可以创建一个大写的bew列

imageData['background_color_2'] = map(lambda x: x.upper(), imageData['background_color'].astype(str))

subset = imageData[imageData['background_color_2']=='BLUE']

为了伯爵

len(subset['background_color'])

作为一个一般规则,如果你是循环在熊猫你做错了。你知道吗

应该看起来像这样(虽然没有经过测试,所以你需要调整它!)地址:

strings = (~imageData.background_color.apply(np.isreal))
blue = (imageData.background_color.str.upper()=="BLUE")
blueshapes = imageData[strings & blue].index           

相关问题 更多 >