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 了。预先感谢您的任何回复。
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'])
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')
应该看起来像这样(虽然未经测试,所以你需要适应它!):
strings = (~imageData.background_color.apply(np.isreal))
blue = (imageData.background_color.str.upper()=="BLUE")
blueshapes = imageData[strings & blue].index
background_color
列即可。无论如何,任何非环条目都是无效的,但它们并不孤单,因此在连接所有颜色的索引后,我会在稍后将它们作为剩余索引找到。每个列表将被提取如下:
imageData['background_color']=map(lambda x: x.upper(), imageData['background_color'].astype(str))
blueShapes=imageData[imageData['background_color']=='BLUE'].index
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]