﻿ python – pandas – 按行元素按另一个数据帧过滤数据帧 - 代码日志

#### python – pandas – 按行元素按另一个数据帧过滤数据帧

``````   c  k  l
0  A  1  a
1  A  2  b
2  B  2  a
3  C  2  a
4  C  2  d
``````

``````   c  l
0  A  b
1  C  a
``````

``````d = df[~(df['l'].isin(dfc['l']) & df['c'].isin(dfc['c']))]
``````

``````   c  k  l
2  B  2  a
4  C  2  d
``````

``````   c  k  l
0  A  1  a
2  B  2  a
4  C  2  d
``````

``````df1 = pd.DataFrame({'c': ['A', 'A', 'B', 'C', 'C'],
'k': [1, 2, 2, 2, 2],
'l': ['a', 'b', 'a', 'a', 'd']})
df2 = pd.DataFrame({'c': ['A', 'C'],
'l': ['b', 'a']})
keys = list(df2.columns.values)
i1 = df1.set_index(keys).index
i2 = df2.set_index(keys).index
df1[~i1.isin(i2)]
``````

(以上答案是编辑。以下是我最初的答案)

``````df1 = pd.DataFrame({'c': ['A', 'A', 'B', 'C', 'C'],
'k': [1, 2, 2, 2, 2],
'l': ['a', 'b', 'a', 'a', 'd']})
df2 = pd.DataFrame({'c': ['A', 'C'],
'l': ['b', 'a']})

# create a column marking df2 values
df2['marker'] = 1

# join the two, keeping all of df1's indices
joined = pd.merge(df1, df2, on=['c', 'l'], how='left')
joined
``````

``````# extract desired columns where marker is NaN
joined[pd.isnull(joined['marker'])][df1.columns]
``````