Have a dataframe with a list column like and two reference lists:
d = {'col1': [1,2,3,4,5], 'col2':[['a','b'],['a','b'],['a','b','c'],['a','b','d'], ['a','b','e']]}
df = pd.DataFrame(data=d)
ref_a = ['c','d','e','f']
ref_b = ['option1', 'option2', 'option3', 'option4']
col1 col2
0 1 [a, b]
1 2 [a, b]
2 3 [a, b, c]
3 4 [a, b, d]
4 5 [a, b, e]
And I want to create a third column that checks if a value in col2 is in ref_a and return the matched item in ref_b
col1 col2 check
0 1 [a, b]
1 2 [a, b]
2 3 [a, b, c] option1
3 4 [a, b, d] option2
4 5 [a, b, e] option3
I've tried something like this:
for index, row in df.iterrows():
for (a, b) in zip(ref_a, ref_b):
if a in row['col2']:
df.loc[index, 'check'] = b
print('true', b)
else:
df.loc[index, 'check'] = ''
And that prints out what I'm anticipating, but doesn't change the actual value, I don't have a large amount of data to iterate over but also not sure if there is a more elegant approach. There will only be one match in the list column, never multiple options.