简体   繁体   English

如何在 Pandas 中按行减去字符串

[英]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.在下面的示例中,我喜欢从“oroville 1974 honda st 90非常干净”中删除oroville,然后用剩余的创建一个新列。

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.事实上,我喜欢对所有行重复相同的操作,并且喜欢在第一行使用“honda st 90 very clean”。 There is as usually False, NaN or zeros in the dataframe which may create problems.数据帧中通常存在 False、NaN 或零,这可能会产生问题。

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']} mydict={'brand': ['honda', 'yamaha', False, 'ktm', 'yamaha'],'city': ['oroville', 'chico', 'chico', 'chico', 'red bluff'],'listing': ['oroville 1974 本田 st 90 非常干净','d/chico 2018 yamaha vino 50 经典','chico 2001 zrx1200r 出售','chico ktm 620 lc4','red 06 yamaha 2猛禽 350'],'年份': ['1974', '2018', '2001', 0, '2006']}

df=pd.DataFrame(mydict) df=pd.DataFrame(mydict)

数据框

The solution below uses just the method Pandas.Series.replace() adding the content to a new column:下面的解决方案仅使用Pandas.Series.replace()方法将内容添加到新列:

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

With the following result:结果如下:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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