Python Pandas remove rows containing values from a list

时间:2017-03-02 23:40:11

标签: python pandas

I am comparing two large CSVs with Pandas both containing contact information. I want to remove any rows from one CSV that contain any of the email addresses from the other CSV.

So if I had

DF1

name phone email
1    1     hi@hi.com
2    2     bye@bye.com
3    3     yes@yes.com

DF2

name phone email
x    y     bye@bye.com
a    b     yes@yes.com

I would be left with

DF3

name phone email
1    1     hi@hi.com

I don't care about any columns except the email addresses. This seems like it would be easy, but I'm really struggling with this one.

Here is what I have, but I don't think this is even close:

def remove_warm_list_duplicates(dataframe):
    '''Remove rows that have emails from the warmlist'''
    warm_list = pd.read_csv(r'warmlist/' + 'warmlist.csv'
                            , encoding="ISO-8859-1"
                            , error_bad_lines=False)
    warm_list_emails = warm_list['Email Address'].tolist()
    dataframe = dataframe[dataframe['Email Address'].isin(warm_list_emails) == False]

3 个答案:

答案 0 :(得分:3)

您可以使用pandas isin()

Set BoxValue = .Find(What:=StrtComboBox.Value, LookAt:=xlWhole) 

结果df

df3 = df1[~df1['email'].isin(df2['email'])]

答案 1 :(得分:1)

try this:

In [143]: pd.merge(df1, df2[['email']], on='email', how='left', indicator=True) \
            .query("_merge == 'left_only'") \
            .drop('_merge',1)
Out[143]:
   name  phone      email
0     1      1  hi@hi.com

答案 2 :(得分:1)

You could simplify a bit with unique() and sets:

warm_list = pd.read_csv(r'warmlist/' + 'warmlist.csv',
                        encoding="ISO-8859-1",
                        error_bad_lines=False)

warm_list_emails = set(warm_list['Email Address'].unique())
df = df.loc[df['Email Address'].isin(warm_list_emails), :]