扬帆大鱼
list comprehension与replace和 一起使用split:df['col2'] = [a.replace(b, '').strip() for a, b in zip(df['col2'], df['col3'])]print (df) col1 col2 col30 A berry black1 B apple green2 C wine red如果顺序不重要,则将拆分的值转换为集合并减去:df['col2'] = [' '.join(set(a.split())-set([b])) for a, b in zip(df['col2'], df['col3'])]print (df) col1 col2 col30 A berry black1 B apple green2 C wine red或者使用带有if条件和的生成器join:df['col2'] = [' '.join(c for c in a.split() if c != b) for a, b in zip(df['col2'], df['col3'])]性能:这是用于生成上面的perfplot的设置:def calculation(val): return val[0].replace(val[1],'').strip()def regex(df): df.col2=df.col2.replace(regex=r'(?i)'+ df.col3,value="") return dfdef lambda_f(df): df["col2"] = df.apply(lambda x: x["col2"].replace(x["col3"], "").strip(), axis=1) return dfdef apply(df): df['col2'] = df[['col2','col3']].apply(calculation, axis=1) return dfdef list_comp1(df): df['col2'] = [a.replace(b, '').strip() for a, b in zip(df['col2'], df['col3'])] return dfdef list_comp2(df): df['col2'] = [' '.join(set(a.split())-set([b])) for a, b in zip(df['col2'], df['col3'])] return dfdef list_comp3(df): df['col2'] = [' '.join(c for c in a.split() if c != b) for a, b in zip(df['col2'], df['col3'])] return dfdef make_df(n): d = {'col1': {0: 'A', 1: 'B', 2: 'C'}, 'col2': {0: 'black berry', 1: 'green apple', 2: 'red wine'}, 'col3': {0: 'black', 1: 'green', 2: 'red'}} df = pd.DataFrame(d) df = pd.concat([df] * n * 100, ignore_index=True) return dfperfplot.show( setup=make_df, kernels=[regex, lambda_f, apply, list_comp1,list_comp2,list_comp3], n_range=[2**k for k in range(2, 10)], logx=True, logy=True, equality_check=False, # rows may appear in different order xlabel='len(df)')