我有以下数据框。
import pandas as pd
d={'P':['A','B','C'],
'Q':[5,6,7]
}
df=pd.DataFrame(data=d)
print(df)
d={'P':['A','C','D'],
'Q':[5,7,8]
}
df1=pd.DataFrame(data=d)
print(df1)
d={'P':['B','E','F'],
'Q':[5,7,8]
}
df3=pd.DataFrame(data=d)
print(df3)
检查一个数据框列不存在的代码是这样的:
df.loc[~df['P'].isin(df1['P'])]
如何在多列中进行相同的检查?
如何找到df3中的P列而不是df和df1中的P列?
预期输出:
P Q
0 E 7
1 F 8
答案 0 :(得分:4)
您可以将2个条件与&
链接以按位AND
:
cond1 = ~df3['P'].isin(df1['P'])
cond2 = ~df3['P'].isin(df['P'])
df = df3.loc[cond1 & cond2]
print (df)
P Q
1 E 7
2 F 8
或者通过concatenate
连接列值或通过+
连接列表:
df = df3.loc[~df3['P'].isin(np.concatenate([df1['P'],df['P']]))]
#another solution
#df = df3.loc[~df3['P'].isin(df1['P'].tolist() + df['P'].tolist())]
答案 1 :(得分:1)
那怎么办,但是jezrael已经给了专家答案:)
您可以简单地定义条件,然后在逻辑上进行组合,例如:
con1 = df3['P'].isin(df['P'])
con2 = df3['P'].isin(df1['P'])
df = df3[~ (con1 | con2)]
>>> df
P Q
1 E 7
2 F 8