Comparing two cell values and extracting the difference

Viewed 90

enter image description here

Trying to compare two cell values. Per topic I need to screen whether the Old countries and New countries list is exactly the same or whether there are new countries added in the new one or deleted and then I want a third column which identifies which countries have been added or deleted.

1 Answers

Here's a working example (for one of your requests). You can alter func to achieve whatever you want. As is, it gets the elements in column 2 that are not in column 1.

import pandas as pd

# some data that is in the same format as your image
df = pd.DataFrame()
df['Col1'] = ['A;E;I;O;U']
df['Col2'] = ['A;B;C;D;E']

# function to find the differences between two sets
def func(string1,string2):
    string1_split = string1.split(';')
    string2_split = string2.split(';')
    return [x for x in set(string2_split) if x not in set(string1_split)]

# apply the function to the two columns
df['Col3'] = df.apply(lambda x: func(x['Col1'], x['Col2']), axis=1)

df[Col3] outputs:

['B','C','D']
Related