如何创建替换单词的功能

时间:2019-07-08 20:09:37

标签: python pandas

我有一个包含两列的df:ORIGIN,DESTINATION

我想做些替换。

一个是包含“字符串”并替换

# assume string contains 'UK|Heathrow' is 'London Heathrow Airport'

dis_air.loc[dis_air['ORIGIN'].str.contains('UK|Heathrow'), 'ORIGIN'] = 'London Heathrow Airport'
dis_air.loc[dis_air['DESTINATION'].str.contains('UK|Heathrow'), 'DESTINATION'] = 'London Heathrow Airport'


# assume string contains 'Gatwick' is 'London Gatwick Airport'
dis_air.loc[dis_air['ORIGIN'].str.contains('Gatwick'), 'ORIGIN'] = 'London Gatwick Airport'
dis_air.loc[dis_air['DESTINATION'].str.contains('Gatwick'), 'DESTINATION'] = 'London Gatwick Airport'

一个等于'string'并替换

# assume 'London' is 'Heathrow'
dis_air.ORIGIN_new [dis_air.ORIGIN_new == 'London'] = 'London Heathrow Airport'
dis_air.DESTINATION_new [dis_air.DESTINATION_new == 'London'] = 'London Heathrow Airport'

可以帮忙创建两个函数,然后我只需输入a和b两个参数即可实现结果。 a是需要替换的字符串,b是替代字符串。

1 个答案:

答案 0 :(得分:0)

pandas中已经有一个函数可以做到这一点。

dis_air['ORIGIN'].replace('UK|Heathrow','London Heathrow Airport',inplace=True)