从pandas列中删除字符

7

我试图从Pandas列系列的开头和结尾简单地删除括号“()”。 这是到目前为止我最好的猜测,但它只返回保留了“()”的空字符串。

postings['location'].replace('[^\(.*\)?]','', regex=True)

这一列看起来像这样: jupyter笔记本的截图

6
如果您只想从字符串的开头或结尾删除字符,无需使用正则表达式。使用strip函数就足够了。例如:postings['location'].str.strip("()") - Psidom
2个回答

13

工作示例

df = pd.DataFrame(dict(location=['(hello)']))

print(df)

  location
0  (hello)

@Psidom的解决方案
str.strip

df.location.str.strip('()')

0    hello
Name: location, dtype: object
选项2
str.extract
df.location.str.extract('\((.*)\)', expand=False)

0    hello
Name: location, dtype: object
选项 3
str.replace
df.location.str.replace('\(|\)', '')

0    hello
Name: location, dtype: object

选项4
replace

df.location.replace('\(|\)', '', regex=True)

0    hello
Name: location, dtype: object

1
谢谢!选项4有效。其他大多数选项只会删除我的Jupyter笔记本中的闭合括号,而不是开放括号。 - Keenan Burke-Pitts

0

你正在使用的是[^\(.*\)?],它的作用是匹配除了你在字符类中指定的所有其他字符。字符类内的^表示对该集合取反。

应该尝试使用^\(|\)$并用""即空字符串替换。

Regex101演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接