我一直在尝试使用嵌套循环遍历pandas DataFrame的行,外部循环,并且每行检查规则的条件,元组列表:[(Attribute,Value), (Att,Val)],匹配DataFrame行中的Att,Val对,内部循环。如果规则中的所有条件都满足,我希望记录行的索引,如果一个或多个条件失败,我希望突破内循环而不记录行索引并继续到下一行。
我已经尝试将break语句放在内部循环,外部循环等中,但我无法按照自己的意愿使用它。非常感谢任何帮助我的尝试。
def rule_coverage(self, rule):
for index,row in self.data.iterrows():
for selector in rule:
if row[selector[0]] != selector[1]:
break
coverage.append(index)
return self.data.iloc[coverage]
答案 0 :(得分:1)
我做这样的事情:
让img = cv2.imread('imgs/bulls.jpg')
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
court_color = np.uint8([[[160,221,248]]])
hsv_court_color = cv2.cvtColor(court_color, cv2.COLOR_BGR2HSV)
hue = hsv_court_color[0][0][0]
# define range of blue color in HSV
lower_color = np.array([hue - 10,10,10])
upper_color = np.array([hue + 10,255,255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv_img, lower_color, upper_color)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(img,img, mask= mask)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)), plt.title('Original Image'), plt.show()
plt.imshow(mask, cmap='Greys'), plt.title('Mask'), plt.savefig('imgs/mask.jpg'), plt.show()
# Erosion
kernel = np.ones((2,2),np.uint8)
erosions2 = cv2.erode(mask,kernel,iterations = 5)
# Dilation
dilation = cv2.dilate(mask,kernel,iterations = 3)
# Opening
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
# Closing
closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
成为代表s
pandas.Series
rule
重新分配数据框以与s = pd.Series(dict(rule))
s
然后比较并返回整行的真实位置
d, s = self.data.align(s, 'inner', 1)
答案 1 :(得分:0)
同志们,我设法通过遵循许多其他帖子的建议来解决问题,这些帖子建议将内部循环重构为将所需结果返回到外部循环的函数。感谢您给出的所有建议。解决方案如下,上部函数是前内部循环,而下部函数是现在简化的外部循环。
def check_rule_datapoint(self, datapoint, complex):
"""
Function to check if a given data point satisfies
the conditions of a given complex. Data point
should be a pandas Series. Complex should be a
tuple or a list of tuples where each tuple is of
the form ('Attribute', 'Value').
"""
if type(complex) == tuple:
if datapoint[complex[0]] == complex[1]:
return True
else:
return False
if type(complex) == list:
result = True
for selector in complex:
if datapoint[selector[0]] != selector[1]:
result = False
return result
def complex_coverage(self, complex):
""" Returns set of instances of the data
which complex(rule) covers.
"""
#import ipdb;ipdb.set_trace(context=8)
coverage = []
#iterate over dataframe rows
for index,row in self.data.iterrows():
if self.check_rule_datapoint(row, complex):
coverage.append(index)
return self.data.iloc[coverage]