【问题标题】:Create new column returning true/false if names in two columns match using regex如果两列中的名称使用正则表达式匹配,则创建返回 true/false 的新列
【发布时间】:2019-04-09 04:35:53
【问题描述】:

我有一个数据框,我在其中尝试匹配两列的列字符串值以创建一个新列,如果两列值匹配则返回 true,否则返回 false。 想要使用匹配和正则表达式,删除所有非字母数字字符并使用小写来匹配名称

pattern = re.compile('[^a-zA-Z]')

    Name A         Name B
0   yGZ,)          ygz.
1   (CGI)          C.G.I
2   Exto           exto.
3   Golden         UTF

我正在考虑尝试这样的事情:

dataframe['Name A', 'Name B'].str.match(pattern, flags= re.IGNORECASE)

    Name A         Name B    Result
0   yGZ,)          ygz.       True
1   (CGI)          C.G.I      True
2   Exto           exto.      True
3   Golden         UTF        False

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    可以使用pd.DataFrame.replace 清理您的字符串,然后使用eq 进行比较。当然,如果您希望保留原始df 的副本,只需将返回的数据框分配给一个新变量;}

    df = df.replace("[^a-zA-Z0-9]", '', regex=True)
    

    然后

    df['Result'] = df['Name A'].str.lower().eq(df['Name B'].str.lower())
    

    输出

        Name A  Name B  Result
    0   yGZ     ygz     True
    1   CGI     CGI     True
    2   Exto    exto    True
    3   Golden  UTF     False
    

    【讨论】:

    • 对于外来字符,清理后的列显示为空白,有什么解决办法吗?
    • @TH14 您只需先对列进行切片以在感兴趣的数据框中应用替换...例如,df[cols].replace(...) 其中cols=['Name A', 'Name B'] 例如。
    【解决方案2】:

    您可以使用str.replace 删除标点符号(另见我的另一篇文章,Fast punctuation removal with pandas),然后

    u = df.apply(lambda x: x.str.replace(r'[^\w]', '').str.lower())
    df['Result'] = u['Name A'] == u['Name B']
    df
    
       Name A Name B  Result
    0   yGZ,)   ygz.    True
    1   (CGI)  C.G.I    True
    2    Exto  exto.    True
    3  Golden    UTF   False
    

    【讨论】:

    • 我收到此错误 AttributeError: ('Can only use .str accessor with string values, which use np.object_ dtype in pandas', 'occured at index Number') 对不起,我应该提到还有其他具有数值的列
    • @TH14 将第一行更改为:u = df[['Name A', 'Name B']].apply(lambda x: x.str.replace(r'[^\w]', '').str.lower()),它应该可以工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多