【发布时间】:2020-09-10 19:40:40
【问题描述】:
我有一个包含 2 列感兴趣的数据框。两者都充满了字符串。我还有一个映射键值对字典,它们也是字符串。我正在使用字典的键通过第一列过滤数据框,仅针对字典中的那些键。
最终目标是查找数据框的第一列,将其与字典中的键匹配,然后确认第 2 列的值与字典中的值匹配。
感兴趣的键上的过滤数据框按预期工作,所以我留下了一个两列的数据框,其中只有字典中存在的列键。过滤后的数据帧可以是几行到几千行不等,但字典的长度是静态的。
最终输出应该是一个数据框,其内容显示过滤后的数据框的行,其中第二列的值与字典的值不匹配。
pairs = {'red': 'apple', 'blue': 'blueberry', 'yellow':'banana'}
filtered_data = {'Color':['red', 'blue'], 'Fruit':['appl','blueberry']}
filtered_df = pd.DataFrame(filtered_data)
#so the filtered_df would resemble
Color Fruit
red appl
blue blueberry
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 行的颜色列为红色,水果列为 appl,因为它与类似于下面的字典不匹配。
Color Fruit
red appl
【问题讨论】:
-
你能提供预期的数据框吗?
-
我不太确定,但你可以试试
df[df['Color'].map(pairs) != df['Fruit']]看看是否适合你?如果没有 - 你能解释一下它应该给你什么吗? -
刚刚更新了我希望得到的 df 的样子
-
@JonClements 解决方案工作正常
标签: pandas python-2.7 dictionary