If want replace if match values in lists use get
in list comprehension with filter list by isinstance
:
f = lambda x: [di.get(y,y) for y in x] if isinstance(x, list) else x
df['col1'] = df['col1'].apply(f)
print (df)
col1 col2
0 w a
1 [A, B] 2
2 [B, B] NaN
There are some another solutions whats happens if no match, added 3
to list:
print (df)
col1 col2
0 w a
1 [1, 2] 2
2 [2, 2, 3] NaN
#if no match return original, here 3
f1 = lambda x: [di.get(y,y) for y in x] if isinstance(x, list) else x
df['col11'] = df['col1'].apply(f1)
#if no match return None
f2 = lambda x: [di.get(y,None) for y in x] if isinstance(x, list) else x
df['col12'] = df['col1'].apply(f2)
#if no match remove not match value
f3 = lambda x: [di[y] for y in x if y in di] if isinstance(x, list) else x
df['col13'] = df['col1'].apply(f3)
print (df)
col1 col2 col11 col12 col13
0 w a w w w
1 [1, 2] 2 [A, B] [A, B] [A, B]
2 [2, 2, 3] NaN [B, B, 3] [B, B, None] [B, B]