Spandan Brahmbhatt
Spandan Brahmbhatt

Reputation: 4054

Check if tuple is in multiple columns in DataFrame

Consider the following dataframe:

df = pd.DataFrame({'col1': [1,2,3,4], 'col2' : ['one','two','three','four'], 'col3': ['abc','xyz','pqr','rst']})
df
    col1    col2    col3
0   1       one     abc
1   2       two     xyz
2   3       three   pqr
3   4       four    rst

How can we search if a multiple values across different columns ?

value_to_search = (1,'one')

In above case, we want to search for 1 in col1 and one in col2.

One way would be to

df[ (df['col1']==value_to_search[0]) & (df['col2']==value_to_search[1])]

Another way could be to iterate over rows but that would be inefficient way.

Is there any clean efficient way ?

Upvotes: 1

Views: 1489

Answers (2)

Spandan Brahmbhatt
Spandan Brahmbhatt

Reputation: 4054

Based on answer provided by @abc, one cleaner way could be,

cols_to_search = ['col1','col2']
df[df[cols_to_search].isin(value_to_search).all(axis=1)]

Upvotes: 1

wz 98
wz 98

Reputation: 93

First of all, I not sure the clean that you mean but you could try the .isin() method.

For example,

    options = (1,2,"one",3)

    df.loc[(df["col1"].isin(options)) & (df["col2"]=='one')]

    col1    col2    col3
  0  1      one     abc

Hope it can help you.

Upvotes: 0

Related Questions