根据数据框中的查找删除数据框中的行



我使用两个数据帧。我想根据另一个数据帧中的匹配项删除第一个数据帧中的行。

在 df1 中,我有两列(称为 Type1 和 Type2(+ 一个标志。 我想删除标志 = True 的行,其中 Type1 和 Type2 匹配另一个 df2 中的组合。

import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randint(0,10,size=(100, 2)),columns = ["Type1","Type2"])
df1["Flag"] = np.random.randint(0,10,size=(100))>6
df1.head()
Type1  Type2   Flag
0      8      5  False
1      1      6  False
2      9      2  False
3      0      9   True
4      2      9  False
df2 = pd.DataFrame(np.random.randint(0,10,size=(100, 2)),columns = ["Type1","Type2"])
df2.head()
Type1  Type2
0      0      9
1      7      8
2      5      1
3      3      3
4      3      2

例如,这里 df1 中索引=3 的行应该删除为 Flag=True,而 (0,9( 存在于 df2 中。

对一个 df 使用merge,然后按boolean indexing过滤 - 只需要df1(left_only( 中的值和Flag中的False,因此删除带有bothTrue的行。

#on parameter omitted if only matched column are same in both df 
df3 = pd.merge(df1, df2, how='left', indicator=True)
#if multiple matched columns
#df3 = pd.merge(df1, df2, how='left', indicator=True, on = ['Type1','Type2'])
print (df3)
Type1  Type2   Flag     _merge
0      8      5  False  left_only
1      1      6  False  left_only
2      9      2  False  left_only
3      0      9   True       both
4      2      9  False  left_only
df3 = df3.loc[(df3['_merge'] == 'left_only') & (~df3['Flag']), ['Type1','Type2']]
print (df3)
Type1  Type2
0      8      5
1      1      6
2      9      2
4      2      9

也可以创建掩码,然后仅过滤df1(如果多列(:

m = (df3['_merge'] == 'left_only') & (~df3['Flag'])
df1 = df1[m]
print (df1)
Type1  Type2   Flag
0      8      5  False
1      1      6  False
2      9      2  False
4      2      9  False

最新更新