2

There is currently a stack overflow answer that explains how to remap Remap values in pandas column with a dict for single value columns. I am wondering how to extend this to columns composed of lists efficiently

 di = {1: "A", 2: "B"}
     col1   col2
0       w      a
1       [1,2]      2
2       [2,2]    NaN        

transform to this 
 col1   col2
0       w      a
1       [A,A]      2
2       [B,B]    NaN
knowads
  • 705
  • 2
  • 7
  • 24

1 Answers1

2

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]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252