1 回答
TA贡献1802条经验 获得超5个赞
您可以使用extractall提取字典中的所有键,并groupby().last()获取最后的键:
pattern=rf'\b({"|".join(some_dictionary.keys())})\b'
last_keys = df_1['category'].str.extractall(pattern)[0].groupby(level=0).last()
# or
# df_1['category'].str.findall(pattern).str[-1]
df_1['description'] = last_keys.map(some_dictionary)
更新:您还可以使用此模式来提取最后一次出现str.extract:
pattern=rf'(?s:.*)\b({"|".join(some_dictionary.keys())})\b'
last_keys = df_1['category'].str.extract(pattern)
输出:
category owner description
0 [AA, pik(BB)] Teagra Billion Bobs
1 [(gem(BB), CC)], ril[DD] Jenny Double Dwarfs
2 hur[AA, (EE)] Justin Eleven Elfs
3 zonk[EE, DD, CC, (BB], lux(AA)) Ray Alot Anacondas
添加回答
举报