Jonas Palačionis
Jonas Palačionis

Reputation: 4842

Checking if value exists in any of two columns with pandas

I am new to pandas.

I am building a dataframe with True and False values using .isin() method.

There are 7 columns in my dataframe and I check if value exists in each column compared to the column on the left. It works out fine using .isin() method.

The problem is that I need to check if value exists in column A or column B to place a True or False value on my new dataframe column C.

For example:

df_1

A     B     C     D
1     a     1     a
a     b     a     
c     c     c     c
d     1           d

And I am checking if value 1 from column A exists in whole column B, C, D and where it does I pass a True statement to that row in that column where match was found.

And I am building new dataframe using masks:

mask_gclid_cloudflare_request_url = final_data.gclid.isin(final_data['Gclid from request url'])
mask_gclid_cloudflare_cookie = final_data.gclid.isin(final_data['Gclid from cookie'])

finalized_export.loc[~mask_gclid_cloudflare_request_url, ['Date from Cloudflare']] = ''
finalized_export.loc[~mask_gclid_cloudflare_cookie, ['Date from Cloudflare']] = ''

How would I check if for example value 1 from column C exists in either column A or column B using the .isin() method?

Thank you for your suggestions

Upvotes: 4

Views: 9140

Answers (1)

jezrael
jezrael

Reputation: 862406

If want boolean DataFrame in output simplier is compare by value without isin:

#if 1 is string use '1'
#df1 = df[['A','B']].eq('1')
df1 = df[['A','B']].eq(1)

df1 = (df[['A','B']] == 1)

With DataFrame.isin only pas one element list with 1:

df1 = df[['A','B']].isin([1])

print (df1)
       A      B
0   True  False
1  False  False
2  False  False
3  False   True

For mask (Series) use one one 2 method DataFrame.any for test if at least one True per row:

print (df1.any(axis=1))
0     True
1    False
2    False
3     True
dtype: bool

Or DataFrame.all for test if all Trues per row:

print (df1.all(axis=1))
0    False
1    False
2    False
3    False
dtype: bool

Upvotes: 8

Related Questions