如果同一行存在于另一个数据框中但以两个df中的所有列结尾时,如何从Pandas数据框中删除行 [英] How to remove rows from Pandas dataframe if the same row exists in another dataframe but end up with all columns from both df

查看:112
本文介绍了如果同一行存在于另一个数据框中但以两个df中的所有列结尾时,如何从Pandas数据框中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的Pandas数据框,它们共有一列.我在堆栈溢出中也看到了类似的问题,但似乎没有一个问题以两个数据帧中的列结尾,因此在标记为重复之前请先阅读以下内容.

I have two different Pandas data-frames that have one column in common. I have seen similar questions on Stack overflow but none that seem to end up with the columns from both dataframes so please read below before marking as duplicate.

示例:

数据帧1

ID  col1 col2  ...
1    9    5
2    8    4
3    7    3 
4    6    2

数据框2

ID  col3  col4  ...
3    11     15
4    12     16
7    13     17

我要实现的是一个具有两个数据帧中的列但在dataframe2中没有找到ID的数据帧.即:

What I want to achieve is a dataframe with columns from both dataframes but without the ID's found in dataframe2. i.e:

所需结果:

ID  col1 col2  col3  col4
1    9    5     -     -
2    8    4     -     -

谢谢!

推荐答案

您可以使用左联接在第一个数据帧而不是第二个数据帧中仅获取id,同时还保留所有第二个数据框架列.

You can use a left join to get only the id's in the first data frame and not the second data frame while also keeping all the second data frames columns.

import pandas as pd

df1 = pd.DataFrame(
    data={"id": [1, 2, 3, 4], "col1": [9, 8, 7, 6], "col2": [5, 4, 3, 2]},
    columns=["id", "col1", "col2"],
)
df2 = pd.DataFrame(
    data={"id": [3, 4, 7], "col3": [11, 12, 13], "col4": [15, 16, 17]},
    columns=["id", "col3", "col4"],
)

df_1_2 = df1.merge(df2, on="id", how="left", indicator=True)

df_1_not_2 = df_1_2[df_1_2["_merge"] == "left_only"].drop(columns=["_merge"])

返回

   id  col1  col2  col3  col4
0   1     9     5   NaN   NaN
1   2     8     4   NaN   NaN

这篇关于如果同一行存在于另一个数据框中但以两个df中的所有列结尾时,如何从Pandas数据框中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆