如何删除DataFrame字符串中VIN及右侧所有内容?
解决DataFrame中删除"Vin"及右侧内容的问题
针对你需要移除Description列里"Vin"及其右侧所有内容的需求,这里提供两种简单可行的pandas处理方案:
方法一:使用字符串分割
利用str.split()按第一个"Vin"分割字符串,取左侧部分并清理空格:
import pandas as pd # 假设你的DataFrame名为df df['Description'] = df['Description'].str.split('Vin', n=1).str[0].str.strip()
n=1确保只分割一次,避免遇到多个"Vin"时出错str.strip()用来去除分割后末尾多余的空格
方法二:使用正则表达式提取
通过str.extract()匹配"Vin"之前的内容,同时兼容没有"Vin"的行:
df['Description'] = df['Description'].str.extract(r'(.*?)\s*Vin', expand=False).fillna(df['Description'])
- 正则
(.*?)\s*Vin采用非贪婪模式,精准匹配到"Vin"前的所有内容 fillna(df['Description'])保证没有"Vin"的行保留原始内容
处理后效果示例
处理后的Description列内容会变为:
Install Ceramic Film on the front 2 roll up on a 18 CX-5
Install Ceramic Film on the front 2 roll up on a 18 Terrain
Install Ceramic Film on the front 2 roll up on a 18 Terrain
Install Ceramic Film on the front 2 roll up on a 18 Yukon
Install Ceramic Film on the front 2 roll up on a 19 1500
Install Ceramic Film on the front 2 roll up on a 19 1500
Install Ceramic Film on the front 2 roll up on a 19 Blazer
内容的提问来源于stack exchange,提问作者codingnewbie
相关产品推荐
相关产品推荐

