【问题标题】:remove characters from pandas column从熊猫列中删除字符
【发布时间】:2017-10-01 18:08:45
【问题描述】:

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

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

该列如下所示: screenshot of jupyter notebook

【问题讨论】:

  • 如果您只想从字符串的开头或结尾删除字符,则不需要正则表达式。 strip 应该足够了。 postings['location'].str.strip("()")

标签: python regex pandas


【解决方案1】:

工作示例

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

【讨论】:

  • 谢谢!选项 4 奏效。大多数其他选项仅删除右括号,而不是我的 jupyter 笔记本中的左括号。
【解决方案2】:

您对[^\(.*\)?] 所做的是匹配除您在字符类中提到的所有其他字符^ 在字符类中表示否定该集合。

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

Regex101 Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2021-03-16
    • 2021-09-25
    • 2016-10-21
    • 2017-07-27
    • 2023-01-11
    • 2022-12-07
    相关资源
    最近更新 更多