[英]Selecting rows from DF1 where column values match values from a column from DF2
[英]How to remove rows in Pandas DF where value from Column A is in Column B and Column C Match
我有一个包含一些用户/文件信息的数据框。 例如:
| Scanned_Item | Matched_Item | Owner_Name |
| item 1 | item 2 | owner 1 |
| item 1 | item 3 | owner 1 |
| item 3 | item 1 | owner 2 |
我有几千件物品。 Matched_Items 可能不是 Scanned_Item。 我想要做的是删除 Scanned_Item 和 Matched_Item 都属于同一个人的所有行。
我想要的 output 是一个 DF,没有所有者与他自己的项目匹配,从而消除了自我重复。 我只想查看所有者匹配其他人文件的行。
相当于说如果 Matched_Item 存在于 Scanned_Item 中,并且 Matched_Item 的 Owner_Name = Scanned_Item 的 Owner_Name。
(匹配是基于与此问题无关的其他预定标准形成的。
编辑:这是我现在写的,但它需要永远,不确定这是否表明它不起作用哈。
for index, row in df.iterrows():
for index2, row2 in df.iterrows():
if row['Scanned_Workbook'] == row2['Matched_Workbook'] and row['Full Name'] == row2['Full Name']:
df.drop(index,errors='ignore')
df.drop(index2,errors='ignore')
Edit2:作为补充细节,因为似乎存在一些清晰度问题。 所有已扫描和匹配的项目都来自相同的原始数据源。 我通过迭代我的原始数据集并使用 Python 集合理解来查找三个条件匹配的文件,找到了匹配项。
所以项目 1 被扫描并与项目 2 匹配 3 个条件,这就是第一行的来源。 但由于我是如何理解的,我只有 Scanned_Items 的所有者名称,而不是 Matched_Items。
我正在尝试删除 Scanned_Item 和 Matched_Item 都属于同一所有者的所有行。
这有助于清晰吗?
Edit3:这是一个将被删除的行的示例。
| Scanned_Item | Matched_Item | Owner_Name |
| item 1 | item 2 | owner 1 |
| item 2 | item 1 | owner 1 |
因为第 1 项和第 2 项都在某个时间点进行了扫描,所以它们相互匹配。 但它们也有相同的所有者。 我想删除任何看起来像这样的行。
所有者名称与扫描的项目相关联。 所以我能找到匹配项目所有者的唯一方法是它是否出现在扫描列中。
如果我理解得很好,您需要删除重复项。
如果要删除所有这些行,为什么不简单地编写以下内容:
new_df = df.drop_duplicates(keep=False)
如果您想保留至少一个重复项,只需更改参数的值:
new_df = df.drop_duplicates(keep='first')
我会将任务分为两个步骤
item
都交给它的owner
第 1 步: map owners
到items
。 我们可以用字典来做到这一点。 假设Matched_Item
是与Owner_Name
关联的项目,
df_owner_items = df[["owner_name", "matched_item"]]. \
drop_duplicates(). \ # We select only non duplicated records
set_index("matched_item") \ # We set index to use the `from_dict` method later in the most useful way
owner_items_dict = df_owner_items.to_dict(orient="index") # Our dataframe is transformed in a dictionary having format {"item1": {"owner_name": "owner 1"}}
第 2 步:创建 boolean 掩码和过滤器
filter = (df["owner_name"] != owner_items_dict["matched_item"]["owner_name"])
filtered_df = df.loc[filter]
希望这可以帮助。
走了一条不同的路线来解决这个问题。 我刚刚加入了原始数据集并找到了matched_items 的所有者,因此我可以在单独的列中同时扫描和匹配所有者。 然后,使用 df.query 删除两个所有者值匹配的所有行。
这解决了我的问题,感谢所有回答/评论的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.