1

I have a data frame, called a, that has the following structure:

df = pd.DataFrame({
    'id': [1, 2, 3],
    'numbers_a': [[2, 3, 5], [1, 2, 4], [4, 6, 9]],
    'numbers_b': [[2, 1, 3], [10, 11], [4, 5, 7]]
})
df

| id | numbers_a | numbers_b |
|----|-----------|-----------|
| 1  | [2, 3, 5] | [2, 1, 3] |
| 2  | [1, 2, 4] | [10, 11]  |
| 3  | [4, 6, 9] | [4, 5, 7] | 

I want to add a new column to this data frame, called result, that should be TRUE if any one value in numbers_b are in numbers_a. Therefore, the following should be the resultant data frame:

| id | numbers_a | numbers_b | result |
|----|-----------|-----------|--------|
| 1  | [2, 3, 5] | [2, 1, 3] | TRUE   |
| 2  | [1, 2, 4] | [10, 11]  | FALSE  |
| 3  | [4, 6, 9] | [4, 5, 7] | TRUE   | 

I have tried to use the following code snippet, but I am getting FALSE for all values:

a['result'] = pd.DataFrame(a.numbers_b.tolist()).isin(a.numbers_a).any(1).astype(bool)

How do I solve this? Thanks in advance.

1 Answer 1

3

Try set intersection:

df['numbers_a'].map(set) & df['numbers_b'].map(set)

0     True
1    False
2     True
dtype: bool

This works well with the overloaded pandas boolean operators, although it isn't particularly performant.


Another method involves list comprehensions:

[set(a).intersection(b) for a, b in zip(df['numbers_a'], df['numbers_b'])]
# [True, False, True]

# To assign the result back
df['result'] = [
    set(a).intersection(b) for a, b in zip(df['numbers_a'], df['numbers_b'])]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.