代码之家  ›  专栏  ›  技术社区  ›  daiyue

使用另一列从左到右匹配字符串

  •  0
  • daiyue  · 技术社区  · 6 年前

    我有一个 df ,我喜欢搭配 amount 从左开始 inv_id ,并创建一个布尔列 left_match True -如果有匹配的话, False -其他方面,

    amount    inv_id        
    309.9     30990071218
    3130.0    313000B20180501
    3330.50   3330.5020180425
    17.35     13249261 100117
    43.2      9037878 020418
    

    我将从中删除任何非数字字符 发票id 第一,

    s = df[inv_id].str.replace(r'\D+', '')
    

    amount * 100

    df['amt_str'] = (df['amount']*100).round().astype(int).astype(str) 
    

    我想知道如何使用 amt_str s . 结果应该是,

    amount    inv_id             left_match        
    309.9     30990071218        True
    3130.0    313000B20180501    True
    3330.50   3330.5020180425    True
    17.35     13249261 100117    False
    43.2      9037878 020418     False
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   Naga kiran    6 年前
    df['left_match'] = df.apply(lambda x:True if re.search(str(x['amount']).split('.')[0],x['inv_id']).start() ==0 else False,axis=1)
    df
    

    输出:

    amount  inv_id  left_match
    0   309.90  30990071218 True
    1   3130.00 313000B20180501 True
    2   17.35   13249261 100117 False
    
        2
  •  1
  •   pietroppeter    6 年前
    df['inv_id_numeric'] = df['inv_id'].str.replace(r'\D+', '')
    df['amt_str'] = (df['amount']*100).round().astype(int).astype(str)
    df['left_match'] = df.apply(lambda x: x['inv_id_numeric'].startswith(x['amt_str']), axis=1)
    

    输出:

        amount           inv_id  inv_id_numeric amt_str  left_match
    0   309.90      30990071218     30990071218   30990        True
    1  3130.00  313000B20180501  31300020180501  313000        True
    2  3330.50  3330.5020180425  33305020180425  333050        True
    3    17.35  13249261 100117  13249261100117    1735       False
    4    43.20   9037878 020418   9037878020418    4320       False
    
        3
  •  1
  •   Space Impact    6 年前

    df['inv_id_temp'] = df['inv_id'].str.replace('.','')
    df['left_match'] = df.apply(lambda x: x['amt_str']==x['inv_id_temp'][:len(x['amt_str'])],1)
    
    df[['amount', 'inv_id','left_match']]
    
        amount  inv_id          left_match
    0   309.90  30990071218     True
    1   3130.00 313000B20180501 True
    2   3330.50 33305020180425  True
    3   17.35   13249261 100117 False
    4   43.20   9037878 020418  False