python - 删除 pandas 系列中以特定字符串开头的所有文本

标签 python regex pandas string substring

我有以下名为“places”的 df

                   place_name
0                 "Palais et bâtiments officiels[modifier | modifier le code]"
1                 "Lieux de culte renommés[modifier | modifier le code]"
2                 "Vestiges gallo-romains[modifier | modifier le code]"

正如你所看到的,有一个类似的子字符串 [modifier |修饰符 le code] 在地方 [“place_name] 的所有输入中,我想删除子字符串。

我尝试了以下两种技术

places["place_name"] = places["place_name"].apply(lambda x: re.sub("\\[modifier \\| modifier le code\\]", "", x))

places["places_name"] = places["place_name"].str.replace("[modifier | modifier le code]", "", regex=False) 

这些都不起作用,因为我认为问题是我试图删除的子字符串与另一个子字符串粘在一起(请注意,开头没有空格),所以我认为代码本身不会将其识别为字符串。我一直在尝试使用 split() 方法拆分它,但我遇到了同样的问题,因为我尝试删除的字符串开头没有空格。

最终输出应该是

                   place_name
0                 "Palais et bâtiments officiels"
1                 "Lieux de culte renommés"
2                 "Vestiges gallo-romains"

我尝试寻找其他解决方案,但找不到任何解决方案,我知道有很多关于字符串的问题,但找不到具体的解决方案。

最佳答案

您应该使用Series.str.split :

places["place_name"] = places["place_name"].str.split('\\[modifier').str[0]

基本上,将字符串拆分为 '[modifier' 并选择第一个值([0]]

关于python - 删除 pandas 系列中以特定字符串开头的所有文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64738100/

相关文章:

javascript - 正则表达式允许输入字段中有 4 个数字(任意长度)

regex - Bash - 从不包含特定模式的文件中获取行

python-3.x - X的imputer = imputer.fit(X [:,1:3])代表什么?imputer.fit(X [:,1:3])的含义是什么?

Python,根据应用于相同长度的现有列表的条件创建新列表

python - 响应所有方法调用的 Python 类的实例

python - httmock 在运行 tox 时不拦截 requests.send()

python - 根据来自另一列 pandas 的相同或更接近的值替换列中的值

python - 鼠标悬停时显示文本 - 标题元素不一致,标题属性不执行任何操作

regex - 在 sed 或 egrep 的帮助下获取定义的子字符串

Python Pandas,从一列聚合多列