我有一个这样的颜色列表:

color = ['green', 'blue', 'red']


我有一个这样的数据框:

df:
col1        col2
 A        dark green
 B        sea blue
 C          blue
 D       exclusive red
 E          green
 F       pale red


我想将col2color列表匹配。如果col2的任何单词与color列表的元素匹配,则将其替换为列表值。

结果数据帧将是

 col1          col2
  A            green
  B            blue
  C            blue
  D            red
  E            green
  F            red


使用熊猫最有效的方法是什么?

最佳答案

对正则表达式Series.str.extract|与连接值使用OR一起使用,最后添加fillna以用原始列替换不匹配的值(NaN s):

print (df)
  col1           col2
0    A     dark green
1    B       sea blue
2    C           blue
3    D  exclusive red
4    E          green
5    F           pale <- not matched value

color=['green','blue','red']

pat = r'({})'.format('|'.join(color))
df['col2'] = df['col2'].str.extract(pat, expand=False).fillna(df['col2'])

print (df)
  col1   col2
0    A  green
1    B   blue
2    C   blue
3    D    red
4    E  green
5    F   pale

关于python - 如果与单词匹配,则用列表替换pandas Dataframe列值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54418326/

10-14 19:54
查看更多