我有一个感兴趣的2列的数据框。两者都充满了弦。我也有一个映射键值对字典,它也是字符串。我正在使用字典的键来仅对字典中的那些键按第一列过滤数据框。最终目标是查找数据帧的第一列使其与字典中的键匹配,然后确认列2的值与字典中的值匹配。感兴趣的键上的过滤后的数据框按预期工作,因此我剩下两列的数据框,它们只有字典中存在的列键。过滤后的数据帧的范围从几行到数千行,但字典的长度是静态的。最终输出应该是一个数据框,其内容显示已过滤数据框的行,其中第二列的值与字典的值不匹配。
pairs = {'red': 'apple', 'blue': 'blueberry', 'yellow':'banana'}
filtered_data = {'Color':['red', 'blue'], 'Fruit':['appl','blueberry']}
filtered_df = pd.DataFrame(filtered_data)
for row in filtered_df.iterrows():
for k,v in pairs.items():
#Here's where I'd like to check the value of column 1, find it in the dict then if the
#values dont match between col 2 in the df and the dict, append the mismatched row to a
#new df.
if row['Color'] == k:
new_df.append(row).where(row['Fruit'] != v)
我确定我需要第一个for循环中的行的索引,但是我不确定如何格式化其余嵌套循环结构。
理想情况下,在这种情况下,当我导出new_df数据帧时,它将有1行带有红色的Color列和appl的Fruit列,因为它与字典不匹配