根据另一个df的列删除df行

时间:2019-12-12 15:56:30

标签: python pandas dataframe

具有两个df值


df 1 


number    1          2     3

12354    mark        24  london
12356    jacob       25  denver
12357    luther      26  berlin
12358    john        27  tokyo
12359    marshall    28  cairo
12350    ted         29  delhi

另一个df 2

number       

12354   

12357    

12359    


删除df1中具有与df2相同列值的所有行

预期产量


0          1          2     3

12356    jacob       25  denver
12358    john        27  tokyo
12350    ted         29  delhi

1 个答案:

答案 0 :(得分:1)

这里有个例子:

import pandas as pd
from io import StringIO

df1 = """
number,1,2,3
12354,mark,24,london
12356,jacob,25,denver
12357,luther,26,berlin
12358,john,27,tokyo
12359,marshall,28,cairo
12350,ted,29,delhi
"""
df2 = """
number
12354
12357
12359
"""

df_df2 = pd.read_csv(StringIO(df2), sep=',')
df_df1 = pd.read_csv(StringIO(df1), sep=',')

df=pd.merge(df_df1,df_df2, indicator=True, how='outer').query('_merge=="left_only"')

df.drop(['_merge'], axis=1, inplace=True)
df.rename(columns={'number': '0'}, inplace=True)
print(df)