我有一个带有“用途”列的dataframe,它有很多字符串值,我想通过查找一个字符串并替换它来标准化它。
例如,购买汽车、购买二手车、购买自己的汽车、购买二手车、购买汽车等都是非常相似的价值。
我使用了以下方法来进行此更改:
#用“车辆”代替任何与购买汽车有关的东西
credit_data['purpose'] = credit_data.purpose.str.replace(r'(^.*car.*$)','Vehicle')而且效果很好,所有这些值都被“车辆”所取代。
在这个专栏中,我对其他类型的教育也有一些类似的条件,比如教育--补充教育、教育、接受教育、获得补充教育、大学教育等等。
因此,我查找了regex语法,并提出了以下内容:
#将与教育有关的任何事情改为“教育”
credit_data['purpose'] = credit_data.purpose.str.replace(r'(^.*education|university|educated.*$)','Education')这样做的结果和上面所说的“现在教育”是相似的--耶!
这就引出了我的问题--我把它应用到其他字符串的某个地方出了问题--例如,我对房地产使用了类似的方法:
#用房地产代替任何与房地产有关的东西
credit_data['purpose'] = credit_data.purpose.str.replace(r'(^.*real estate|housing|house|property.*$)','Real Estate')我的结果是不同的--我从购买我自己的房子,建造房子,购买房产等值开始,所有的方法似乎都只是替换我识别的字符串,而不是用替换字符串替换整个字符串。
所以,我没有一堆写着“房地产”的条目,我有很多条目,比如购买我自己的房地产,建造一个房地产,购买一个房地产,等等。
我不知道我哪里出了问题?
提前谢谢。
编辑以从dataframe中添加请求的系列:
Df = [purchase of the house, car purchase, supplementary education, to have a wedding, housing, transactions, education, having a wedding, purchase of the house for my family, buy real estate, buy commercial real estate, buy residential real estate, construction of own property, property, building a property, buying a second-hand car, buying my own car, transactions with commercial real estate, building a real estate, housing, transactions with my real estate, cars, to become educated, second-hand car purchase, getting an education, car, wedding ceremony, to get a supplementary education, purchase of my own house, real estate transactions, getting higher education, to own a car, purchase of a car, profile education, university education, buying property for renting out, to buy a car, housing renovation, going to university]
发布于 2020-11-14 03:36:55
您使正则表达式过于限制性,并且使用错误的字符进行替换。您可以使用\b来匹配单词边界,使用|匹配多个模式,使用IGNORECASE来处理案例问题。所以,例如
credit_data.purpose.str.replace(r'\b(real estate|housing|house|property)\b',
'Real Estate', regex=True, flags=re.IGNORECASE)如果要替换整个字符串,可以使用所有点(.*)。
credit_data.purpose.str.replace(r'.*(real estate|housing|house|property).*',
'Real Estate', regex=True, flags=re.IGNORECASE)https://stackoverflow.com/questions/64830587
复制相似问题