Skip to main content
 首页 » 编程设计

python之从 Pandas 列中删除字符

2024年10月01日8qq号

我试图简单地从 pandas 专栏系列的开头和结尾删除“(”和“)”。到目前为止,这是我最好的猜测,但它只返回 () 完好无损的空字符串。

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

该列如下所示: screenshot of jupyter notebook

请您参考如下方法:

工作示例

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
替换

df.location.replace('\(|\)', '', regex=True) 
 
0    hello 
Name: location, dtype: object