python中的数据帧:基于df2中的行从df1中删除行
我有两个数据帧:python中的数据帧:基于df2中的行从df1中删除行,python,python-3.x,pandas,dataframe,merge,Python,Python 3.x,Pandas,Dataframe,Merge,我有两个数据帧: df1: contains all information rowname a b c d R1 1 2 0 1 R2 2 2 0 1 R3 0 2 0 0 R4 1 2 0 1 df2: contains a subset of the rows and columns: rowname a b c R1 1 2 0 R2 2 2 0 R4 1 2
df1: contains all information
rowname a b c d
R1 1 2 0 1
R2 2 2 0 1
R3 0 2 0 0
R4 1 2 0 1
df2: contains a subset of the rows and columns:
rowname a b c
R1 1 2 0
R2 2 2 0
R4 1 2 0
我想过滤掉所有不在df1
中的df2
行。因此,对于本例,我希望在保留所有列的同时去掉df1
中的R3
我认为使用
df1.merge(df2,…)
可以实现这一点,但我尝试了各种参数,但都没有成功。我正在使用python3。Simpy使用isin()过滤数据帧。
这是一种方式,只在列
['a','b','c']
上匹配
df = pd.concat([df1, df2])
df = df.loc[df.duplicated(['a', 'b', 'c'], keep=False)]\
.dropna(subset=['d'], axis=0)
df['d'] = df['d'].astype(int)
结果:
a b c d rowname
0 1 2 0 1 R1
1 2 2 0 1 R2
3 1 2 0 1 R4
a b c d rowname
0 1 2 0 1 R1
1 2 2 0 1 R2
3 1 2 0 1 R4