Python Pandas - How to check if a "tuple" of two Series elements is contained in a set?

Asked

Viewed 126 times

1

I have a "set" of "tuples" as follows set = {(2, 3), (2, 4), (5, 5)}

My Dataframe is like this:

df = pd.DataFrame( {'one': [1,2,4,1], 'two' : [5,3,2,2]})

I want to check if in each row the "tuple" formed by the elements of the two series is contained in the set. The desired result would be this:

df = pd.DataFrame({'one': [1,2,4,1], 'two' : [5,3,2,2], 'three' : [False, True, False, False]})

I tried to:

df['three'] =  ((df['one'], df['two']) in set)

It did not work and gave me the following error message: 'Series' Objects are mutable, Thus they cannot be hashed"

How to achieve the desired result? Thank you

  • We are in [en.so], could translate your question?

  • Wow, I didn’t notice. I’m gonna fix this.

2 answers

0

I found a solution:

df['A'] = list(zip(df.one, df.two))
df['three'] = df['A'].isin(set)
  • Ruan, The idea of zip is good but it seems to me that would not work the isin... Could you confirm?

0

Using zip and lists in understanding:

z=zip(......)
df['three'] = [x in set for x in z]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.