我有一本字典
My_dict={'RED':'fruit', 'BLUE':'fish', 'GREEN':'colur'}
和一个数据帧Df
Col1| Col2|
|:--------|:-------|
|12| There are red trees in the forest|
|13|The sky is BLUE|
|14|The grasses are Green|
我需要检查数据帧中的单词是否与键匹配,以及是否匹配转换为大写
Df是
Col1| Col2|
|:--------|:-------|
|12| There are RED trees in the forest|
|13|The sky is BLUE|
|14|The grasses are GREEN|
一种方法:
df["Col2"] = df["Col2"].str.replace(rf"(?i)b({'|'.join(map(str.lower, my_dict))})b", repl=lambda x: x.group().upper(), regex=True)
print(df)
Col1 Col2
0 12 There are RED trees in the forest
1 13 The sky is BLUE
2 14 The grasses are GREEN
作为替代使用case
参数(如@jezrael所建议的):
df["Col2"].str.replace(rf"b({'|'.join(map(str.lower, my_dict))})b", repl=lambda x: x.group().upper(), regex=True, case=False)