John Mack
John Mack

Reputation: 41

create new column in dataframe that subtract a column with list from another column with list

I have a dataframe that contains 2 column and I would like to create a third one that remove values in first column contained in 2nd column:

list_first list_second
[1,2,3] [3]
[4,7,8,9] [4,9]

output desired

list_first list_second list_third
[1,2,3] [3] [1,2]
[4,7,8,9] [4,9] [7,8]

Upvotes: 0

Views: 115

Answers (1)

jezrael
jezrael

Reputation: 862911

Use list comprehension for difference between lists:

df['list_third'] = [[x for x in a if x not in b] for a, b in df[['fist_first','list_second']].to_numpy()]
print (df)
     fist_first list_second list_third
0     [1, 2, 3]         [3]     [1, 2]
1  [4, 7, 8, 9]      [4, 9]     [7, 8]

Upvotes: 1

Related Questions