i am quit new to Python and also in stack overflow. This platform is quit helpful for me to get what i wanted to perform code wise. I am working on a dataframe in pandas and I want to replace a part of string only if it is followed by / or - or *
. the sample string is-
MAA-BOM/MADRAS
.
I want to replace MAA to MADRAS, BOM to BOMBAY, MAD to MADRID
. so the desired output will be like MADRAS-BOMBAY/MADRAS
. I want only MAA and BOM to be replaced while MAD in MADRAS should remain intact
. I was using .replace()
with dictionary but this is not giving me desired output.
Any help is much appreciated.
Thanks in advance.
Build a dictionary of mappings:
m = {'MAA' : 'MADRAS', 'BOM': 'BOMBAY', 'MAD' : 'MADRID'}
Now, call str.replace
on your column:
df['Col'] = df['Col'].str.replace(r'.*?(?=[/*-])',
lambda x: m.get(x.group(), None))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.