1

I have two pandas df colums with populated with some names, first df has more name enteries, and second has less, e.g.

id names
1 John Doe
2 Jane Doe
id names
1 John Doe

I need to create a column with True/False in the first df, if names are matching, e.g.

id names match
1 John Doe True
2 Jane Doe False

so far I have tried this two methodes:

df['match'] = (df1.names is df2.names) # always return False
df['match'] = df1.names.isin(df2.names) # compare only first names, eg. John, but doesn't the second

Additionally I have tried to lowercase and remove strings, but still not getting the result

What am I doing wrong?

6
  • 2
    df1.names.isin(df2.names.tolist()) Commented Jul 15, 2021 at 11:50
  • there is no "first name" and "second name" here........ there is only "names".......... so do you want to compare "names" ? Commented Jul 15, 2021 at 11:50
  • @ThePyGuy thanks, but this also only compares the first name and not whole str. Commented Jul 15, 2021 at 11:52
  • 1
    @AnuragDabas ids are not matching, can't be used Commented Jul 15, 2021 at 11:53
  • @Joshua yes, I want to compare the whole str ('names'), but methode I used ither compares only the first part of the string and ignores the second or gives all false.... Commented Jul 15, 2021 at 11:54

1 Answer 1

1

I tested the solution I provided in comment and it works, here is the sample run:

>>> df1.names.isin(df2.names) #Additional call .tolist() isn't even required.
0     True
1    False
Name: names, dtype: bool

If above doesn't work, try this:

>>> df1['names'].apply(lambda x: x in df2.names.tolist())
0     True
1    False
Name: names, dtype: bool
Sign up to request clarification or add additional context in comments.

3 Comments

Which pandas version and python version are you using? Also update the question running the provided solution, and let us see if it's actually not working.
pandas version 1.3.0, python version 3.9.5
the second variant works perfect - many many many many thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.