尝试清除“名称”列中“模型”值后面的错误文本。
df = pd.DataFrame([['ABC-12(s)', 'Some text ABC-12(s) wrong text'], ['ABC-45', 'Other text ABC-45 garbage text'], ['XYZ-LL', 'Another text XYZ-LL unneeded text']], columns = ['Model', 'Name'])
预期结果:
尝试过:
df["name"] = df["name"].str.partition(df["model"].to_string(), expand=False)
但这会返回原始字符串,没有任何更改或错误。就像它无法在“名称”单元格中找到分隔符一样。 看来我错过了一些非常简单的事情。
最佳答案
另一种解决方案,使用 re:
import re
df["Name"] = df.apply(
lambda x: re.split(r"(?<=" + re.escape(x["Model"]) + r")\s*", x["Name"])[0],
axis=1,
)
print(df)
打印:
Model Name
0 ABC-12(s) Some text ABC-12(s)
1 ABC-45 Other text ABC-45
2 XYZ-LL Another text XYZ-LL
关于Python pandas 从字符串中删除子字符串之后的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68717925/