Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Check if values in a column exist elsewhere in a dataframe row

Suppose I have a dataframe as below:

df = pd.DataFrame({'a':[1,2,3,4],'b':[2,3,4,5],'c':[3,4,5,6],'d':[5,3,2,4]})

I want to check if elements in column d exist elsewhere in its corresponding row. So the outcome I want is

[False, True, False, True]

Towards that end, I used

df.apply(lambda x: x['d'] in x[['a','b','c']], axis=1)

but this is somehow giving me [False, False, False, False].

over 4 years ago · Santiago Trujillo
5 answers
Answer question

0

Taking advantage of numpy broadcasting, you can do it easily:

(df[['d']].to_numpy() == df.to_numpy())[:, :-1].any(axis=1)

Output:

array([False,  True, False,  True])

Using numpy is about as fast as you can get.

over 4 years ago · Santiago Trujillo Report

0

Try:

out = (df[['a','b','c']].T==df['d']).any()

Output:

0    False
1     True
2    False
3     True
dtype: bool
over 4 years ago · Santiago Trujillo Report

0

Use eq to broadcast equality comparison across the columns. Then check if there are any matches in the row:

df.drop(columns='d').eq(df['d'], axis=0).any(axis=1).array
<PandasArray>
[False, True, False, True]
Length: 4, dtype: bool

Speedwise, a numpy option is best.

over 4 years ago · Santiago Trujillo Report

0

Try with

df.eq(df.pop('d'),axis=0).any(1)#.values
0    False
1     True
2    False
3     True
dtype: bool
over 4 years ago · Santiago Trujillo Report

0

Need to add 'values':

df.apply(lambda x: x['d'] in x[['a','b','c']].values, axis=1)
Out[11]: 
0    False
1     True
2    False
3     True
dtype: bool

What you've typed is checking whether x['d'] is in the set of keys of x[['a','b','c']] not values. Dictionaries work in similar ways:

1 in {'a': 1, 'b': 2}
Out[30]: False
1 in {'a': 1, 'b': 2}.values()
Out[31]: True
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!