让这个数据清理循环更加Python化

问题描述 投票:0回答:5
我正在使用Python 2.7清理一些人类分类数据,主要使用pandas,但使用

numpy.isreal()

来检查浮动,因为有些人显然在像
'background_color'
这样的字段中输入了浮动。

无论如何,我发布了一个示例,展示了我当前设置下的一种颜色的样子,这是可行的,它只是看起来不太像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函数来让这个更Pythonic和更漂亮。就像我说的,它的功能符合预期,但用 Python 编写似乎太……C 或 Java 了。预先感谢您的任何回复。

python python-2.7 pandas
5个回答
0
投票
你可以创建一个大写的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'])
    

0
投票
您可以定义一个 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')
    

0
投票
作为一般规则,如果你在 pandas 中循环,那么你就做错了。

应该看起来像这样(虽然未经测试,所以你需要适应它!):

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

0
投票
谢谢大家!我对 Steven G 的答案进行了轻微的修改,我将所有这些都备份在主 .csv 中,因此我没有担心只需用其等效的字符串覆盖

background_color

 列即可。无论如何,任何非环条目都是无效的,但它们并不孤单,因此在连接所有颜色的索引后,我会在稍后将它们作为剩余索引找到。每个列表将被提取如下:

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

0
投票
我会把它变成一个函数并返回一个数组。

Google:Python之禅

为您提供快速参考

python list/dict/set over map/filter

更好的可读性和更清晰的代码。

def colorShapes(color): return [i for i in range(imageData.shape[0]) if not(np.isreal(imageData.loc[i, 'background_color'].upper() == color and imageData.loc[i, 'background_color'].upper() == color]
    
© www.soinside.com 2019 - 2024. All rights reserved.