Python 从列中删除字符
我试图简单地从pandas专栏的开头和结尾删除“(”和“)”。这是我目前为止最好的猜测,但它只返回空字符串,而()保持不变Python 从列中删除字符,python,regex,pandas,Python,Regex,Pandas,我试图简单地从pandas专栏的开头和结尾删除“(”和“)”。这是我目前为止最好的猜测,但它只返回空字符串,而()保持不变 postings['location'].replace('[^\(.*\)?]','', regex=True) 该列如下所示: 您使用[^\(.*)?]所做的是匹配除字符类中提到的字符以外的所有其他字符^在字符类中表示对该集求反 应尝试使用^\(|\)$并替换为”,即空字符串 工作示例 df = pd.DataFrame(dict(location=['(hello)
postings['location'].replace('[^\(.*\)?]','', regex=True)
该列如下所示:
您使用
[^\(.*)?]
所做的是匹配除字符类中提到的字符以外的所有其他字符^
在字符类中表示对该集求反
应尝试使用^\(|\)$
并替换为”
,即空字符串
工作示例
df = pd.DataFrame(dict(location=['(hello)']))
print(df)
location
0 (hello)
@Psidom的解决方案str.strip
选项2str.extract
选项3str.replace
选项4更换
如果只想从字符串的开头或结尾删除字符,则不需要正则表达式<代码>条带就足够了<代码>帖子['location'].str.strip(“()”)谢谢!选择4奏效了。在我的jupyter笔记本中,大多数其他选项只移除了结束支架,而没有移除开始支架。
df.location.str.strip('()')
0 hello
Name: location, dtype: object
df.location.str.extract('\((.*)\)', expand=False)
0 hello
Name: location, dtype: object
df.location.str.replace('\(|\)', '')
0 hello
Name: location, dtype: object
df.location.replace('\(|\)', '', regex=True)
0 hello
Name: location, dtype: object