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.