如果想更换,如果在列表中匹配值,用get
在列表理解与筛选器列表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
还有一些其他解决方案,如果不匹配,会发生什么情况,请添加3
到列表中:
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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句