简体   繁体   中英

How to substract string row wise in Pandas

I like to subtract a string from another string in the same row. in the example below, I like to remove oroville from "oroville 1974 honda st 90 very clean" and then create a new column with the remaining.

In fact I like to repeat the same for all rows and like to and up with "honda st 90 very clean" on the first row. There is as usually False, NaN or zeros in the dataframe which may create problems.

I have the dict provided below. Thank you for your help!

mydict={'brand': ['honda', 'yamaha', False, 'ktm ', 'yamaha'],'city': ['oroville', 'chico', 'chico', 'chico', 'red bluff'],'listing': ['oroville 1974 honda st 90 very clean','d/chico 2018 yamaha vino 50 classic','chico 2001 zrx1200r for sale','chico ktm 620 lc4', 'red bluff 2006 yamaha raptor 350'],'year': ['1974', '2018', '2001', 0, '2006']}

df=pd.DataFrame(mydict)

数据框

The solution below uses just the method Pandas.Series.replace() adding the content to a new column:

df['new_column'] = df.listing.replace(df.city, '', regex = True).replace(df.year, '', regex = True)

With the following result:

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM