Pandas数据表剔除TG_plus列TG前缀的非循环实现方案咨询
Pandas非循环实现方案
我们可以用以下三种方案替代原生循环,性能和可读性都更好,按推荐优先级排序:
方案1:使用str.removeprefix(推荐,Pandas 1.4.0+支持)
这是专门用于移除前缀的方法,逻辑最直观,不会误删中间出现的相同内容:
# 移除TG列的CG前缀,strip用来去掉前缀后的多余空格 df["TG"] = df.apply(lambda row: row["TG"].removeprefix(row["CG"]).strip(), axis=1) # 移除TG_plus列的TG前缀 df["TG_plus"] = df.apply(lambda row: row["TG_plus"].removeprefix(row["TG"]).strip(), axis=1)
方案2:字符串切片 + apply(兼容低版本Pandas)
和你原循环逻辑完全一致,用pandas的apply替代手动循环,写法更简洁:
df["TG"] = df.apply(lambda row: row["TG"][len(row["CG"]):].strip(), axis=1) df["TG_plus"] = df.apply(lambda row: row["TG_plus"][len(row["TG"]):].strip(), axis=1)
方案3:纯向量化操作(性能最优,适合大数据量)
完全避免行遍历,性能比apply高10倍以上,适合10万行以上的大表:
# 处理TG列 cg_length = df["CG"].str.len() df["TG"] = df["TG"].str.slice(cg_length).str.strip() # 处理TG_plus列 tg_length = df["TG"].str.len() df["TG_plus"] = df["TG_plus"].str.slice(tg_length).str.strip()
内容的提问来源于stack exchange,提问作者user16795517
相关产品推荐
相关产品推荐

